gpt4 book ai didi

c++ - C/C++ - 条件头文件包含不起作用

转载 作者:太空狗 更新时间:2023-10-29 23:33:59 24 4
gpt4 key购买 nike

我的项目中有三个文件。

交流电
b.c
测试.h

test.h 声明了一个

namespace test_namespace {
int i;
void f1();
};

test.h也被包围了

#ifndef __x
#define __x
...
#endif

现在, a.c 包括 test.h 和 b.c 也包括 test.h 。a.c有main()函数,b.c有test_namespace::f1()的实现

但是,在编译这个时,我得到一个链接错误 -

"test_namespace::i is already defined in <b.c's object file mapping in /tmp>"

如果我注意在 test.h 中包含条件编译预处理器指令,为什么它同时包含在文件 a.c 和 b.c 中?

另外值得注意的是,如果我将 b.c 单独编译为共享库,然后在链接 a.c 的目标文件时将其用作共享库,则不会出现此错误。

有人可以向我解释上述错误,特别是面对条件编译指令吗?

最佳答案

您不能在头文件中声明变量。符号 test_namespace::i 由 a.c 和 b.c 导出。链接器找到两者,但不知道要使用哪一个。

你想在 test.h 中做的是:

namespace test_namespace {
extern int i;
void f1();
}

然后在 eather a.c 或 b.c 中声明 test_namespace::i:

namespace test_namespace {
int i;
}

关于c++ - C/C++ - 条件头文件包含不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7008014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com