调试和预处理器指令

Mar*_*llo 6 c++ compiler-construction c-preprocessor

为了进行调试,我在应用程序中调用了许多调试日志函数.当然,在生产版本中,需要跳过这些调试调用.而不是写:

#if DEVEL == 1
    Log::debug(...);
#endif
Run Code Online (Sandbox Code Playgroud)

围绕调试函数的所有调用,我决定在调试函数本身中编写以下内容:

#if DEVEL != 1
    return;
#endif
Run Code Online (Sandbox Code Playgroud)

编译器是否会避免无用函数调用的开销,或者#if #endif出于性能原因使用(许多丑陋)构造我会更好吗?

iam*_*ind 7

你可以做一个简单的伎俩,而不是担心优化器:

#if DEVEL == 1
#define LOG_DEBUG(...) Log::Debug(__VA_ARGS__)  // variadic macro
#else
#define LOG_DEBUG
#endif
Run Code Online (Sandbox Code Playgroud)

现在用LOG_DEBUG它来保持简单.


Mot*_*tti 5

如果该函数可用于内联(例如,它在头文件中实现),那么优化器将毫无困难地摆脱函数调用,从而不会产生任何开销.