Variable and scope beyond file . cpp C++

Asked

Viewed 167 times

0

Is there a possibility of a file . cpp "seeing" a variable declared in in another file . cpp? Example: in the main.cpp file there is a global variable int myVar. You can access it in another file, in my.cpp?

1 answer

1


Variables declared in global scope of the file can be accessed by other files using extern.

foo.cpp

int myVar = 10;

main.cpp

#include <iostream>

extern int myVar;

int main() {
  std::cout << myVar << std::endl;

  return 0;
}

To share variables it is recommended to declare them in header files. h, and they must also be constant or pre-processed to not interfere with the behavior of the other functions that depend on them.

  • Oops, thanks Vinicius. Thank you very much. It worked here.

  • @mrsoliver if my answer was helpful for you mark it as correct answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.