在此示例代码中,程序员定义或注释掉一个宏,以便从已发布的软件中删除一个函数。
#include <stdio.h>
#define MACRO //or omitted
#ifdef MACRO
void Function(const char* str)
{
printf("%s\n", str);
}
#else
#define Function(str)
#endif
int main(void)
{
Function("hello world");
getchar();
return 0;
}
这有什么问题吗?
答案 0 :(得分:0)
它会起作用。但是这样就删除了整个符号。我更喜欢以下方法。
#include <stdio.h>
#define MACRO 1
#if MACRO
void Function(const char* str)
{
printf("%s\n", str);
}
#else
void Function(const char *str){}
#endif
int main(void)
{
Function("hello world");
getchar();
return 0;
}
以下内容发生了变化:
#if
现在比较一个布尔值。您的IDE现在能够找到在所有情况下定义MACRO
的位置。 (右键单击,查找定义) MACRO
更改为2,更改Function
的全部含义。例如,发布编译的变体可能包含打印到文件或系统日志。 Function
总会有一个符号,即使它没有任何作用,即使在编译代码中也是如此。这样做的好处是参数中的字符串文字仍然计入大小统计信息。作为嵌入式开发人员,我发现这很重要。显然,这部分是制作代码的人的偏好。
答案 1 :(得分:0)
即使您的解决方案有效,我也更喜欢以下方法:
#include <stdio.h>
#define MACRO //or omitted
#ifdef MACRO
#define FUNCTION(a) Function(a);
#else
#define FUNCTION(a)
#endif
#ifdef MACRO
void Function(const char* str)
{
printf("%s\n", str);
}
#endif
int main(void)
{
FUNCTION("hello world")
getchar();
return 0;
}
注意:FUNCTION是宏,Function是函数的实际名称
这可以通过在启用MACRO时将宏FUNCTION(a)定义为对Function(const char *)的调用来实现。另一方面,当禁用MACRO时,对FUNCTION(a)的调用将被定义为空。
我倾向于喜欢这种方法,因为从定义函数定义的宏中抽象出用于定义调用的宏会更容易。您可能遇到处于释放模式的情况,您只需要删除对Function的一些调用。在这种情况下,仍然需要Function()的定义。例如:
#include <stdio.h>
#define DEBUG //or omitted
#ifdef DEBUG
#define FUNCTION(a) Function(a);
#else
#define FUNCTION(a)
#endif
void Function(const char* str)
{
printf("%s\n", str);
}
int main(void)
{
// Call function with Hello World only in debug
FUNCTION("hello world")
getchar();
// Call function with goodbye world in both debug and release
Function("goodbye world");
return 0;
}