标题/包含警卫不起作用? [英] Header/Include guards don't work?

查看:21
本文介绍了标题/包含警卫不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于标题/包含警卫不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆