ch3-Constants in C (Redefine and reinitialize link error)

Chapter_3     Exercise_3-10     Forward Constants_in_C++     Exercise_3-11







CONTENTS:     const.h     const1.c     const2.c




const.h     TCP1, p. 166         download


char c1;
// char c2 = 'c'; // link error: `c2' redefined (reinitialized) in `const2.c'
const int i1;
// const int i2 = 10; // link error: const `i2' redef (reinit) in `const2.c'











const1.c     TCP1, p. 165-166         download


#include "const.h"
#include <stdio.h> // for printf()

#define PI 3.14

int i = 1; // initialized in `const1.c'

const char a; // uninit const OK (by default 0), initialized in `const2.c'
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()
{
printf("PI = %g\n", PI); // keeps value from `const1.c'
printf("i = %d\n", i); // initialized in `const1.c'
printf("a = '%c'\n", a); // 'a', // initialized in `const2.c'

cp = &d; // OK, non-const pointer
// *cp = 'e'; // compile error: `d' is const
// ccp = &d; // compile error: const pointer

return 0;
}
/*
gcc -c const1.c const2.c // make (create) object files
gcc -c const*.c
gcc const*.o -o const // link object files, make executable
rm const*.o // clean (delete object files)
./const
PI = 3.14
i = 1
a = 'a'
*/











const2.c         download


#include "const.h"

#define PI 3.14159 // redefining `PI' is OK

int i; // redefining non-const `i' OK, not reinitialized
const char a = 'a'; // redefining const `a' OK, initialized in `const2.c'
// const char c = 'c'; // link error: const `c' redefined and reinitialized
const char c; // uninitialized redefinition OK
// const char* cp = &c; // link error: `cp' redefined and reinitialized
const char* cp; // `cp' redefined (not reinitialized) OK
//const char* const ccp = &c; // link error: `ccp' redefined and reinitialized
const char* const ccp; // `ccp' redefined (not reinitialized) OK
/*
gcc -c const2.c // make (create) object file
*/









Chapter_3     Exercise_3-10     Forward BACK_TO_TOP Constants_in_C++     Exercise_3-11



Comments

Popular posts from this blog

Contents