Using the same variable for multiple files in C ++

In the process of changing any code, I spilled some functions on several files. I have controls.cpp and display.cpp files, and I would like to be able to have access to the same set of variables in both files. I do not mind where they are initialized or declared, while functions in both files can use them.

This was not a problem when the functions were in a single file, but now it seems almost impossible after an hour of searching the Internet and trying various things.

+7
c ++ variables
source share
5 answers

Define the variable in one file, for example:

 type var_name; 

And declare it global in another file, for example:

 extern type var_name; 
+17
source share

use these variables as extern i.e.

 extern int i; 

in another file, it is declared in the same way as a regular global variable ...

 int i;//global 
+6
source share

Create two new files:

  • Something like Globals.h and declare all type variables: extern type name;
    • btw remember protection.
  • Something like Globals.cpp and declare type variables: type name;

Then add #include "Globals.h" at the top:

  • Globals.cpp
  • controls.cpp
  • display.cpp

You may then want some functions to initialize them.

+4
source share

Essentially, all you have to do is declare the variable once in one code file and declare it in others as extern (making sure NOT to initialize it when you declare it extern, or some compilers will ignore the extern keyword, giving compiler errors to you.)

The easiest way to do this is to use a macro in the header file, for example:

 #pragma once #ifdef __MAIN__ #define __EXTERN(type, name, value) type name = value #else #define __EXTERN(type, name, value) extern type name; #endif 

and then declare the variables in the same header file, for example:

 __EXTERN(volatile int, MyVolatileInteger, 0); 

from any ONE file in the project, include the header file, for example:

 #define __MAIN__ #include "Globals.h" 

from everything else, just turn it on as usual, for example:

 #include "Globals.h" 

Presto, everything is ready. Variables are declared only once and are initialized in a string. This is very convenient, and it eliminates the need to declare everything twice.

+2
source share

All declarations that you want to see in several compilation units (.cpp files) should be included in the header file, which you include in all places where you need to use a variable, type, class, etc.

This is much better than extern, which essentially hides your intention to share the ad.

-one
source share

All Articles