C++如何在调试模式下运行宏定义调试?
问题描述:
我正在使用cygwin来编译我的程序。我使用的命令是g ++ -std = C++ 11 -W -Wall -pedantic a1.cppC++如何在调试模式下运行宏定义调试?
我想执行一部分代码,如果调试模式已定义,而另一部分则不执行。
我的问题是,什么是在调试模式下编译的命令,以及我应该在if/else执行代码中放入什么内容?
答
您可以添加一个命令行选项,如-DDEBUGMODE
定义到您的调试版本。
在您的代码中,您可以根据DEBUGMODE
被定义与否来决定做什么。
#ifdef DEBUGMODE
//DEBUG code
#else
//RELEASE code
#endif
我也建议阅读 _DEBUG vs NDEBUG 和 Where does the -DNDEBUG normally come from?
+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);
}
相关:http://stackoverflow.com/questions/2290509/debug-vs-ndebug – SleuthEye
请注意,您会发现很难调试未在调试模式下执行的代码。 –