页眉/ include防范不工作? [英] Header/Include guards don't work?

查看:200
本文介绍了页眉/ include防范不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我越来越即使我用头看守我的头文件中的内容的多个声明。我的例子code是如下:

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:

thing.c:

#include "thing.h"

int increment(){
    return something++;
}

thing.h:

thing.h:

#ifndef THING_H_
#define THING_H_

#include <stdio.h>

int something = 0;

int increment();

#endif

当我尝试编译此,GCC说,我有一些变量的多个定义。 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东西= 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:

thing.h:

#ifndef THING_H_
#define THING_H_

#include <stdio.h>

extern int something;

int increment();

#endif

这个办法,只有 thing.c 将有的东西的实例, main.c中将指向它。

This way, only thing.c will have an instance of something, and main.c will refer to it.

这篇关于页眉/ include防范不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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