GNU Makefile中多行宏中的变量分配问题 [英] Variable assignment issue in multiline macro in GNU Makefile

查看:69
本文介绍了GNU Makefile中多行宏中的变量分配问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个简单的问题,但我找不到原因/解决方案.我已经在Makefile中定义了一个简单的shell函数,其功能如下:

I understand that this is a simple question but i am unable to find the reason/solution. I have defined a simple shell function in Makefile that is doing as follows,

define my_function
    my_var="Hello";
    echo $(my_var);
    echo Recvd arg = $(1);
endef

请注意,这是在makefile中定义的,而我在其中一条规则中使用

Please note that this is defined inside a makefile and I am using in one of my rule,

 $(obj_dir)/%.o: $(src_base)/%.cpp 
 $(q)$(CXX) $(CXXFLAGS) -o $@ 
 $(call my_function, $@) 

但是局部变量my_var永远不会被赋值.我已经尝试过使用eval,set和export进行很多操作,但是似乎没有任何东西为函数中的变量赋值.而echo $(my_var)只会打印任何内容.这在shell脚本中工作正常,但是在Makefile中使用时,会导致此问题.

But the local variable my_var never gets assigned. I have tried many things using eval, set and export but nothing seems to be assigning value to variable in the function. And echo $(my_var) will just print nothing. This works fine in shell script but when used in Makefile, it causes this issue.

请帮助我解决这个问题.帮助将不胜感激.

Please help me sort this out. Help will be highly appreciated.

推荐答案

Make将在单独的shell中调用配方的每个逻辑行.所以对于像这样的东西:

Make will invoke every logical line of a recipe in a separate shell. So for something like:

foo:
        echo line1
        echo line2

这将启动两个不同的shell,一个运行第一个echo,另一个运行第二个shell(实际上make具有一些性能增强,因此,如果命令足够简单",它将避免启动shell,但是行为是两种方式都一样).

this starts two different shells, one to run the first echo and another to run the second (in reality make has some performance enhancements so that it avoids starting a shell if the command is "simple enough", but the behavior is the same either way).

因此,如果您在一行中写一个变量,然后在另一行中使用它,那么当shell退出时,该值将丢失:

So if you write a variable in one line then use it in another line, the value will be lost when the shell exits:

foo:
        foo=bar
        echo $$foo

不打印任何内容.为了使用多条物理线而不是一条逻辑线,您必须以反斜杠/换行符组合结束每条物理线:make将收集它们并将它们发送到单个shell中:

prints nothing. In order to use multiple physical lines but a single logical line you must end each physical line with a backslash/newline combination: make will collect them and send them to a single shell:

foo:
        foo=bar; \
        echo $$foo

将显示栏".

即使在多行变量分配中也是如此.另外,当您要引用 shell 变量时,必须使用$$(就像我在上面所做的那样).使用单个$将通过该名称引用 make 变量.而且shell变量引用不支持括号(但是如果需要,可以使用花括号).所以你必须写:

This holds true even within multi-line variable assignments. Also, you must use $$ (as I do above) when you want to refer to a shell variable. Using a single $ will refer to the make variable by that name. And the shell variable referencing doesn't support parentheses (but you can use curly braces if you want). So you must write:

define my_function
    my_var="Hello"; \
    echo $$my_var; \
    echo Recvd arg = $(1);
endef

这篇关于GNU Makefile中多行宏中的变量分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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