Reputation: 2204
I have a .cpp file (lets call it check.cpp) with the following preprocessor-directive:
#ifdef CHECK
// code to execute goes here
#endif
check.cpp file is used in two different projects. (The projects are in the same folder and share the same check.cpp file which is also in the same folder)
I want one project to execute this code, but the other project to not execute this code.
So in the end, for ProjectA, check.cpp will have:
#ifdef CHECK
// This code WILL execute
#endif
And for ProjectB, check.cpp will have:
#ifdef CHECK
// This code WILL NOT execute
#endif
Is that possible using preprocessor-directives, or maybe there is an easier way?
My idea was to use
#define CHECK 1
And put that in one of the projects and not the other, but the .cpp file needs to include the #define for it to work and this file is shared...
Any ideas?
Upvotes: 0
Views: 507
Reputation: 6684
If you want to use your approach using #defines, I would suggest following approach:
#ifdef FOO
#define BAR(x) f(x)
#undef FOO
#else
#define BAR(x) g(x)
#endif
And in ProjectA.cpp:
#define FOO
#include "header.h"
void a(int x) {
BAR(x); // f(x)
}
In ProjectB.cpp
#undef FOO
#include "header.h"
void b(int x) {
BAR(x); // g(x)
}
This will call two versions of different functions, but your code could stay in same file common.cpp. So in g(x)
you could run the code specific to ProjectB.cpp
and in f(x)
you could run the code specific to ProjectA.cpp
Hope I answered the question right.
Upvotes: 0
Reputation: 2553
I don't think that is possible.
#ifdef CHECK
...
#endif
Will always execute if CHECK is defined. The only way to not include the enclosed code in a project would be to un-define CHECK for that project if it was ever defined.
#undef CHECK
in project B
Upvotes: 0
Reputation: 6260
I'm not sure which compiler you're using, but in Visual Studio, define 'CHECK' in the project for which you want to execute the code:
Project settings > Configuration Properties > C/C++ > Preprocessor > Preprocessor Definitions
Upvotes: 2
Reputation: 18358
No matter what you do, you'll need a point of decision where you instruct the compiler what code to compile.
Different development environments provide various methods to inject the data into this point of decision. It can be via environment variables that have different values for different projects. Another way (a cleaner one, I'd say) is to separate the code in 2 different files, one to be included in the first project and one in the second.
Upvotes: 1