2017-05-04 88 views
0

我想启用“printf(”宏消息是%d \ n“,MESSAGE);”在运行时间。例如,如果我在运行时给出参数10,它应该打印该消息。如果没有给出,它不应该打印此消息。是否有可能?在运行时启用DEBUG消息

#include <stdio.h> 

#define MESSAGE 10 

int foo; 
void main(int argc, char *argv[]) 
{ 
     foo = atoi(argv[1]); 
     printf("foo is %d\n", foo); 

#if MESSAGE==foo 
     printf("macro MESSAGE is %d\n",MESSAGE); 
#endif 
} 
+0

'if'检查有什么问题? –

+0

预处理器无法使用运行时值。 – BLUEPIXY

+0

或者你的意思是编译时间...那么这是一个不同的球赛。 –

回答

3

我们可以定义有条件的基于预处理器宏宏在编译时什么宏的定义是控制:

#if DEBUGGING 
#define debug(format, ...) fprintf(stderr, format, __VA_ARGS__) 
#else 
#define debug(format, ...)() 
#endif 

debug宏本身实际上是GCC's manual一个例子。

或者,我们可以做一个类似的功能,在运行时间一些变量的值检查:

#include <stdarg.h> 
#include <stdio.h> 
int debugging = 10; 
void debug(int msglevel, const char *fmt, ...) 
{ 
    if (debugging < msglevel) return; 
    va_list va; 
    va_start(va, fmt); 
    vfprintf(stderr, fmt, va); 
    va_end(va); 
} 
... 
debug(10, "Error: %s\n", "some explanation"); 

全功能使得它更容易做多的详细程度比较大。当然,我们仍然可以在编译时使用函数的另一个定义来完全禁用它。有关可变参数,请参见va_arg(3) man page

+0

@ikkachu,谢谢。它非常酷,工作正常 – Akaash

相关问题