makefile自动推导详解

发布时间:2023-07-22 12:04:20 作者:yexindonglai@163.com 阅读(462)

1、什么是自动推导

自动推导也叫隐含规则,所谓隐含规则指的是,我们在Makefile文件中不使用 gcc/g++ 命令来生成目标文件,但是执行make命令以后,Makefile 会自动帮我们执行。这就是Makefile 的隐含规则,也可以称为自动推导的过程。

2、实战

首先准备三个文件 student.h、student.cpp 和主程序 main.cpp

student.h

  1. #ifndef NAKEFILE_PROJECT_STUDEN_H
  2. #define NAKEFILE_PROJECT_STUDEN_H
  3. int getAge();
  4. #endif //NAKEFILE_PROJECT_STUDEN_H

student.cpp

  1. #include "student.h"
  2. int getAge(){
  3. return 1;
  4. }

main.cpp

  1. #include <iostream>
  2. #include "student.h"
  3. int main() {
  4. std::cout << "Hello, World!" << std::endl;
  5. std::cout << "getAge:"<<getAge() << std::endl;
  6. return 0;
  7. }
编写makefile(常规写法)

注意:下面的缩进,必须用tab键,不能用4个空格键代替,否则会报错

而且,makefile的前后的顺序没有要求,在编译的时候会自动排序;

  1. main : main.o student.o
  2. g++ -o main main.o student.o
  3. main.o:main.cpp
  4. g++ -c main.cpp
  5. studen.o: student.cpp student.h
  6. g++ -c student.cpp student.h
  7. clean :
  8. rm main main.o student.o
编写makefile(自动推导写法)

自动推导的写法少了很多东西,

  1. main : main.o student.o
  2. g++ -o main main.o student.o
  3. main.o:
  4. student.o: student.h
  5. clean :
  6. rm main main.o student.o

执行make命令后我们会发现,我们在makefile里面没写main.cpp,它根据main.o自动推导出了main.cpp的文件名称, 同理,我们在makefile文件中也没写student.cpp,它根据student.o自动推导出了student.cpp文件;这就是自动推导的强大之处

比较

接下来我们将常规写法和自动推导的写法做一个比较;由此可以发现,当你声明了 xxx.o之后,它会自动去当前目录下寻找 xxx.c或者xxx.cpp文件;找到之后会进行编译操作;

使用变量

以上的makefile还可以用变量进行优化,优化后如下,执行结果和上面是一样的;

  1. main=main.o
  2. student=student.o
  3. man_student=main.o student.o
  4. main : $(man_student)
  5. g++ -o main $(man_student)
  6. $(main):
  7. $(student): student.h
  8. clean :
  9. rm main $(man_student)

关键字c++