Variable definition in header files

喜夏-厌秋 提交于 2019-11-27 08:02:25

Header guard protects you from multiple inclusions in a single source file, not from multiple source files. I guess your problem stems from not understanding this concept.

It is not that pre-processor guards are saving during the compile time from this problem. Actually during compile time, one only source file gets compiled into an obj, symbol definitions are not resolved. But, in case of linking when the linker tries to resolve the symbol definitons, it gets confused seeing more than one definition casuing it to flag the error.

One thing that I've used in the past (when global variables were in vogue):

var.h file:

...
#ifdef DEFINE_GLOBALS
#define EXTERN
#else
#define EXTERN extern
#endif
EXTERN int global1;
EXTERN int global2;
...

Then in one .c file (usually the one containing main()):

#define DEFINE_GLOBALS
#include "var.h"

The rest of the source files just include "var.h" normally.

Notice that DEFINE_GLOBALS is not a header guard, but rather allows declaring/defining the variables depending on whether it is defined. This technique allows one copy of the declarations/definitions.

You have two .c files. They get compiled separately. Each one includes your header file. Once. Each one gets a definition. They conflict at link time.

The conventional solution is:

#ifdef DEFINE_SOMETHING
int something = 0;
#endif

Then you #define DEFINE_SOMETHING in only one .c file.

Header guards stop a header file being included multiple times in the same translation unit (i.e. in the same .c source file). They have no effect if you include the file in two or more translation units.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!