ch3-Constants in C++ (Redefine non-const link error)
Chapter_3 Exercise_3-10 Constants_in_C | Mathops Exercise_3-11 |
CONTENTS: Const.hpp Const1.cpp Const2.cpp
Const.hpp TCP1, p. 166 download
// char c1; // link error: non-const `c1' redefined in `Const2.cpp'
// char c2 = 'c'; // link error: non-const `c2' redefined in `Const2.cpp'
const int x = 10; // OK
Const1.cpp TCP1, p. 165-166 download
#include "Const.hpp"
#include <iostream>
using std::cout;
using std::endl;
#define PI 3.14
int i; // uninitialized global variable, by default 0
// const char a; // compile error: uninitialized const
const char c = 'c';
const char d = 'd';
const char* cp = &c;
// int* ip = &PI; // compile error: lvalue required as unary `&' operand
const char* const ccp = &c; // const pointer
int main()
{
cout << "PI = " << PI << endl; // keeps value from `Const1.cpp'
cout << "i = " << i << endl; // 0
cout << "c = '" << c << "'" << endl; // keeps value from `Const1.cpp'
cp = &d; // OK, non-const pointer
// *cp = 'e'; // compile error: `d' is const
// ccp = &d; // compile error: const pointer
return 0;
}
/*
g++ -c Const1.cpp Const2.cpp // make (create) object files
g++ -c Const*.cpp
g++ Const*.o -o Const // link object files, make executable
rm Const*.o // clean (delete object files)
./Const
PI = 3.14
i = 0
c = 'c'
*/
Const2.cpp download
#include "Const.hpp" // const `x' redefined OK
#define PI 3.14159 // redefining `PI' is OK
// int i; // link error: non-const `i' redefined
const char c = 'd'; // const `c' redefined OK
// const char* cp = &c; // link error: non-const pointer `cp' redefined
const char* const ccp = &c; // const pointer `ccp' redefined OK
/*
g++ -c Const2.cpp // make (create) object file
*/
Chapter_3 Exercise_3-10 Constants_in_C | BACK_TO_TOP | Mathops Exercise_3-11 |
Comments
Post a Comment