Reputation: 19093
I think the preprocessor handles files one by one and I can't figure out how to do it with includes, so I think it's impossible, but it would be great to hear other's thoughts.
I have in a.cpp
:
#define A 1
and I want to use it from 2.cpp
.
EDIT: I cant modify first file. So for now i just have copied defines. But question still opened.
Upvotes: 11
Views: 26631
Reputation: 258698
Defines inside a source file aren't seen by other translation units. Implementation files are compiled separately.
You can either
extern const int A = 1;
in an implementation file and declare it when you want to use it extern const int A;
.Of these, I'd say the first option is possibly the worst you can use.
Upvotes: 23
Reputation:
Like a way - using extern const variables.
For example:
file1.h (where you will use definitions)
extern const int MY_DEF;
#if (MY_DEF == 1)
//some another definitions
#endif
file2.h (where you will define definitions)
const int MY_DEF = 1
Pro & Con:
(+): you can use some values for defines
(-): ALL definitions must be defined
Upvotes: -1
Reputation: 13244
You would need to put your #define
in a header file which is then #include
d by both cpp files.
Upvotes: 4
Reputation: 42215
If you want to share a define between two source files, move it to a header file and include that 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 could also specify the define in the compiler command line. This can be fiddly to maintain for cross platform code (which may need different command lines for different compilers) though.
Upvotes: 9