如何通过"make"传递宏定义命令行参数(-D)到C源代码? [英] How to pass macro definition from "make" command line arguments (-D) to C source code?

查看:2167
本文介绍了如何通过"make"传递宏定义命令行参数(-D)到C源代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常使用以下选项将宏定义从"make命令行"传递给"makefile": -Dname =值.可以在makefile中访问该定义.

我还使用类似的编译器选项将宏定义从"makefile"传递到源代码": -Dname = value(许多编译器支持).可以在源代码中访问此定义.

我现在需要的是允许我的makefile的用户能够立即将任意宏定义从"make.exe命令行"传递到源代码",而不必更改makefile中的任何内容. /p>

,因此用户可以输入: make -f mymakefile.mk -SOMEOPTION var = 5

然后直接在代码main.c中可以看到var:

int main()
{
  int i = var;
}

解决方案

以这种方式调用make命令:

make CFLAGS=-Dvar=42

并确保在Makefile中的编译命令中使用$(CFLAGS).正如@jørgensen所提到的,将变量赋值放在make命令之后将覆盖已经定义了Makefile的CFLAGS值.

或者,您可以在CFLAGS以外的其他变量中设置-Dvar=42,然后在CFLAGS中重用此变量,以避免完全覆盖CFLAGS.

I usually pass macro definitions from "make command line" to a "makefile" using the option : -Dname=value. The definition is accessible inside the makefile.

I also pass macro definitions from the "makefile" to the "source code" using the similar compiler option : -Dname=value (supported in many compilers). This definition is accessible in the source code.

What I need now, is to allow the user of my makefile to be able to pass arbitrary macro definitions from the "make.exe commandline" to "source code" right away, without having to change anything in the makefile.

so the user can type : make -f mymakefile.mk -SOMEOPTION var=5

then directly the code main.c can see var :

int main()
{
  int i = var;
}

解决方案

Call make command this way:

make CFLAGS=-Dvar=42

And be sure to use $(CFLAGS) in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make command will override the CFLAGS value already defined the Makefile.

Alternatively you could set -Dvar=42 in another variable than CFLAGS and then reuse this variable in CFLAGS to avoid completely overriding CFLAGS.

这篇关于如何通过"make"传递宏定义命令行参数(-D)到C源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆