简体   繁体   中英

How to access a variable from .cpp file in a .h file

Consider this scenario:

File1.cpp :

double dir = M_PI/2;

hFile1.h :

void printdir () {
cout << dir;
}

Main.cpp :

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

This obviously will not work because hFile1.h will throw an error: "use of undeclared identifier 'dir'". In this example, I want to be able to access and use the defined dir variable in hFile1.h. 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. Code:

File1.cpp :

extern double dir = M_PI/2;

hFile1.h :

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

Main.cpp :

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

You need to use keyword "extern" in hFile1.h as below. I tested, it worked.

extern double dir;

void printdir () {
    cout << dir;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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