【发布时间】:2014-12-19 12:04:20
【问题描述】:
我想使用 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
如您所见,我尝试了许多不同的连接方式,但都没有奏效。
也许还有另一种更好的方法来生成这样的字符串?
【问题讨论】:
-
没有条件
#defines。至于隐式函数声明警告,strcpy声明在string.h标头中。 -
我认为宏无法实现您想要的,因此您可能需要发布另一个问题。
-
是的 - 我认为这也是“几乎可能”。当然,当我简单地将字母添加到代码中的变量时,它会起作用。但这每次都会执行,并且只传递一个静态字符串。那么将没有使用预处理器的巧妙解决方案。我必须返回一个静态字符串,每次我都必须在源代码中手动更改它。
标签: c gcc c-preprocessor avr-gcc