我有一个包含函数定义的 C 文件。
#ifdef SOMEFEATURE
myfunction_withfeature()
#else
myfunction_withoutfeature()
#endif
{
do_something;
#ifdef SOMEFEATURE
do_one_way;
#else
do_another_way;
#endif
do_something_else;
}
如果我在 header 或 Makefile 中定义了 SOMEFEATURE,我会得到一个版本,否则我会得到另一个版本。我需要的是两个版本。我知道我可以复制并粘贴代码并定义/取消定义符号,但这看起来很乱。有没有一种方法可以在不重复代码的情况下定义这两个函数?
最佳答案
一种可能性是将函数放在一个单独的文件中,比方说justmyfunction.c:
#ifdef SOMEFEATURE
void myfunction_withfeature()
#else
void myfunction_withoutfeature()
#endif
{
printf("Always doing this.\n");
#ifdef SOMEFEATURE
printf("Doing it one way, with the feature.\n");
#else
printf("Doing it another way, without the feature.\n");
#endif
printf("Always doing this too.\n");
}
然后#include它和其他函数一起在文件中:
#include <stdio.h>
#include "justmyfunction.c"
#define SOMEFEATURE
#include "justmyfunction.c"
int main(void) {
printf("Doing it twice...\n");
myfunction_withfeature();
myfunction_withoutfeature();
printf("Done.\n");
return 0;
}
或者你可以用宏做一些可怕的事情:
#include <stdio.h>
#define DEFINE_MYFUNCTION(function_name, special_code) \
void function_name() \
{ \
printf("Always doing this.\n"); \
\
special_code \
\
printf("Always doing this too.\n"); \
}
DEFINE_MYFUNCTION(myfunction_withfeature, printf("Doing it one way, with the feature.\n");)
DEFINE_MYFUNCTION(myfunction_withoutfeature, printf("Doing it another way, without the feature.\n");)
int main(void) {
printf("Doing it twice...\n");
myfunction_withfeature();
myfunction_withoutfeature();
printf("Done.\n");
return 0;
}
或者使用脚本为不同的函数生成代码。
关于使用预处理器的 C 多个函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19841745/