0

我有一个带有函数定义的 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 我会得到一个版本,否则我会得到另一个版本。我需要的是两个版本。我知道我可以复制和粘贴代码并定义/取消定义符号,但这看起来很乱。有没有一种方法可以在不重复代码的情况下定义这两个函数?

4

5 回答 5

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;
    }

或者使用脚本生成不同功能的代码。

于 2013-11-07T17:28:13.750 回答
1

好吧,你可以编译你的代码两次:

cc -DSOMEFEATURE x.c -o x1.o
cc -x.c -o x2.o

然后链接那些对象文件。请记住,您需要确保没有“两个版本”的其他函数将被复制并且链接器不会喜欢它。因此,您需要在它们周围放置 ifdef,或者确保您的文件仅包含带有“ifdef SOMEFEATURE”的函数。

总的来说,我认为这是一个糟糕的设计决策,应该尽可能避免它。

于 2013-11-07T17:02:34.780 回答
0

你可以:

  • 将通用代码移动到子例程(函数)中。

  • 将标志作为参数传递:例如:

    myfunction_withfeature() { myfunction_common(true); }

于 2013-11-07T17:38:06.217 回答
0

在我看来,如果您只想使用预处理器,@Thomas Padron-McCarth 有正确的处理方式。如果事情变得过于复杂,那么您将需要切换到其他类型的模板或代码生成系统。我个人使用过输出 C 或 C++ 代码的 perl 脚本,然后是Cog,它使用 python 动态替换部分代码。

于 2013-11-07T17:36:22.270 回答
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;
}
于 2013-11-07T17:48:38.750 回答