用于创建查找表的 C 预处理器宏

标签 c macros preprocessor

我有一个查找表,它链接了我所有的“两个字符命令”,例如AA、AB、SS,按第一个字符的字母顺序排列到其对应的函数地址。

command_list 中的行(即分支)对应于它们的 ASCII 值减去“A” IE。 command_list[0] 是所有“A”命令 command_list[1] 是所有“B”命令。

此外,第二个字符在“分支”下分配了一个“ Twig ”

例如如果命令 AA 被分配给 Twig 0.... command "AA" 变为 command_list['A' -'A']->twig[0] 变为 command_list[0]->twig[0] 然后我可以调用地址 command_list[0]->twig[0]->leaf_function

处的函数

我的问题是

  1. 使用 #define CREATE_TWIG(CHAR_1, CHAR_2) twig_t twig_##CHAR_1##CHAR_2 = {.twig_id = 'CHAR_1', .leaf_function = &command_##CHAR_1##CHAR_2}; 我可以创建一根 Twig ,但 .twig_id 很困惑,并且始终被分配 (int) 1,而不是 CHAR_1 的十进制值。这是为什么?
  2. 如何使用宏自动执行此部分?注意: Twig 的数量可以是一个非负整数,最多 26 个,即 A 到 Z
twig_t * A_twigs[2] =  {&twig_AD, &twig_AS};

branch_t A_branch = {.branch_id = 'A', .num_twigs = 2, .twigs = A_twigs};

tree command_list[1] = {&A_branch};

其余代码/typedef/结构

 typedef struct{
        uint8_t twig_id;
        void * leaf_function;
    }twig_t;

    typedef struct{
        uint8_t branch_id;
        uint8_t num_twigs;
        twig_t **twigs;
    }branch_t;

    typedef branch_t* tree;

    void command_AD(void);
    void command_AS(void);

    #define CREATE_TWIG(CHAR_1, CHAR_2) twig_t twig_##CHAR_1##CHAR_2  = {.twig_id =  'CHAR_1', .leaf_function = &command_##CHAR_1##CHAR_2};

    CREATE_TWIG(A,S)

    twig_t twig_AD = {.twig_id = 'D', .leaf_function = &command_AD};


    twig_t * A_twigs[2] =  {&twig_AD, &twig_AS};

    branch_t A_branch = {.branch_id = 'A', .num_twigs = 2, .twigs = A_twigs};

    tree command_list[1] = {&A_branch};

最佳答案

把“”去掉吗? CHAR_1 包含您的字符 ascii 值。

关于用于创建查找表的 C 预处理器宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58919131/

相关文章:

c - 将数字四舍五入为 int 大小边界字节数的方法

c - FreeRTOS 中 mtCOVERAGE_TEST_MARKER 宏的用途

c++ - 使用#ifdefs 进行代码选择会创建丑陋的结构 - 替代方案?

c - 用c计算欧氏距离的最快方法

macros - 如何为 iOS 和 macOS 编写通用的 Swift 代码。在 cocoa 中我可以使用#ifdef,我现在该怎么办?

c - 用于用户名验证的正则表达式修改

machine-learning - 有没有办法在 scikit-learn 中保存预处理对象?

c# - C# 预处理器指令可以嵌套吗?

c - 如何将函数放入宏中?

c - 在所需时刻显示缓冲区