【发布时间】:2011-12-17 02:15:50
【问题描述】:
出于某种原因,即使我使用了标头保护,我也会在我的头文件中获得多个内容声明。我的示例代码如下:
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 应该确保不会发生这种情况,所以我很困惑为什么会这样。
【问题讨论】:
-
编译器错误“多个声明”与链接器错误“多个定义”不同”。您在问题中都提到了(实际上唯一的问题是后者);了解差异是了解问题所在的关键。标头保护防止多个声明,而不是多个定义。
-
@Clifford 抱歉,我应该提到我遇到了链接器错误。
-
另外,在 C 中,
int increment();不是原型,而是声明了一个带有未指定数量参数的函数。为此使用int increment(void);。
标签: c header include-guards