Reputation: 17368
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?
Upvotes: 1
Views: 2803
Reputation: 52314
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)
Upvotes: 9
Reputation: 10489
If you have renamed any files you should remove them from the solution and re-add them. Sometimes Visual Studio is a bit weird with this and they will cause linker errors when left in.
Make sure to do a rebuild.
You may also have accidentally included a .cpp
file instead of a .h
file. Double check all the includes just in case.
Upvotes: 0
Reputation: 16509
EDIT: this is based on the original post, which had a typo. It's NOT the OP's real problem, apparently.
You've given your guards two different names. They must match.
#ifndef CONFIG_H
#define CONFIG_H // not CONFIG_G!
Upvotes: 4
Reputation: 145
#ifndef CONFIG_H
#define CONFIG_G
... exciting stuff in C ....
#endif
its a typo because of that you are getting 'already defined error'
in your header file you are defining CONFIG_G instead of CONFIG_H , so from the next source file the #ifndef CONFIG_H is true so it is again including the same contents
Upvotes: 2