Linux 上的 C++ - 如何#define #ifdef / #endif 调试条件
C++ on Linux - How do I #define a #ifdef / #endif debug conditional
如果定义了 DEBUG
,我想跟踪我的代码,如下面的 #ifdef
代码块:
#ifdef DEBUG
OP_LOG(debug) << "SEQUENCE: " __FILE__ << "::" << __FUNCTION__;
#endif
有人说我可以用#define
这样上面三行就只有一行了。这是我能弄清楚的最接近的结果,但它无条件地提供跟踪输出,无论是否定义了 DEBUG
:
#define DEBUG_TRACE(note) OP_LOG(debug) << "SEQUENCE : " << __FILE__ <<"::" <<__FUNCTION__ << note
我不知道如何做条件#define
。这可能吗?如果可以,怎么做?
你不能把#ifdef
放在#define
的替换部分,但是你可以使用#define
在 一个#ifdef
/#endif
块中,像这样:
#ifdef DEBUG
#define DEBUG_TRACE(note) ... // put your debug code here
#else
#define DEBUG_TRACE(note)
#endif
在 #else
的情况下,如果 DEBUG
未定义,这会定义 DEBUG_TRACE
展开为空。
Someone said I could create a #define, so that the above three lines would only be one line instead.
我没听说过。我最喜欢的方法是
#ifdef DEBUG
#define DEBUG_LOG OP_LOG(debug) << "SEQUENCE: " __FILE__ << "::" << __FUNCTION__;
#else
#define DEBUG_LOG
#endif
这样你只需要在设置了 -DDEBUG
的地方写 DEBUG_LOG。
它的工作方式:
查看 #ifdef
、#else
、#endif
语句。我们将 DEBUG_LOG
定义为在未设置 -DDEBUG
时扩展为空,如果设置为 OP_LOG(debug) << "SEQUENCE: " __FILE__ << "::" << __FUNCTION__;
。这样您以后就不必担心 -DDEBUG
,您只需在要进行跟踪调用时使用 DEBUG_LOG
。
如果定义了 DEBUG
,我想跟踪我的代码,如下面的 #ifdef
代码块:
#ifdef DEBUG
OP_LOG(debug) << "SEQUENCE: " __FILE__ << "::" << __FUNCTION__;
#endif
有人说我可以用#define
这样上面三行就只有一行了。这是我能弄清楚的最接近的结果,但它无条件地提供跟踪输出,无论是否定义了 DEBUG
:
#define DEBUG_TRACE(note) OP_LOG(debug) << "SEQUENCE : " << __FILE__ <<"::" <<__FUNCTION__ << note
我不知道如何做条件#define
。这可能吗?如果可以,怎么做?
你不能把#ifdef
放在#define
的替换部分,但是你可以使用#define
在 一个#ifdef
/#endif
块中,像这样:
#ifdef DEBUG
#define DEBUG_TRACE(note) ... // put your debug code here
#else
#define DEBUG_TRACE(note)
#endif
在 #else
的情况下,如果 DEBUG
未定义,这会定义 DEBUG_TRACE
展开为空。
Someone said I could create a #define, so that the above three lines would only be one line instead.
我没听说过。我最喜欢的方法是
#ifdef DEBUG
#define DEBUG_LOG OP_LOG(debug) << "SEQUENCE: " __FILE__ << "::" << __FUNCTION__;
#else
#define DEBUG_LOG
#endif
这样你只需要在设置了 -DDEBUG
的地方写 DEBUG_LOG。
它的工作方式:
查看 #ifdef
、#else
、#endif
语句。我们将 DEBUG_LOG
定义为在未设置 -DDEBUG
时扩展为空,如果设置为 OP_LOG(debug) << "SEQUENCE: " __FILE__ << "::" << __FUNCTION__;
。这样您以后就不必担心 -DDEBUG
,您只需在要进行跟踪调用时使用 DEBUG_LOG
。