出于某种原因,我在头文件中获得了多个内容声明,即使我使用了标头保护.我的示例代码如下:
For some reason, I'm getting multiple declarations of content within my header file even though I'm using header guards. My example code is below:
main.c:
#include "thing.h" int main(){ printf("%d", increment()); return 0; }thing.c:
#include "thing.h" int increment(){ return something++; }thing.h:
#ifndef THING_H_ #define THING_H_ #include <stdio.h> int something = 0; int increment(); #endif当我尝试编译它时,GCC 说我对 something 变量有多个定义.ifndef 应该确保不会发生这种情况,所以我很困惑为什么会这样.
When I attempt to compile this, GCC says that I have multiple definitions of the something variable. ifndef should make sure that this doesn't happen, so I'm confused why it is.
推荐答案包含防护功能正常,不是问题的根源.
The include guards are functioning correctly and are not the source of the problem.
发生的情况是每个包含 thing.h 的编译单元都有自己的 int something = 0,因此链接器会抱怨多个定义.
What happens is that every compilation unit that includes thing.h gets its own int something = 0, so the linker complains about multiple definitions.
以下是解决此问题的方法:
Here is how you fix this:
thing.c:
#include "thing.h" int something = 0; int increment(){ return something++; }thing.h:
#ifndef THING_H_ #define THING_H_ #include <stdio.h> extern int something; int increment(); #endif这样,只有 thing.c 会有 something 的实例,main.c 会引用它.
This way, only thing.c will have an instance of something, and main.c will refer to it.
更多推荐
标题/包含警卫不起作用?
发布评论