简体   繁体   中英

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"?

PS 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 ?

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).

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.

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.

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 (eg 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM