Wayou

考察下面的示例代码:

main.c

#include <stdio.h>

int main(){
    printf("hello world!");
    return 0;
}

正常情况下,通过 gcc 在命令行将其编译后产出相应文件,可执行文件或 object 文件等。

$ gcc -o main.out main.c

上面命令编译后首页 main.out 可执行文件。

$ ./main.out
hello world!

Make 工具

通过 make 命令,可以将上面的编译进行有效自动化管理。通过将从输入文件到输出文件的编译无则编写成 Makefile 脚本,Make 工具将自动处理文件间依赖及是否需要编译的检测。

make 命令所使用的编译配置文件可以是 MakefilemakefileGUNMake

其中定义任务的基本语法为:

target1 [target2 ...]: [pre-req-1 pre-req-2 ...]
    [command1
     command2
     ......]

上面形式也可称作是一条编译规则(rule)。

其中,

  • target 为任务名或文件产出。如果该任务不产出文件,则称该任务为 Phony Targetsmake 内置的 phony target 有 all, installclean 等,这些任务都不实际产出文件,一般用来执行一些命令。
  • pre-req123... 这些是依赖项,即该任务所需要的外部输入,这些输入可以是其他文件,也可以是其他任务产出的文件。
  • command 为该任务具体需要执行的 shell 命令。

Makefile 示例

比如文章最开始的编译,可通过编写下面的 Makefile 来完成:

Makefile

all:main.out

main.out: main.c
    gcc -o main.out main.c

clean:
    rm main.out

上面的 Makefile 中定义了三个任务,调用时可通过 make <target name> 形式来调用。

比如:

$ make main.out
gcc -o main.out main.c

产出 main.out 文件。

再比如:

$ make clean
rm main.out

clean 任务清除刚刚生成的 main.out 文件。

三个任务中,all 为内置的任务名,一般一个 Makefile 中都会包含,当直接调用 make 后面没有跟任务名时,默认执行的就是 all

$ make
gcc -o main.out main.c

命令的换行

如果一条编译规则中所要执行的 shell 命令有单条很长的情况,可通过 \ 来换行。

main.out: main.c
    gcc \
    -o main.out \
    main.c

注意 \ 与命令结尾处需要间隔一个空格,否则识别出错。

main.out: main.c
    gcc\ # 

相关文章:

  • 2021-07-08
  • 2021-06-11
  • 2021-10-11
  • 2022-03-04
  • 2022-01-05
  • 2021-10-01
  • 2021-07-07
  • 2021-05-30
猜你喜欢
  • 2021-11-11
  • 2021-10-31
  • 2022-02-15
  • 2022-01-01
  • 2018-07-07
  • 2021-12-18
  • 2021-06-22
相关资源
相似解决方案