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

编程入门 行业动态 更新时间:2024-10-11 13:24:46
本文介绍了标题/包含警卫不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

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

本文发布于:2023-11-26 20:29:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635082.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警卫   不起作用   标题

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!