[英]C Preprocessor Guards?
I am working on a C
project, and am trying to use pre-processor guards as can be used in C++: 我正在研究
C
项目,并且正在尝试使用可以在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: 在我的源代码中包括此内容似乎在Visual Studio中无效,因为当我在多个文件中包含给定文件(例如
Config.h
,编译器会给我以下错误:
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? 请问有人可以给我任何指示(不要双关语)吗?
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
. 链接器消息指示发生了这种情况
_OPCodes
例如在lib
和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) (例如,请参阅定义和声明之间的区别?以获取更多信息)
EDIT: this is based on the original post, which had a typo. 编辑:这是基于原始的帖子,其中有一个错字。 It's NOT the OP's real problem, apparently.
显然,这不是OP的真正问题。
You've given your guards two different names. 您已经给卫队起了两个不同的名字。 They must match.
他们必须匹配。
#ifndef CONFIG_H
#define CONFIG_H // not CONFIG_G!
#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 在头文件中,您正在定义CONFIG_G而不是CONFIG_H,因此在下一个源文件中,#ifndef CONFIG_H为true,因此它再次包含相同的内容
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.
有时Visual Studio对此有点奇怪,当它们留在其中时,它们将导致链接器错误。
Make sure to do a rebuild. 确保进行重建。
You may also have accidentally included a .cpp
file instead of a .h
file. 您可能还意外地包含了
.cpp
文件而不是.h
文件。 Double check all the includes just in case. 仔细检查所有包含的内容,以防万一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.