step_1 添加Makfile文件

step_1 添加Makfile文件

  1. 在hello_main.c所在目录新建Makefile文件。

     mdxz_18@mdxz18:~/lzp/workdir/base_code/linux_app/makefile_step/step_1$ vim Makefile
    
  2. 编写Makefile内容如下:

     hello_main:hello_main.c hello_func.c
     gcc -o hello_main hello_main.c hello_func.c -I .
    
     clean:
     	rm -f *.o hello_main
    
  3. make编译默认目标hello_main,编译前后结果如下。

     mdxz_18@mdxz18:~/lzp/workdir/base_code/linux_app/makefile_step/step_1$ ls
     hello_func.c  hello_func.h  hello_main.c  Makefile
     mdxz_18@mdxz18:~/lzp/workdir/base_code/linux_app/makefile_step/step_1$ make
     gcc -o hello_main hello_main.c hello_func.c -I .
     mdxz_18@mdxz18:~/lzp/workdir/base_code/linux_app/makefile_step/step_1$ ls
     hello_func.c  hello_func.h  hello_main  hello_main.c  Makefile
    
  4. 运行编译出的hello_main:

     mdxz_18@mdxz18:~/lzp/workdir/base_code/linux_app/makefile_step/step_1$ ./hello_main
     hello ,world.
     output i=0.
     output i=1.
     output i=2.
     output i=3.
     output i=4.
     output i=5.
     output i=6.
     output i=7.
     output i=8.
     output i=9.
    
  5. 该文件定义了默认目标hello_main用于编译程序,clean目标用于删除编译生成的文件。特别地,其中 hello_main目标名与 gcc 编译生成的文件名”gcc -o hello_main”设置成一致了,也就是说,此处的目标 hello_main 在 Makefile看来,已经是一个目标文件 hello_main。这样的好处是 make 每次执行的时候,会检查 hello_main 文件和依赖文件 hello_main.c、 hello_func.c 的修改日期,如果依赖文件的修改日期比 hello_main 文件的日期新,那么 make 会执行目标其下的 Shell 命令更新hello_main 文件,否则不会执行。演示如下:

     mdxz_18@mdxz18:~/lzp/workdir/base_code/linux_app/makefile_step/step_1$ make     make: 'hello_main' is up to date.
     mdxz_18@mdxz18:~/lzp/workdir/base_code/linux_app/makefile_step/step_1$ touch hello_func.c
     mdxz_18@mdxz18:~/lzp/workdir/base_code/linux_app/makefile_step/step_1$ make
     gcc -o hello_main hello_main.c hello_func.c -I .
     mdxz_18@mdxz18:~/lzp/workdir/base_code/linux_app/makefile_step/step_1$
    

伪目标

前面我们在 Makefile 中编写的目标,在 make 看来其实都是目标文件,例如 make 在执行的时候由于在目录找不到 targeta 文件,所以每次 make targeta 的时候,它都会去执行 targeta 的命令,期待执行后能得到名为 targeta的同名文件。如果目录下真的有targeta、 targetb、 targetc 的文件,即假如目标文件和依赖文件都存在且是最新的,那么 make targeta 就不会被正常执行了,这会引起误会。为了避免这种情况, Makefile 使用“.PHONY”前缀来区分目标代号和目标文件,并且这种目标代号被称为“伪目标”, phony 单词翻译过来本身就是假的意思。也就是说,只要我们不期待生成目标文件,就应该把它定义成伪目标,前面的演示代码修改如下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值