开发者

C++ conditional compilation

开发者 https://www.devze.com 2022-12-24 16:53 出处:网络
I have the following code snippet: #ifdef DO_LOG #define log(p) record(p) #else #define log(p) #endif void record(char *data){

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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消