标题/包括警卫不起作用?

use*_*968 5 c header include-guards

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

main.c中:

#include "thing.h"

int main(){
    printf("%d", increment());

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

thing.c:

#include "thing.h"

int increment(){
    return something++;
}
Run Code Online (Sandbox Code Playgroud)

thing.h:

#ifndef THING_H_
#define THING_H_

#include <stdio.h>

int something = 0;

int increment();

#endif
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,GCC说我对some变量有多个定义.ifndef应该确保不会发生这种情况,所以我很困惑为什么会这样.

NPE*_*NPE 10

包含警卫功能正常,不是问题的根源.

会发生的是,包含的每个编译单元thing.h都有自己的编译单元int something = 0,因此链接器会抱怨多个定义.

以下是您解决此问题的方法:

thing.c:

#include "thing.h"

int something = 0;

int increment(){
    return something++;
}
Run Code Online (Sandbox Code Playgroud)

thing.h:

#ifndef THING_H_
#define THING_H_

#include <stdio.h>

extern int something;

int increment();

#endif
Run Code Online (Sandbox Code Playgroud)

这样,只会thing.c有一个实例something,并main.c会引用它.

  • 你也可以补充一点,即使没有多重定义错误,每个TU也会拥有自己的变量副本,并且无法达到在所有源文件中共享相同变量的目的. (2认同)