c - 标题/包含守卫不起作用?

标签 c header include-guards

出于某种原因,我在头文件中得到了多个内容声明,即使我使用了头文件保护。我的示例代码如下:

主.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/

相关文章:

c - 函数 printArray 无法正常工作

c - 使用 java/jna 获取硬件信息以在所有操作系统上工作

c - 为什么这个宏被定义为({ 1; })?

c++ - 在 C 源文件中包含带有命名空间的 C++ 头文件导致编译错误

c++ - 添加自定义邮件标题

c++ - 无法使用在不同头文件中定义的结构

c - sync() 调用和sync 命令有何不同?

c++ - 混淆包含头文件

c++ - 头部防护装置的用途

c++ - 在包含防护中使用 #error 指令