c - 如何为词法分析器创建makefile?

标签 c makefile lex lexical-analysis

我想使用 flex 为我的词法分析器制作一个 make 文件,我已经尝试了很多 make 文件的模板,但它没有用,所以请帮我建立一个,这里是编译代码的行:

lex -t lexical.l > lexical.c
cc -c -o lexical.o lexical.c
cc -o lexy lexical.o -ll

最佳答案

如果您使用的是 GNU make,则根本不需要 makefile。内置规则涵盖您的用例。

让我们打印内置规则,看看 make 是否知道如何将 '%.l' 转换为 '%.c'。

$ make -p | grep -A6 '\.l\.c'
make: *** No targets specified and no makefile found.  Stop.
.l.c:
#  Implicit rule search has not been done.
#  Modification time never checked.
#  File has not been updated.
#  recipe to execute (built-in):
    @$(RM) $@ 
     $(LEX.l) $< > $@

确实如此。以类似的方式,您可以检查 GNU make 是否知道如何从“%.c”构建“%.o”以及如何从“%.o”构建“%”可执行文件。

假设在当前目录中有一个 lexical.l 并且没有 makefile 让我们看看如何构建 lexical

$ make -n lexical
rm -f lexical.c 
lex  -t lexical.l > lexical.c
cc    -c -o lexical.o lexical.c
cc   lexical.o   -o lexical
rm lexical.c lexical.o

太棒了。我们只缺少用于链接您要求的 -ll 标志。让我们将它添加到 LDLIBS

$ make -n lexical LDLIBS=-ll
rm -f lexical.c 
lex  -t lexical.l > lexical.c
cc    -c -o lexical.o lexical.c
cc   lexical.o  -ll -o lexical
rm lexical.c lexical.o

瞧!因此,您的 makefile 可以短至

LDLIBS=-ll
all: lexical

关于c - 如何为词法分析器创建makefile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13394915/

相关文章:

c++ - 在另一个系统上构建时禁用特定的 C++ 行和#includes

linux - "Make install"与 "Make install clean"?

c++ - 如何使用 Makefile 变量作为文件包含在 g++ 命令中?

raspberry-pi - 如何在 Raspbian Raspberry 上安装 GNU flex 或 lex

c - 如何区分没有相等运算符的两个整数?

c - C 中的符号常量

c - OpenMP 并行区域的不同运行时间

c - 从文件中的字符串获取字符串长度

c - 编辑从 lex 和 bison 文件生成的 C 文件