c - 在 C 中的 Makefile 中定义、编译和执行终端命令
问题描述
在某些任务中,我需要在 .c 文件中运行终端命令。我的 .c 文件中有以下布局,它运行得非常好:
#ifdef CONDITION_A
static const char * funcA(){
#define SIZE 56
#define T_A_CMD "sudo info | grep \"Memory Size:\""
...
...}
#endif
#ifdef CONDITION_B
static const char * funcB(){
#define SIZE 56
#define T_B_CMD "sudo info | grep \"Battery Level:\""
...
...}
#endif
现在假设我们有submakeA.mk
andsubmakeB.mk
和主 Makefile。当你编译时make TARGET=submakeA
将funA()
被编译并运行。如果你运行make TARGET=submakeB
,funcB()
将被编译并运行。
现在我被要求在相应的 submakeA.mk 和 submakeB.mk 文件中定义“T_A_CMD”和“T_B_CMD”。
我有以下布局:1)在主Makefile中:
ifdef t_a_cmd
cflag += -DCONFIG_T_A_CMD='"$(t_a_cmd)"'
endif
ifdef t_b_cmd
cflag += -DCONFIG_T_B_CMD='"$(t_b_cmd)"'
endif
2)在 submakeA.mk 中:
t_a_cmd = sudo info | grep \"Memory Size:\"
3) 在 submakeB.mk 中:
t_b_cmd = sudo info | grep \"Battery Level:\"
4)在.c文件中
#ifndef CONFIG_T_A_CMD
//do nothing
#else
#define T_A_CMD "sudo info | grep \"Memory Size:\""
#endif
#ifndef CONFIG_T_B_CMD
//do nothing
#else
#define T_B_CMD "sudo info | grep \"Battery Level:\""
#endif
#ifdef CONDITION_A
static const char * funcA(){
#define SIZE 56
#ifdef T_A_CMD
...
...
#endif
}
#endif
#ifdef CONDITION_B
static const char * funcB(){
#define SIZE 56
#ifdef T_B_CMD
...
...
#endif
}
#endif
当我运行它时,编译器给了我这个错误:
> Generating info details header file
/bin/sh: 3: syntax error: "(" unexpected
/home/usr/build.mk:59: recipe for target '/home/usr/build/submakeA/A.o' failed
make[1]:***[/home/usr/build/submakeA/A.o] Error2
Makefile:230: recipe for target 'A' failed
make: *** [A] Error
我试图改变#ifdef T_A_CMD
和#endif
周围的位置,但所有的组合都没有帮助。有人可以让我知道出了什么问题吗?此外,我没有找到任何关于在 Makefile 中使用“DCONFIG”和“CONFIG”以及如何将它们一直传递到 .c 源文件的文档或资源。如果有人可以向我指出这样的资源,那也很棒
解决方案
这个问题并不完全清楚,但似乎这个词CONFIG
可能是不必要的并且会引起问题。
我提出以下Makefile
内容。我假设cflag
它的角色类似于更传统的角色CFLAGS
,因为它的值被传递给 C 编译器:
ifdef t_a_cmd
cflag += -DT_A_CMD='"$(t_a_cmd)"'
endif
ifdef t_b_cmd
cflag += -DT_B_CMD='"$(t_b_cmd)"'
endif
...并且我会建议以下.c
文件内容 whereT_A_CMD
和T_B_CMD
are #define
-d 仅当它们尚未通过Makefile
. 更改此现有代码:
#ifndef CONFIG_T_A_CMD
//do nothing
#else
#define T_A_CMD "sudo info | grep \"Memory Size:\""
#endif
#ifndef CONFIG_T_B_CMD
//do nothing
#else
#define T_B_CMD "sudo info | grep \"Battery Level:\""
#endif
...对此:
#ifndef T_A_CMD
#define T_A_CMD "sudo info | grep \"Memory Size:\""
#endif
#ifndef T_B_CMD
#define T_B_CMD "sudo info | grep \"Battery Level:\""
#endif
推荐阅读
- angular - 角度路由不适用于 www 目录
- app-config - 在 app.config 中,supportedRuntime sku 只定义了允许的最早框架
- java - 用其他数组填充数组
- spring-boot - 传递带有@JsonIgnore 标记的属性时抛出错误
- python - 如何在pyqt5中改变QGraphicsSvgItem的颜色?
- java - 无法使用 Spring Boot 从资源中读取文件
- python - 如何解决jupyter中的变量未定义错误
- javascript - 如何将对象从一个函数解析到另一个函数?
- google-colaboratory - 如何在 Google Colaboratory 上使用 Conda 安装 Bob
- angular - 角垫选择