0

在我的 C++ 代码中有几个 fprintf 语句,用于调试。因为我可能会再次需要它们,所以我暂时不想评论它们。但是,我需要快速执行程序,所以我想避免它们被打印出来,因为它们目前是这样(我将 stderr 重定向到一个文件)。

最好这将由用户将参数传递给程序来确定,我将这样提取:

main (int argc, char *argv[])
{
int isPrint=0;
if (argc > 1 ) {
       isPrint = atoi ( argv[2]);
}

}

我想将 fprintf 重命名为另一个名称,然后根据isPrint的值从该函数使用相同的参数执行 fprintf 调用;然而,后来我意识到 fprintf 可以有很多不同类型的参数和不同数量的参数;并且我不知道任何通用的方式来声明我自己的功能与这些要求。

所以我想知道如何创建一个函数,它的工作原理与 fprintf 完全一样,但它需要额外的参数isPrint;或者如何以另一种方式解决上述问题。

第一次发布后的补充信息:一种解决方案是在每个 fprintf 语句之前添加:

if (isPrint == true )
4

4 回答 4

5

典型的方法是使用预处理器编译掉对fprintf().

你会做这样的事情:

#if defined DEBUG
#define LOG(a) fprintf a
#else
#define LOG(a)
#endif

And in the code you would do:

LOG(("The value is %f", some_variable));

Note the double parenthesis, that's just to make the syntax work. You can do it nicer, but this is simpler to explain.

Now, you would either just edit the code to #define or #undef the DEBUG preprocessor symbol at the top of the file, or pass suitable options to the compiler (-D for GCC).

于 2012-04-19T12:56:24.807 回答
1

For debugging purpose you can use the variable argument macro:

#ifdef DEBUG
#define FPRINTF(...) fprintf(__VA_ARGS__)
#else
#define FPRINTF(...)
#endif

Be attentive that, if you use fprintf directly instead of FPRINTF then since you are defining a library function, it should appear after #include<> of that function.

于 2012-04-19T12:57:02.083 回答
1

First note that if this is just for debugging, I'd agree that the typical way is to use macros or preprocessor defines to tell the compiler to include logging or not.

However, if you don't want it removed entirely by the compiler (so that you can turn the printing on or off with an argument), you could write your own log function that takes isPrint and some string, and then use snprintf() to format the string before you call it.

Something along these lines:

void myLog(int isPrint, char *message)
{
    if(isPrint == 1)
    {
        fprintf(logFile, "%s", message);
    }
}

char msg[64];
snprintf(msg, 64, "Test Message %d", 10);
myLog(isPrint, msg);

It may also be possible to wrap fprintf() in your own varags function, but that would be more complicated.

于 2012-04-19T13:09:42.263 回答
0

It depends how much flexibilty you've got in changing the code and whether you want to be able to switch this off at runtime or just compile time.

I'd suggest you wrap it in your own variadic function (for tips look here) and then you've encapsulated the functionality.

Your function will essentially be just a thin wrapper round fprintf() but at this point you can then either use the preprocessor to ensure that your logging function does nothing if you compile it out, or you can do an integer comparison with, say, a logging level at runtime so that the underlying fprintf() only gets called if your debugging level is high enough.

于 2012-04-19T13:39:13.413 回答