简体   繁体   English

C ++条件编译

[英]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"? 现在如果我在我的代码中调用log("hello world")并且没有定义DO_LOG ,那么该行是否会被编译,换句话说它会占用字符串“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 ? PS程序中有很多记录调用,它对内存敏感,那么有没有其他方法可以有条件地编译,这样它只依赖于#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. 但是,我想补充一点,如果您对将日志记录添加到C ++应用程序感兴趣,可能需要使用Log4Cxx库。 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.). 它使用类似的宏,您可以从应用程序中完全忽略它,但是当启用日志记录时,它支持几种不同级别的日志记录(基于重要性/严重性)以及发送日志记录输出的多个不同“appender”(例如syslog) ,控制台,文件,网络I / O等)。

The full API documentation may be found at Log4Cxx API docs . 可以在Log4Cxx API文档中找到完整的API文档 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). 此外,如果您有任何使用Log4J的 Java开发人员,他们应该感到宾至如归(并说服您使用它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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