[英]#define DEBUG 1
我正在嘗試打開調試模式,如果
#define DEBUG 1
我想打印一些變量值,如果
#define DEBUG 0
我要他們離開。
問題是我有很多實現文件,我希望這個 DEBUG 變量可用於整個項目。 現在我需要編輯 foo1.c、foo2.c、foo3.c 中的 DEBUG 變量,這看起來很乏味且容易出錯,必須有更好的方法。 有什么建議?
編譯時,您應該能夠為編譯器指定一個選項。 例如,您可以使用-DDEBUG
選項調用 GCC。
在這種情況下,您最好使用:
#ifdef DEBUG
#endif
或者:
#if defined(DEBUG)
#endif
如果這不是你現在做的方式。 我很驚訝您的項目沒有全局頭文件。 類似的東西:
#undef DEBUG
#define DEBUG 1
在名為“debug.h”的文件中。 在你的 C 程序中,你可以使用#include "debug.h"
來包含它
嘗試類似 Steve McConnel 在Code Complete 2的“第 8 章:防御性編程”的第 6 節中建議的內容……將其添加到您的代碼中:
#ifdef DEBUG
#if (DEBUG > 0) && (DEBUG < 2)
printf("Debugging level 1");
#endif
#if (DEBUG > 1) && (DEBUG < 3)
printf("Debugging level 2");
#endif
#if (DEBUG > n-1) && (DEBUG < n)
printf("Debugging level n");
#endif
#endif
然后在編譯時添加此標志(警告:這可能與編譯器有關):
-DDEBUG=m
或者,正如其他人所建議的那樣,擁有一個定義此類事物的全局標頭。
作為對您的問題的回應,您還可以簡單地調用編譯器,如:
cc -c -DDEBUG=1
或者
cc -c -DDEBUG=0
您必須刪除文件中的“定義調試 1/0” - 或將其替換為:
#ifndef DEBUG
#define DEBUG 0
#endif
這是我正在使用的(GCC 語法):
使用以下內容創建文件 debug.h 並將其包含在每個 c 文件中:
#ifdef DEBUG extern FILE *dbgf; #define D_MIN 0x00010000 // Minimum level #define D_MED 0x00020000 // Medium level #define D_MAX 0x00040000 // Maximum level #define D_FLUSH 0x00080000 // Usefull by a program crash #define D_TRACE 0x00100000 #define D_1 0x00000001 ... #define D(msk, fmt, args...) if(msk & dbgmsk) { fprintf(dbgf, "%s:",__FUNCTION__); fprintf(dbgf, fmt, ## args ); if(msk & D_FLUSH) fflush(dbgf); } #define P(msk, fmt, args...) if(msk & dbgmsk) { fprintf(dbgf, fmt, ## args ); if(msk & D_FLUSH) fflush(dbgf); } #else #define D(msk, fmt, args...) #define P(msk, fmt, args...) #endif
dbgmsk 是變量,它可以是全局的(整個程序)或局部的/靜態的,並且必須在開始時進行初始化。 您可以為整個程序或每個模塊定義多個選項。 這比帶有 level 變量的版本更好、更靈活。
前任。 模塊1.c:
#include "debug.h"
static int dbgmsk; // using local dbgmsk
module1_setdbg(int msk) { dbgmsk = msk; D(D_TRACE,"dbgmsk1=%x\n", dbgmsk); }
foo1() { P(D_1, "foo1 function\n" );
....
}
foo2() {}
...
foo3.c
#include "debug.h"
extern int dbgmsk; // using global dbgmsk
前任。 主要的:
#include "debug.h"
FILE *dbgf;
int dbgmsk = 0; // this is the global dbgmsk
int main() {
dbgf = stderr; // or your logfile
dbgmsk = D_MIN;
module1_setdbg(D_MIN|D_MED|D_TRACE|D_1);
....
}
我還將所有 dbgmsk 變量存儲在程序啟動時讀取的配置文本文件中。
將“#define DEBUG”放在“debug.h”中,並在每個*.c 文件中#include 該頭文件。
正如@person-b 所說,將此定義指定為編譯器選項,例如 -D DEBUG
請注意,為了簡化這一點,您應該將代碼中的測試更改為:
#if DEBUG
到:
#ifdef DEBUG
這樣您就不必擔心指定 0 或 1 值,而是可以依賴於它是否被定義。
samoz 和 Stephen Doyle 建議檢查 DEBUG 的定義是否存在而不是其值,這是一個很好的建議。 但是,如果您真的想使用 DEBUG=0,您可以這樣做:每次定義 DEBUG 標志時(即,在每個文件中),檢查現有定義:
#ifndef DEBUG
#define DEBUG 1
#endif
然后,當您在編譯器中使用選項 -DDEBUG=0 時,將永遠不會執行 #define 行。
試試這個。
在您擁有的第一個文件中,將包含:
#define DEBUG
然后,每當您想要調試代碼時,請執行以下操作:
#ifdef DEBUG
do some stuff
#endif
這也將阻止您的調試代碼使其成為發布代碼。
我個人喜歡
#ifdef DEBUG #define IFDEBUG if(0)else #else #define IFDEBUG if(1)else #endif
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.