user672033
user672033

Reputation:

C++ precompiler conditionally include code

I have a few projects that share a lot of common code, but sometimes I need to not include certain parts of the common code depending on the project.

I've tried creating a separate file called project_names.hh, containing this:

// list of project names
#define FIRSTPROJECT 0
#define SECONDPROJECT 1

// PROJECT_NAME must be set to one of the above names in the project's main.cc file
#define PROJECT_NAME

Then in one of the projects' main files I do this:

#define PROJECT_NAME FIRSTPROJECT

The problem is that even though I include project_names.hh in another file, I can't seem to get this statement to compile:

#if PROJECT_NAME == FIRSTPROJECT

I get this error:

error: operator '==' has no left operand

Does anyone have a good way to do this?

Thanks!

Marlon

Upvotes: 1

Views: 1206

Answers (5)

Mark
Mark

Reputation: 6071

This is most probably because the PROJECT_NAME isn't set. You should check, which file is being compiled and check if the #define is set there.

It might help to set the define as a compiler option for the whole building process. For most compilers that I know (gcc, MSVC, clang, xlC), the compiler option would be

-DPROJECT_NAME=FIRSTPROJECT

Upvotes: 0

Kevin
Kevin

Reputation: 1706

You should include project_names.hh in the file in which you're running the #if PROJECT_NAME == FIRSTPROJECT. The preprocessor might not have loaded and executed the statements setting PROJCET_NAME in the first place.

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126203

That's because you've defined PROJECT_NAME to be the empty string with your line

#define PROJECT_NAME

you want to change it to

#define PROJECT_NAME FIRSTPROJECT

This needs to be in a header file that all the files of that project #include.

Alternatively, you could get rid of the #define PROJECT_NAME and instead use
-DPROJECT_NAME=FIRSTPROJECT on the compiler command line for all the files in that project. Note that if the same file is used in multiple projects, you'll need to compile it mulitple times with different options, and have it put the output in different places...

Upvotes: 2

rather than #define PROJECT_NAME FIRSTPROJECT,

use #define FIRSTPROJECT,

then check its existence with #ifdef FIRSTPROJECT

Upvotes: 1

morganfshirley
morganfshirley

Reputation: 63

If I were in your situation I would simply define either FIRSTPROJECT or SECONDPROJECT instead of setting PROJECT_NAME to either of those values. I would then use #ifdef to check whether that value is set.

Upvotes: 1

Related Questions