【问题标题】:Undefined reference issue with a minimal "extern" usage test case具有最小“外部”使用测试用例的未定义​​参考问题
【发布时间】:2014-09-13 22:24:35
【问题描述】:

我的测试用例有两个文件:

a.cc:

#include <iostream>

using namespace std;

const string program_name("myprog");

b.cc:

#include <iostream>

using namespace std;

extern const string program_name;

int main(int argc, char **argv) {
    cout << program_name << endl;

    return 0;
}

编译时,我得到以下输出:

$ g++ -c a.cc -o a.o -std=c++11 -O2
$ g++ -c b.cc -o b.o -std=c++11 -O2
$ g++ a.o b.o -o case
b.o: In function `main':
b.cc:(.text.startup+0x7): undefined reference to `program_name'
collect2: error: ld returned 1 exit status

在 a.o 中,我有以下符号:

0000000000000018 b _ZL12program_name

在 b.o 中:

         U program_name

问题是:为什么我要在这里开枪打死自己?

注意:g++ 4.9.1

【问题讨论】:

    标签: c++ linker extern


    【解决方案1】:

    不错。这一切都归功于const关键字。

    它已经在 stackoverflow 上:[click]

    让我引用:

    这是因为 const 默认意味着内部链接,所以你的“定义”在它出现的翻译单元之外是不可见的。

    【讨论】:

    • 谢谢!我也通过在定义中添加“extern”来解决它。
    猜你喜欢
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多