【问题标题】:Undefined reference when using extern on a c++ object, but not integral type在 c++ 对象上使用 extern 时未定义的引用,但不是整数类型
【发布时间】:2012-10-03 02:24:53
【问题描述】:

尝试在 c++ 对象上使用 extern 时出现未定义的引用错误。整数类型似乎不会发生这种情况。我错过了什么?!下面的代码复制了这个问题:

file1.cpp:

#include <string>

const std::string s("test");
int i = 99;

int main()
{
        extern void Test();
        Test();
}

file2.cpp:

#include <iostream>
#include <string>

extern const std::string s;
extern int i;

void Test()
{
        std::cout << s << std::endl;
        std::cout << i << std::endl;
}

如果我注释掉 's' std::string 变量的用法,链接错误就会消失。

SO 上还有其他类似的问题,但它们似乎都与没有定义变量的人有关,我就是!

【问题讨论】:

    标签: c++ gcc


    【解决方案1】:

    它是std::string 上的const,它提供s 内部链接。引用自【3.5 程序与链接】:3:

    具有命名空间范围 (3.3.6) 的名称具有内部链接,如果它是 名字

    ——显式声明为 const 或 constexpr 的变量,并且 既没有明确声明 extern 也没有事先声明有 外部链接;或

    【讨论】:

      【解决方案2】:

      如果去掉 const,它可以在 vc++ 中工作,如果你将它们都定义为 extern const,它也可以工作。

      // file1.cpp
      extern const std::string s("test");
      extern const int i = 99;
      
      // file2.cpp
      extern const std::string s;
      extern const int i;
      

      如果您从 file1.cpp 中删除任何“extern”,它就无法编译。如果变量定义为 const,您可以从 file1.cpp 中删除 'extern'。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-10
        • 1970-01-01
        • 2022-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-28
        相关资源
        最近更新 更多