I have two .c files and one 开发者_如何学Go.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 .h
file and define it in a single .c
file:
bar.h:
extern const struct foo bar;
bar.c:
#include "bar.h"
/* do this in a single file */
const struct foo bar = ...;
Then include bar.h
everywhere you want to access bar
:
something.c:
#include "bar.h"
void doSomethingWithBar() {
struct *foo something = &bar;
...
}
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
#ifndef __BAR_H__
#define __BAR_H__
... header contents
#endif
) 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.
You should declare only :
const struct foo bar;
and assign it a value in a .c
file.
精彩评论