使用预处理器的 C 多个函数定义

标签 c c-preprocessor

我有一个包含函数定义的 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/

相关文章:

c - C代码中忽略的模数操作数

c - C 项目的 IDE 中的预处理器感知代码导航

c - 当 C 预处理器宏被定义两次时会发生什么?

C#pragma 是预处理还是编译时操作?

c - 使用 TQLI 算法进行特征值计算失败并出现段错误

c - 是否可以重复getopt

c - 为什么 $$ 不接受类型 char

C - 没有使用参数指针获得正确的值

我可以使用预处理器使这一点更清楚吗?

c++ - 乘法宏给出错误的答案