简体   繁体   English

如何从 .h 文件中的 .cpp 文件访问变量

[英]How to access a variable from .cpp file in a .h file

Consider this scenario:考虑这个场景:

File1.cpp :文件 1.cpp :

double dir = M_PI/2;

hFile1.h : hFile1.h :

void printdir () {
cout << dir;
}

Main.cpp :主.cpp :

#include "hFile1.h"
int main () {
printdir();
}

This obviously will not work because hFile1.h will throw an error: "use of undeclared identifier 'dir'".这显然不起作用,因为 hFile1.h 会抛出错误:“使用未声明的标识符 'dir'”。 In this example, I want to be able to access and use the defined dir variable in hFile1.h.在这个例子中,我希望能够访问和使用 hFile1.h 中定义的dir变量。 Is this possible?这可能吗?

NOTE: I have already tried using extern based on similar posts on this topic and it didn't work, even after I did exactly what they did.注意:我已经尝试过基于关于这个主题的类似帖子使用extern并且它不起作用,即使我完全按照他们所做的去做。 Code:代码:

File1.cpp :文件 1.cpp :

extern double dir = M_PI/2;

hFile1.h : hFile1.h :

extern double dir;
void printdir () {
cout << dir;
}

Main.cpp :主.cpp :

#include "hFile1.h"
int main () {
printdir();
}

You need to use keyword "extern" in hFile1.h as below.您需要在hFile1.h使用关键字“extern”,如下所示。 I tested, it worked.我测试过,有效。

extern double dir;

void printdir () {
    cout << dir;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM