2015-11-07 178 views
0

我正在使用cygwin來編譯我的程序。我使用的命令是g ++ -std = C++ 11 -W -Wall -pedantic a1.cppC++如何在調試模式下運行宏定義調試?

我想執行一部分代碼,如果調試模式已定義,而另一部分則不執行。

我的問題是,什麼是在調試模式下編譯的命令,以及我應該在if/else執行代碼中放入什麼內容?

+0

相關:http://stackoverflow.com/questions/2290509/debug-vs-ndebug – SleuthEye

+0

請注意,您會發現很難調試未在調試模式下執行的代碼。 –

回答

0

您可以添加一個命令行選項,如-DDEBUGMODE定義到您的調試版本。

在您的代碼中,您可以根據DEBUGMODE被定義與否來決定做什麼。

#ifdef DEBUGMODE 
    //DEBUG code 
#else 
    //RELEASE code 
#endif 

我也建議閱讀 _DEBUG vs NDEBUGWhere does the -DNDEBUG normally come from?

+0

謝謝,這工作! –

0

1 - 首先調試啓用/禁用方法是-D添加到您的完成指令,如:

gcc -D DEBUG <prog.c> 

2-第二:爲了啓用調試功能,定義用這樣的調試語句代替的MACRO:

#define DEBUG(fmt, ...) fprintf(stderr, fmt,__VA_ARGS__); 

要禁用調試功能定義宏用什麼來替代這樣的:

#define DEBUG(fmt, ...) 

例準備進行調試:

#include <stdio.h> 
#include <stdlib.h> 

int addNums(int a, int b) 
{ 
DEBUG ("add the numbers: %d and %d\n", a,b) 
return a+b; 
} 

int main(int argc, char *argv[]) 
{ 
int arg1 =0, arg2 = 0 ; 

if (argc > 1) 
    arg1 = atoi(argv[1]); 
    DEBUG ("The first argument is : %d\n", arg1) 

if (argc == 3) 
    arg2 = atoi(argv[2]); 
    DEBUG ("The second argument is : %d\n", arg2) 


printf("The sum of the numbers is %d\n", addNums(arg1,arg2)); 

return (0); 
} 
相關問題