首页 > 解决方案 > 在 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.mkandsubmakeB.mk和主 Makefile。当你编译时make TARGET=submakeAfunA()被编译并运行。如果你运行make TARGET=submakeBfuncB()将被编译并运行。

现在我被要求在相应的 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 源文件的文档或资源。如果有人可以向我指出这样的资源,那也很棒

标签: cmakefileconfig

解决方案


这个问题并不完全清楚,但似乎这个词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_CMDT_B_CMDare #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

推荐阅读