c - 为什么 $(< file.txt) 不适用于 makefile?

标签 c makefile

使用命令行我得到了所需的输出

 $ ./program $(< file.txt)
 ./program 1 2 3 4 5

但有一个 makefile

all: program file.txt
    ./program $(< file.txt)
    @rm -f program
    
program: program.c
    gcc program.c -o program

我得到了输出

gcc program.c -o program
./program

最佳答案

因为在 makefile 中,$(...)语法用于变量插值。因此,您的 makefile 尝试扩展名为 < file.txt 的 makefile 变量/环境变量的值。 。如果未设置,它将扩展为空字符串。

证明:

all:
        echo $(< file.txt)

和 file.txt 包含

now it works

然后执行

% env '< file.txt=Hello world' make
echo Hello world
Hello world

即通过设置名为 < file.txt 的环境变量值(value)Hello world ,问候语被打印出来。解决方法是转义 $字符加倍:

all:
        echo $$(< file.txt)

然后

% make
echo $(< file.txt)
now it works

Q.E.D.

最后,而$() POSIX shell 中的插值语法,$(< file.txt)不是,但您可以将其替换为 $(cat file.txt)因此它可以与最低限度符合 POSIX 的 shell 一起使用。当然,在 makefile 中,您再次需要将美元加倍,因此获得最大程度的兼容性

$$(cat file.txt)

或者,您可以使用类似的 makefile 工具,即 $(shell ) ,即

 $(shell cat file.txt)

也可以...(现在有一个 $ )。最后你可以用 $(file ) 读取文件GNU makefile 函数也有,即

all:
        echo $(file <file.txt)

工作方式类似,但根本不会调用 shell。

关于c - 为什么 $(< file.txt) 不适用于 makefile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66177027/

相关文章:

makefile - GNU make 似乎忽略了中间文件的非终端匹配规则

c - GNU 读取线 : avoid prompt string in output if input is not interactive

c - 为什么这些构造使用增量前和增量后未定义的行为?

c - GCC - 打印结构的定义

ELF文件的CRC校验和

c - Makefile 依赖项和时间戳

c++ - 无法使用单独的文件夹获取生成文件以使头文件正常工作

makefile - 在 makefile 中的目标内执行 shell 命令

c - 尝试使用 execvp 在 C 中执行外部命令(在类似 shell 的程序中)

sed - 使用 sed 改变 Makefile 变量