前言
Makfile的内容很多,我也查阅了一些博客,然后自己写了一个小demo,大家要是想了解更深入一些,推荐大家看这篇文章。
跟我一起写Makefile
一、编译过程
首先介绍一下,编译过程和基本的.cpp文件编译以及链接指令
预处理——编译——汇编——链接
文件test.cpp代码如下:
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
cout<<"this is a g++ test"<<endl;
}
-
g++ test.cpp
生成默认名字的可执行文件:a.out;可以通过./a.out运行,打印出:this is a g++ test
-
g++ test.cpp
生成名字为test的可执行文件
-
g++ -c test.cpp
只编译不链接 -c(生成.o的二进制文件),再执行下面一条命令,生成可执行文件
g++ test.o -o test -
g++ -E test.cpp > test.e
预编译 -E(把所有的有关文件,宏等拼接至一个文件内) -
g++ -S test.cpp
只编译不汇编
-
g++ -g test.cpp -o test
带调试的可执行文件
当项目比较复杂时,需要用到Makefile!!!
二、初识Makefile
Makefile的组成有三个部分:目标、依赖和规则。
目标:运行make之后生成什么;
依赖:告诉make如何做实现目标;
规则:目标和依赖都是通过规则来表达的。
举个最简单的例子,帮助大家理解一下。
多文件编译,三个文件夹Dog, person,test
Dog文件夹中包括:dog.cpp , dog.hh
dog.hh代码如下:
class Dog
{
public:
Dog();
};
dog.cpp代码如下:
#include <iostream>
using namespace std;
#include "Dog.hh"
Dog::Dog()
{
cout<<"Dog constructor"<<endl;
}
person文件夹中包括:Person.cpp , Person.hh
Person.hh代码如下:
class Person
{
public:
Person();
};
Person.cpp代码如下:
#include <iostream>
using namespace std;
#include "Person.hh"
Person::Person()
{
cout<<"Personconstructor"<<endl;
}
test文件夹中包括:**main.cpp **
#include <stdio.h>
#include <iostream>
using namespace std;
#include "Person.hh"
#include "Dog.hh"
int main()
{
cout<<"Enter main"<<endl;
Person p;
Dog dog;
return 0;
}
看到这里,大家会觉得这代码非常简单,其实主要是帮助大家理解,关键在下面这个。
Path:文件路径;
-I:指定文件搜索路径;
$:变量;
clean:执行make clean命令时,会清除已经生成的.o文件;
@:执行后面语句,但不打印。
总结
Makefile很强大,这只是冰山一角,还有很多需要学习的,加油!