gpt4 book ai didi

C 预处理器获取带串联的选项列表

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:11 25 4
gpt4 key购买 nike

我想使用 C 预处理器生成依赖于其他编译选项的选项列表。

(或者我可以问如何将多个字符串连接成一个定义?)

这里我有一个示例 (avr-gcc) 来说明我想做什么,但它不起作用:

// C preprocessor get option list with concatenation

#include <stdint.h>

// #define CompileOption1 1 // first compile option
#define CompileOption2 1 // second compile option

static char options[20] = " "; // string of options

/**********************************************************/
void exec_command (uint8_t opt) {
switch (opt) {
#define MAIN_COMMAND "FirstDefinition"
#ifdef CompileOption1
case 'b':
#define MAIN_COMMAND (MAIN_COMMAND ## "b")
break;
#endif
#ifdef CompileOption2
case 't':
#define MAIN_COMMAND MAIN_COMMAND ## t
break;
case 'u':
#endif
case 's':
// #define MAIN_COMMAND (MAIN_COMMAND ## "s")
break;
case 'v':
// #define MAIN_COMMAND (MAIN_COMMAND ## v)
break;
case 'r':
// #define MAIN_COMMAND "Blabla"
break;
}
// #define MAIN_COMMAND "Testomat"
strcpy(options, MAIN_COMMAND);
}

/**********************************************************/
int main(void) {

while(1) {
exec_command('v');
// doing something with the options here
}
}

我想获得保存在字符串中的正确“选项”列表。

编译显示这些错误:

main.c: In function ‘exec_command’:
main.c:21:0: warning: "MAIN_COMMAND" redefined [enabled by default]
main.c:13:0: note: this is the location of the previous definition
main.c:36:2: warning: implicit declaration of function ‘strcpy’ [-Wimplicit-function-declaration]
main.c:36:2: warning: incompatible implicit declaration of built-in function ‘strcpy’ [enabled by default]
main.c:36:1: error: ‘MAIN_COMMANDt’ undeclared (first use in this function)
main.c:36:1: note: each undeclared identifier is reported only once for each function it appears in

如您所见,我尝试了多种不同的连接方式,但都没有奏效。

也许还有另一种更好的方法来生成这样的字符串?

最佳答案

我认为您需要的代码更像:

#define B_OPT
#define T_OPT
#define S_OPT
#define V_OPT

void exec_command(uint8_t opt)
{
switch (opt)
{
#define MAIN_COMMAND "FirstDefinition"
#ifdef CompileOption1
case 'b':
#undef B_OPT
#define B_OPT "b"
break;
#endif
#ifdef CompileOption2
case 't':
#undef T_OPT
#define T_OPT "t"
break;
case 'u':
#endif
case 's':
#undef S_OPT
#define S_OPT "s"
break;
case 'v':
#undef V_OPT
#define V_OPT "v"
break;

}
strcpy(options, MAIN_COMMAND B_OPT T_OPT S_OPT V_OPT);
#undef B_OPT
#undef T_OPT
#undef S_OPT
#undef V_OPT
}

我不确定你是否也会#undef MAIN_COMMAND。在一个层面上,最后四个 #undef 操作不是必需的。您也可以根据需要重新定义 MAIN_COMMAND 的值;具体要求尚不清楚。

关键是为要连接成最终字符串的组件定义宏值,然后依靠字符串连接将相关部分组成一个字符串。

我不完全相信您正在尝试做的事情是个好主意,但我认为这是实现您似乎想要的事情的一种方式。

关于C 预处理器获取带串联的选项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27565771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com