出于某种原因,我在头文件中得到了多个内容声明,即使我使用了头文件保护。我的示例代码如下:
主.c:
#include "thing.h"
int main(){
printf("%d", increment());
return 0;
}
事物.c:
#include "thing.h"
int increment(){
return something++;
}
事物.h:
#ifndef THING_H_
#define THING_H_
#include <stdio.h>
int something = 0;
int increment();
#endif
当我尝试编译它时,GCC 说我对 something 变量有多个定义。 ifndef 应该确保这不会发生,所以我很困惑为什么会这样。
最佳答案
include 守卫功能正常,不是问题的根源。
发生的情况是每个包含 thing.h
的编译单元都有自己的 int something = 0
,因此链接器会提示有多个定义。
这是解决此问题的方法:
事物.c:
#include "thing.h"
int something = 0;
int increment(){
return something++;
}
事物.h:
#ifndef THING_H_
#define THING_H_
#include <stdio.h>
extern int something;
int increment();
#endif
这样,只有 thing.c
会有一个 something
的实例,而 main.c
会引用它。
关于c - 标题/包含守卫不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7926224/