1、源代码

hello.c

  1. #include<stdio.h>
  2. int main()
  3. {
  4. printf("hello world");
  5. getchar();
  6. return 0;
  7. }

2、编译过程

方式1:命令行

  • 1、预处理:gcc -E hello.c -o hello.i
  • 2、编译:gcc -S hello.i -o hello.S
  • 3、汇编:gcc -c hello.S -o hello.o
  • 4、链接:gcc hello.o -o hello

    root@ubuntu:/mnt/hgfs/make_demo# ls hello.c root@ubuntu:/mnt/hgfs/make_demo# gcc -E hello.c -o hello.i root@ubuntu:/mnt/hgfs/make_demo# ls hello.c hello.i root@ubuntu:/mnt/hgfs/make_demo# gcc -S hello.i -o hello.S root@ubuntu:/mnt/hgfs/make_demo# ls hello.c hello.i hello.S root@ubuntu:/mnt/hgfs/make_demo# gcc -c hello.S -o hello.o

root@ubuntu:/mnt/hgfs/make_demo# ls

hello.c hello.i hello.o hello.S

root@ubuntu:/mnt/hgfs/make_demo# gcc hello.o -o hello

root@ubuntu:/mnt/hgfs/make_demo# ls

hello hello.c hello.i hello.o hello.S

  • 其他简化写法

    gcc -c hello.c -o hello.o

gcc hello.o -o hello

xin@ubuntu:/mnt/hgfs/make_demo$ ./hello

hello world

gcc -c hello.c

gcc hello.o -o hello

xin@ubuntu:/mnt/hgfs/make_demo$ ./hello

hello world

方式2:makefile

  • makefile ``` hello:hello.o gcc hello.o -o hello hello.o:hello.S gcc -c hello.S -o hello.o hello.S:hello.i gcc -S hello.i -o hello.S hello.i:hello.c gcc -E hello.c -o hello.i

clean: rm hello hello.o hello.S hello.i ```

  • 运行过程

    root@ubuntu:/mnt/hgfs/make_demo# ls

hello.c makefile

root@ubuntu:/mnt/hgfs/make_demo# make

gcc -E hello.c -o hello.i

gcc -S hello.i -o hello.S

gcc -c hello.S -o hello.o

gcc hello.o -o hello

root@ubuntu:/mnt/hgfs/make_demo# ls

hello hello.c hello.i hello.o hello.S makefile

root@ubuntu:/mnt/hgfs/make_demo# ./hello

hello world

root@ubuntu:/mnt/hgfs/make_demo# make clean

rm hello hello.o hello.S hello.i

root@ubuntu:/mnt/hgfs/make_demo# ls

hello.c makefile

3、自动化变量

  • $@ 表示目标文件
  • $^ 表示所有的依赖文件
  • $< 表示第一个依赖文件
  • $? 表示比目标还要新的依赖文件列表
  • 上述makefile可以简化

    hello:hello.o

gcc $^ -o $@

hello.o:hello.S

gcc -c $^ -o $@

hello.S:hello.i

gcc -S $^ -o $@

hello.i:hello.c

gcc -E $^ -o $@

clean:

rm hello hello.o hello.S hello.i