Makefile 命令

在一个规则中,除了目标和目标依赖外,还有一个重要的部分:命令。

命令一般由shell命令(echo、ls)和编译器的一些工具(gcc、ld、ar、objcopy等)组成,使用tab键缩进。

.PHONY: clean
a.out: hello.c
    echo "start compiling..."
    gcc -o a.out hello.c
    echo "compile done"
clean:
    rm -f a.out hello.o

命令是make在编译程序时真正要执行的部分。对于规则中的每一个命令,make会开一个进程执行,每条命令执行完,make会监测每个命令的返回码。

  • 若命令返回成功,make继续执行下一个命令
  • 若命令执行出错,make会终止执行当前的规则,退出编译流程

make每执行一条命令,会把当前的命令打印出来。如上面的Makefile,当你使用make命令编译时,Makefile的打印信息如下:

wit@pc:/home/makefile# make
echo "start compiling..."
start compiling...
gcc -o a.out hello.c
echo "compile done"
compile done

如果你不想在make编译的时候打印正在执行的执行,可以在每条命令的前面加一个@

.PHONY: clean
a.out: hello.c
    @echo "start compiling..."
    @gcc -o a.out hello.c
    @echo "compile done"
clean:
    rm -f a.out hello.o

添加@以后,make在编译时就不会打印每条正在执行的命令了:

wit@pc:/home/makefile# make
start compiling...
compile done
《Makefile工程实践》视频教程,一线开发工程师独家录制,网上首家讲解Makefile的实战课程。从零开始,教你一步一步编写一个工程项目的Makefile,支持使用第三方静态库、动态库,支持指定模块或目录编译生成静态库、动态库,赠送企业级的Makefile模板,学完即可拿来使用,投入项目开发实战,具备独立开展项目开发和管理的能力。详情请点击淘宝链接:Linux三剑客