C++ 如何在定义了宏调试的调试模式下运行?

C++ How do I operate in debug mode with macro debug defined?

我正在使用 cygwin 来编译我的程序。我使用的命令是 g++ -std=c++11 -W -Wall -pedantic a1.cpp

如果定义了调试模式,我想执行一部分代码,如果没有定义,我想执行另一部分代码。

我的问题是,在调试模式下编译的命令是什么?我应该在我的代码中放入什么来执行 if/else?

您可以在调试版本中添加一个命令行选项定义,例如 -DDEBUGMODE

在您的代码中,您可以根据是否定义 DEBUGMODE 来决定要做什么。

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

我也推荐阅读 _DEBUG vs NDEBUGWhere does the -DNDEBUG normally come from?

1- 第一次调试enable/disable方法是在你的补全命令中加上-D,像这样:

gcc -D DEBUG <prog.c>

2- 第二:要启用调试,请定义用这样的调试语句替换的 MACRO:

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

要禁用调试,请定义要用这样的内容替换的 MACRO:

#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);
}