如何让编译器在宏未定义时忽略对应的日志调用代码?
Absolutely, you can configure your code to skip those log-related lines entirely when the required macros aren't defined—no more compilation errors, and your release code stays clean. Here are two reliable approaches:
1. Wrap Log Calls with Preprocessor Guards
The simplest fix is to wrap every DBGL_LOG_INFO call with a check for whether DBGL_UART_LOG_ENABLED is defined (and optionally, whether it's set to true to match your original logic). This tells the preprocessor to discard the log line entirely if the macro doesn't exist.
Example code:
// Only compile the log line if DBGL_UART_LOG_ENABLED is defined and truthy #if defined(DBGL_UART_LOG_ENABLED) && DBGL_UART_LOG_ENABLED DBGL_LOG_INFO(DBGL_UART_LOG_ENABLED, "UART is initialized"); #endif
This matches your original behavior: when the macro is defined as true, the log runs; when it's defined as false or not defined at all, the code is stripped out before compilation.
2. Define a Fallback Empty Macro
If you don't want to add guards around every single log call, you can define a "no-op" (no operation) version of DBGL_LOG_INFO in a shared header file that's included by all your C files. This ensures the macro exists even when the log module is missing, and it does nothing when called.
Add this to a common header (like common_log_fallback.h):
#ifndef DBGL_LOG_INFO // Use do-while(0) to ensure the macro behaves like a function in all contexts #define DBGL_LOG_INFO(enabled, msg) do { } while(0) #endif
Then include this header in every C file that uses the log macro. Now, when DBGL_LOG_INFO isn't provided by the log module, the preprocessor replaces it with an empty block that the compiler will optimize away completely.
Why Your Original Code Fails
The error happens because when DBGL_UART_LOG_ENABLED is undefined, the preprocessor can't resolve that identifier when expanding DBGL_LOG_INFO. By either guarding the call or providing a fallback macro, you eliminate that undefined identifier reference entirely.
内容的提问来源于stack exchange,提问作者Steckdoose

