仅在_DEBUG定义时打印:c

时间:2014-09-02 05:20:55

标签: c preprocessor-directive

我只想在定义_DEBUG时打印信息

#define DEBUG(y) y == true ? #define _DEBUG true  : #define _DEBUG false

#ifdef _DEBUG
#define Print(s)  printf(s); 
#endif

获取错误:

error: '#' is not followed by a macro parameter

有关如何使用预处理器指令实现此目的的任何建议吗?

我打算在我的主编中使用它:

DEBUG(true);
Print("Inside main in debug mode");

7 个答案:

答案 0 :(得分:5)

cannotrun-time重新定义了MACRO。 你也没有#define inside of another #define,就像你在代码的第一行尝试一样。

您可以这样做:

#ifdef _DEBUG
#define Print(s)  printf("%s", s)
#else
#define Print(s)  
#endif

从你的主要使用它:

#define _DEBUG
Print("Inside main in debug mode");
#undef _DEBUG
Print("Inside main debug mode off");

如果你真的需要在运行时打开和关闭调试,你可以这样做:

void PrintIf(BOOL dbg, char * msg)
{
   if (dbg)
   {
       printf("%s", msg)
   }
}

并像这样使用

y = TRUE;
PrintIf(y,"Inside main in debug mode");
y = FALSE;
PrintIf(y,"Inside main debug mode off");

答案 1 :(得分:2)

试试这个:

#ifdef DEBUG
#define Print(s) printf("%s", s)
#else
#define Print(s)
#endif

然后:

#define DEBUG
Print("Inside main in debug mode");

答案 2 :(得分:1)

  

我打算在我的主编中使用它:

DEBUG(y);
Print("Inside main in debug mode");

抱歉,ifdef是编译时间(非运行时)。您可以使用全局bool和运行时检查来启用和禁用调试。

答案 3 :(得分:1)

你不能像你想要的那样用宏创建预处理器语句;它不起作用,也是不允许的。有条件打印,请参阅C #define macro for debug printing

答案 4 :(得分:1)

问题出现在这里:

#define DEBUG(y) y == true ? #define _DEBUG true  : #define _DEBUG false

在引入#defines时,定义#出现在行的开头,而不是以后(尽管)预处理器通常允许一行或两行缩进。)您需要重写{{1}消除三元运算符只是:

#define

虽然您可以使用宏扩展定义,但是经常会引入其他错误。通常最好只在#ifdef _DEBUG #define Print(s) printf(s); #endif 语句中包装_DEBUG代码:

#ifdef

答案 5 :(得分:1)

宏在预处理阶段被替换

#define DEBUG(y) y == true ? #define _DEBUG true  : #define _DEBUG false

此语句将在编译时进行评估。

在编译时评估条件运算符(三元运算符)。所以你得到这个错误,并且必须始终在语句的开头使用#manrator,这是你正在做的第二个错误。

你可以这样更好地使用它

#define DEBUG
printf ("true");
#else
printf ("false");

您还可以使用gcc选项-D

动态定义此宏
gcc -D DEBUG filename.c -o outputFile

答案 6 :(得分:0)

第一行不正确:

#define DEBUG(y) y == true ? #define _DEBUG true  : #define _DEBUG false

您不能在预处理程序指令中使用#define(如另一个#define

它没有意义,因为preprocessing发生在真正的编译之前(所以在运行时之前,当你的y有一些价值时)。阅读cpp preprocessor documentation。回想一下,有时预处理器甚至是一个不同的程序(/lib/cpp),但今天是大多数C编译器的第一阶段。

您可以要求提供源代码的预处理形式(例如,如果使用GCC,请使用gcc -C -E source.c > source.i)并使用寻呼机(less source.i)或编辑器查看该表单。< / p>