得到交流常数的值

aza*_*sup 6 c c++

我有一个.h文件,其中数百个常量被定义为宏:

#define C_CONST_NAME Value
Run Code Online (Sandbox Code Playgroud)

我需要的是一个可以动态获取其中一个常量值的函数.

需要的函数头:

int getConstValue(char * constName);
Run Code Online (Sandbox Code Playgroud)

这在C语言中是否可能?

----编辑

谢谢你的帮助,那很快:)

因为我认为没有奇迹解决方案满足我的需求.

实际上我使用的头文件是由"SCADE:http://www.esterel-technologies.com/products/scade-suite/ " 生成的.

我从@Chris获得的解决方案是使用一些python来生成完成工作的c代码.

现在我要对其进行一些优化以找到常量名称.我有超过5000个常数O(500 ^ 2)

我也在看"X-Macros"我第一次听到它,它在C中工作,因为我不允许使用c ++.

谢谢

Ned*_*der 6

C不能为你做这件事.您需要将它们存储在不同的结构中,或使用预处理器来构建您需要的数百个if语句.像Cogflect这样的东西可以提供帮助.


Chr*_*rle 4

干得好。您需要为每个新常量添加一行,但它应该让您了解宏如何工作:

#include <stdio.h>

#define C_TEN 10
#define C_TWENTY 20
#define C_THIRTY 30

#define IFCONST(charstar, define) if(strcmp((charstar), #define) == 0) { \
    return (define); \
}

int getConstValue(const char* constName)
{
    IFCONST(constName, C_TEN);
    IFCONST(constName, C_TWENTY);
    IFCONST(constName, C_THIRTY);

    // No match                                                                                                                                                                                                                              
    return -1;
}

int main(int argc, char **argv)
{
    printf("C_TEN is %d\n", getConstValue("C_TEN"));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我建议你运行gcc -E filename.c看看 gcc 对这段代码做了什么。