一种可能性是将函数放在一个单独的文件中,比如说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;
}
或者使用脚本生成不同功能的代码。