0

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();
}

1 Answers1

2

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

extern double dir;

void printdir () {
    cout << dir;
}
TuanPM
  • 685
  • 8
  • 29