我有一个带有函数定义的C文件。
#ifdef SOMEFEATURE
myfunction_withfeature()
#else
myfunction_withoutfeature()
#endif
{
do_something;
#ifdef SOMEFEATURE
do_one_way;
#else
do_another_way;
#endif
do_something_else;
}
如果我在标题或Makefile中定义SOMEFEATURE,我会得到一个版本,如果没有,我会得到另一个版本。我需要的是两个版本。我知道我可以复制并粘贴代码并定义/取消定义符号,但这看起来很混乱。有没有办法可以定义两个函数而不重复代码?
答案 0 :(得分:2)
一种可能性是将该功能放在一个单独的文件中,假设 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;
}
使用脚本生成不同功能的代码。
答案 1 :(得分:1)
好吧,您可以使用以下代码编译代码两次:
cc -DSOMEFEATURE x.c -o x1.o
cc -x.c -o x2.o
然后链接这些对象文件。请记住,您需要确保没有“两个版本”的其他功能将被复制,链接器将不喜欢它。所以你需要在它们周围放置ifdef,或者确保你的文件只包含“ifdef SOMEFEATURE”的函数。
一般来说,我认为这是一个糟糕的设计决定,如果可能的话应该避免它。
答案 2 :(得分:0)
答案 3 :(得分:0)
你可以:
将公共代码移动到子程序(函数)中。
传递一个标志作为参数:例如:
myfunction_withfeature() { myfunction_common(true); }
答案 4 :(得分:0)
my_function_withfeature()
{
my_common_function(1);
}
my_function_withoutfeature()
{
my_common_function(0);
}
my_common_function(int feature)
{
do_something;
if (feature == 1) {
do_one_way;
}
else {
do_another_way;
}
do_something_else;
}