[英]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
,為什么沒有用printf
替換DEBUG_PRINT
我是根據在線教程編寫的。 我想基於此為 C++ 編寫一個輸出函數。 但是在#define DEBUG_PRINT(...) NOOP
這句話中, (...)
代表什么? 有什么辦法可以輸出宏定義被替換的內容嗎?
預處理器基本上從上到下掃描輸入。 因此,它首先處理#include "Header/debug_out.h"
包含的#if DEBUG_OUT
,然后才處理#define DEBUG_OUT
。
你需要確保DEBUG_OUT
的內容之前定義Header/debug_out.h
進行處理。 以下應該工作:
#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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.