I have two .c files and one .h file included from them both. In the .h file, I have declared global constants. When building with gcc, I get linking problems, telling me that the constants are defined twice, even though I have
#ifndef __FOO
#define __FOO
const struct foo bar = ...
#endif
I get
/tmp/ccql6KF1.o:(.rodata+0x0): multiple definition of `bar'
However, compiling the very same code with g++ works perfectly. Is there some differences in the way C and C++ treats global constants declared in .h files? What approach should I consider?
Please note that all objects need to share the memory for the constants, since I have limited resources.
You should declare the constant in a
.hfile and define it in a single.cfile:bar.h:
bar.c:
Then include
bar.heverywhere you want to accessbar:something.c:
Edit (by Shahbaz): The reason why this works and your code doesn’t work is that when you include a file, the contents of that file are copy pasted in place of #include (this is regardless of the file, you can include anything, including files with .h extension is just a convention). So when you say
const struct foo bar;in a header file and include it in two files, it’s exactly like writing that line in both files, therefore defining the variable in both files and hence the link error.Your header protection also doesn’t work (the
) because each of your source files are compiled separately, therefore when bar.h is included in one file and
__BAR_H__defined, when the next file is being compiled this definition of__BAR_H__is lost.