0

I am trying out standard method of guarding a .h (example:checkpgm.h) file with guard variables as follows

#ifndef _CHECKPGM
#warning CHECKPGM value is 0
#define _CHECKPGM 1
char a;
#endif

This code is included in two files checkmain.c and checksub.c

When these two files are linked I get the error message

Building target: checkpgm
Invoking: GCC C Linker
gcc  -o "checkpgm" ./src/checkmain.o ./src/checksub.o   
/usr/bin/ld: ./src/checksub.o:/home/nagesh/eclipse-workspace/multi/checkpgm/Debug/../src/checkpgm.h:18: multiple definition of `a'; ./src/checkmain.o:/home/nagesh/eclipse-workspace/multi/checkpgm/Debug/../src/checkpgm.h:18: first defined here

I am unable to understand how this is happening in-spite of guarding.

I tried

  1. Changing #define _CHKPGM to #define _CHKPGM 1 (explicit value assignment)
  2. Similarly, #if _CHKPGM == 0
  3. Checking with #if defined
  4. Adding _CHECKPGM with -D flag (Undefined)
  5. Somehow standard libraries are not having this problem (stdio.h, stdlib.h); So copied their style _BEGIN_DECLS...
  6. By warning messages, it is clear that _CHECKPGM gets assigned in its first inclusion. However This value will be lost when compilation of second program begins and hence guard fails. But unable to figure out why?.

Can you folks please help us out?

Thanking in advance...

RaviJ

checkpgm.h is included in

RaviJ
  • 1
  • The solution is to not define (or "tentatively define" in this case) externally linked variables or functions inside a header file. Change `char a;` to `extern char a;` and add `char a;` to one of the .c files. – Ian Abbott Feb 10 '21 at 14:36
  • Yes, this resolves issue. I was under the impression that value set in compilation of one file will be retained during other file also. Just to clarify, the guard tried out in original question above, helps if a [.h] is included multiple times in a single file. Ian's solution (answer to question) addresses the cases where same .h is included in multiple files. Thanks Ian. – RaviJ Feb 11 '21 at 09:06

0 Answers0