宏定义没有按预期替换?

Macro definition not replaced as expected?

我按照在线教程,想用#undef设计我的调试输出函数。我写了一个 debugOut.h 文件。 内容如下:

#include <stdio.h>

#define NOOP //(void(0))

#undef DEBUG_PRINT

#if DEBUG_OUT
#define DEBUG_PRINT printf
#else 
#define DEBUG_PRINT(...) NOOP
#endif 

#undef DEBUG_OUT

然后我写了一个main函数来测试我的设计是否正确

#include<iostream>
#include "Header/debug_out.h"
#define DEBUG_OUT
int main(){
    DEBUG_PRINT("module1 debug...\n");
    printf("hello,world");
}

但是输出结果只有hello, world。为什么我定义了#define DEBUG_OUT,为什么DEBUG_PRINT没有换成printf

我是根据网上教程写的。我想基于此为c++编写一个输出函数。但是在#define DEBUG_PRINT(...) NOOP这句话中,(...)代表什么?有什么方法可以输出宏定义被替换的内容吗?

预处理器基本上从上到下扫描输入。所以它首先处理 #include "Header/debug_out.h" 中包含的 #if DEBUG_OUT 并且只处理 然后 它处理 #define DEBUG_OUT.

您需要确保在处理 Header/debug_out.h 的内容之前定义了 DEBUG_OUT。以下应该有效:

#include<iostream>
#define DEBUG_OUT             // first define DEBUG_OUT 
#include "Header/debug_out.h" // when this is processed DEBUG_OUT is defined
int main(){
    DEBUG_PRINT("module1 debug...\n");
    printf("hello,world");
}

此外,“Header/debug_out.h”中有一个错字:

#if DEBUG_OUT

应该是

#ifdef DEBUG_OUT
#include <stdio.h>

#define NOOP //(void(0))

#undef DEBUG_PRINT

#if DEBUG_OUT      ///////////should be #ifdef
#define DEBUG_PRINT printf
#else 
#define DEBUG_PRINT(...) NOOP
#endif 

#undef DEBUG_OUT

以下是从投票最多的人中复制的。

#include<iostream>
#define DEBUG_OUT             // first define DEBUG_OUT 
#include "Header/debug_out.h" // when this is processed DEBUG_OUT is defined
int main(){
    DEBUG_PRINT("module1 debug...\n");
    printf("hello,world");
}