【问题标题】:How to properly escape # character in a makefile?如何正确转义makefile中的#字符?
【发布时间】:2020-12-10 05:25:28
【问题描述】:

我正在学习 makefile,为了尝试一下,我编写了一个包含以下文本的 makefile:

blah: blah.o
        cc blah.o -o blah
blah.o: blah.c
        cc -c blah.c -o blah.o
blah.c:
        echo '\#include <stdio.h>  int main(){ return 0; }' > blah.c
clean:
        rm -f blah.o blah.c blah

不幸的是,通过输入make 命令我得到了这个错误:

blah.c:1:1: error: stray ‘\’ in program
 \#include <stdio.h>  int main(){ return 0; }
 ^
blah.c:1:2: error: stray ‘#’ in program
 \#include <stdio.h>  int main(){ return 0; }
  ^
blah.c:1:11: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘<’ token
 \#include <stdio.h>  int main(){ return 0; }
           ^
Makefile:4: recipe for target 'blah.o' failed
make: *** [blah.o] Error 1

我并不真正理解错误,因为我正确地转义了 # 字符(如我所想)。

感谢任何帮助!

【问题讨论】:

  • 如果你不知道如何在命令行上做某事,那么你绝对没有机会成功使用 make。 Make是一个自动化工具。它使您手动执行的操作自动化。首先尝试在命令行上手动生成源文件,然后您就会知道如何使用 make 来生成。

标签: c bash makefile terminal


【解决方案1】:

这是一个 shell 问题,而不是 makefile 问题。如果您在 shell 提示符下运行命令,而不是从 makefile 中运行,您将看到相同的行为:

$ echo '\#include <stdio.h>  int main(){ return 0; }' > blah.c
$ cat blah.c
\#include <stdio.h>  int main(){ return 0; }

这是简单的 shell 引用规则。如果您在 shell 中使用单引号,那么单引号字符串中的任何内容都不会被 shell 解释。它将按原样编写。所以,不要引用它:

blah.c:
    echo '#include <stdio.h>  int main(){ return 0; }' > blah.c

【讨论】:

  • 这就是blah.c:1:21: warning: extra tokens at end of #include directive。它应该是printf '#include &lt;stdio.h&gt;\nint main(){ return 0; }' &gt; blah.c 以获得最大的可移植性。
  • 嗯,是的,生成的字符串是否有意义是另一个问题:)
  • 很奇怪,如果我写 echo '#include \n int main(){ return 0; }' > blah.c 在 makefile 中它可以很好地编译,但是如果我只写 echo "Hello \n World" ,则无法识别换行符。
  • 双引号与单引号。此外,您应该使用 printf,因为与转义字符相关的回显行为未标准化,甚至在同一系统上的 shell 之间也可能不同(某些 shell 具有内置回显)
【解决方案2】:

问题是没有必要在'...' 字符串中转义字符——它们都是文字,包括\(也就是说,没有办法'...' 字符串中的转义字符)。因此,您在 blah.c 中的 # 之前会得到一个文字 \,这会阻止 C 预处理器将其视为指令。

删除\,它应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2011-12-01
    • 2022-01-01
    • 2011-08-05
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 2011-01-05
    相关资源
    最近更新 更多