Search code examples
c++cc-preprocessorguard

C Preprocessor Guards?


I am working on a C project, and am trying to use pre-processor guards as can be used in C++:

#ifndef CONFIG_H
#define CONFIG_H

... exciting stuff in C ....

#endif

Including this in my source appears to have no effect in Visual Studio, as when I include a given file, such as Config.h, in multiple files, the compiler gives me the following errors:

1>main.obj : error LNK2005: _OPCodes already defined in lib.obj
1>main.obj : error LNK2005: _OPTotal already defined in lib.obj
1>main.obj : error LNK2005: _RegCodes already defined in lib.obj
1>main.obj : error LNK2005: _RegTotal already defined in lib.obj
1>main.obj : error LNK2005: _UDSTotal already defined in lib.obj

Could anyone give me any pointers (no pun intended) on this, please?


Solution

  • The guards will prevent defining things twice in a compilation unit. They will not prevent defining the same thing in different compilation units. And the linker messages indicates that it is what occurs _OPCodes for instance is defined in lib and in main.

    Usually, a header should have only declarations for functions and global variables, corresponding definitions would be provided in one of the source files.

    (See for instance What is the difference between a definition and a declaration? for more information)