Is it possible to use #define from another cpp file?

I think the preprocessor processes the files one by one, and I can’t figure out how to do this with the included ones, so I think this is impossible, but it would be great to hear other thoughts.

I have a.cpp :

 #define A 1 

and I want to use it from 2.cpp .

EDIT: I cannot change the first file. So for now, I just copied defines. But the question is still open.

+7
source share
4 answers

Definitions inside the source file are not displayed by other translation units. Implementation files are compiled separately.

You can either

  • put them in the header and include it
  • use compiler options.
  • do it in a reasonable way - const int A = 1; in the implementation file and declare it when you want to use it extern const int A; .

Of these, I would say that the first option is probably the worst one you can use .

+16
source

If you want to share the definition between the two source files, move it to the header file and include this header from both source files.

mydefines.h:

 #ifndef MY_DEFINES_H #define MY_DEFINES_H #define A (1) // other defines go here #endif // MY_DEFINES_H 

source1.cpp:

 #include "mydefines.h" // rest of source file 

source2.cpp:

 #include "mydefines.h" // rest of source file 

You can also specify the definition on the compiler command line. This can be difficult to support cross-platform code (which may be required for different commands for different compilers).

+7
source

You will need to put your #define in the header file, which will then be #include d with both cpp files.

+4
source

As a way - using external constant variables.

For example:

file1.h (where you will use the definitions)

 extern const int MY_DEF; #if (MY_DEF == 1) //some another definitions #endif 

file2.h (where you define the definitions)

 const int MY_DEF = 1 

Pro and Con:

(+): you can use some values ​​to determine

(-): ALL definitions must be defined

-one
source

All Articles