user300665
user300665

Reputation:

C++ conditional compilation

I have the following code snippet:

#ifdef DO_LOG
#define log(p) record(p)
#else
#define log(p)
#endif

void record(char *data){
.....
.....
}

Now if I call log("hello world") in my code and DO_LOG isn't defined, will the line be compiled, in other words will it eat up the memory for the string "hello world"?

P.S. There are a lot of record calls in the program and it is memory sensitive, so is there any other way to conditionally compile so that it only depends on the #define DO_LOG?

Upvotes: 5

Views: 2259

Answers (4)

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95629

No. The preprocessor is executed prior to compilation, and so the code will never even be seen. I would like to add, though, that if you are interested in adding logging to your C++ application, you might want to use the Log4Cxx library. It uses similar macros which you can completely elide from your application, but when logging is enabled, it supports several different levels of logging (based on importance/severity) as well as multiple different "appenders" to which to send logging output (e.g. syslog, console, files, network I/O, etc.).

The full API documentation may be found at Log4Cxx API docs. Also, if you have any Java developers on board who have used Log4J, they should feel right at home with Log4Cxx (and convince you to use it).

Upvotes: 2

sharptooth
sharptooth

Reputation: 170539

No, it will not be in the binary. It will not even be compiled - the preprocessor will expand it into an empty string prior to the compilation, so the compiler will not even see it.

Upvotes: 4

Gorpik
Gorpik

Reputation: 11038

Since the preprocessor runs before the compiler, the line will not even exist when the compiler runs. So the answer is no, it does not use any memory at all.

Upvotes: 4

unwind
unwind

Reputation: 400059

This should be trivial to verify for yourself by inspecting the resulting binary.

I would say "no", since the expression totally goes away, the compiler will never see the string (it's removed by the preprocessor's macro expansion).

Upvotes: 14

Related Questions