【问题标题】:Accessing a global variable defined in a .cpp file in another .cpp file [duplicate]在另一个 .cpp 文件中访问 .cpp 文件中定义的全局变量 [重复]
【发布时间】:2017-05-05 15:19:35
【问题描述】:

考虑以下场景:

MyFile.cpp

const int myVar = 0; // 全局变量

另一个文件.cpp

void myFun()
{
    std::cout << myVar; // compiler error: Undefined symbol
}

现在如果我在使用之前在 AnotherFile.cpp 中添加extern const int myVar;,链接器会报错为

未解决的外部

我可以将myVar 的声明移动到MyFile.h 并在AnotherFile.cpp 中包含MyFile.h 来解决问题.但我不想将声明移至头文件。我还有其他方法可以完成这项工作吗?

【问题讨论】:

    标签: c++ extern


    【解决方案1】:

    在 C++ 中,constimplies internal linkage。您需要在 MyFile.cpp 中将 myVar 声明为 extern

    extern const int myVar = 0;
    

    AnotherFile.cpp 中的:

    extern const int myVar;
    

    【讨论】:

    • 不,像以前一样继续编译和链接。
    • 能否请您发布您使用的命令?
    • 哦,对不起,我以为你已经在 AnotherFile.cpp 中声明了它。你需要把它放在 AnotherFile.cpp 中:extern const int myVar;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    相关资源
    最近更新 更多