访问另一个.cpp文件中的.cpp文件中定义的全局变量 [英] Accessing a global variable defined in a .cpp file in another .cpp file

查看:1217
本文介绍了访问另一个.cpp文件中的.cpp文件中定义的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下情形:

MyFile.cpp :

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

AnotherFile.cpp :

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

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

Now if I add extern const int myVar; in AnotherFile.cpp before using, linker complains as

未解决的外部

Unresolved external

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

I can move the declaration of myVar to MyFile.h and include MyFile.h in AnotherFile.cpp to solve the issue. But I do not want to move the declaration to the header file. Is there any other way I can make this work?

推荐答案

在C ++中,const

In C++, const implies internal linkage. You need to declare myVar as extern in MyFile.cpp:

extern const int myVar = 0;

AnotherFile.cpp中的

The in AnotherFile.cpp:

extern const int myVar;

这篇关于访问另一个.cpp文件中的.cpp文件中定义的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆