Accessing an external variable in C ++ from another file

I have a global variable in one of the cpp files where I assign a value to it. Now, to be able to use it in another cpp file, I declare it as extern , and this file has several functions that use it, so I do it globally. Now the value of this variable can be obtained in one of the functions, and not in the other. Any suggestions other than using it in the header file would be nice, because I spent 4 days on this.

+8
source share
1 answer

Sorry, I ignore the response request suggesting nothing but the use of header files. Headers are needed for this when you use them correctly ... Read carefully:

global.h

 #ifndef MY_GLOBALS_H #define MY_GLOBALS_H // This is a declaration of your variable, which tells the linker this value // is found elsewhere. Anyone who wishes to use it must include global.h, // either directly or indirectly. extern int myglobalint; #endif 

global.cpp

 #include "global.h" // This is the definition of your variable. It can only happen in one place. // You must include global.h so that the compiler matches it to the correct // one, and doesn't implicitly convert it to static. int myglobalint = 0; 

user.cpp

 // Anyone who uses the global value must include the appropriate header. #include "global.h" void SomeFunction() { // Now you can access the variable. int temp = myglobalint; } 

Now that you are compiling and linking your project, you should:

  • Compile each source file (.cpp) into an object file;
  • Link all the object files to create an executable / library / independently.

Using the syntax above, you should have neither compilation nor error references.

+30
source

Source: https://habr.com/ru/post/1432587/


All Articles