1. make 命令
1. make 命令的功能
make 命令可以用来编译程序,也可以通过过个输入文件来生成输出文件
2. make 命令常用的选项
−f<filename> 指定 file 文件为描述文件,如果 file 参数为”-“符,那么描述文件指向标准输入。如果没有” −f ”参数,则系统将默认当前目录下名为 makefile 或者名为 Makefile 的文件为描述文件。在 Linux 中, GNUmake 工具在当前工作目录中按照 GNUmakefile 、 makefile 、 Makefile 的顺序搜索 makefile 文件。
−i 忽略命令执行返回的出错信息。
- −s 沉默模式,在执行之前不输出相应的命令行信息。
- −r 禁止使用[ build−in 规则]。
- −n 非执行模式,输出所有执行命令,但并不执行。
- −t 更新目标文件。
- −q make 操作将根据目标文件是否已经更新返回”0”或非”0”的状态信息。
- −p 输出所有宏定义和目标文件描述。
- −d Debug模式,输出有关文件和检测时间的详细信息。
- -c dir 在读取 makefile 之前改变到指定的目录dir。
- -I dir 当包含其他 makefile文件时,利用该选项指定搜索目录。
- −h help文挡,显示所有的make选项。
- −w 在处理 makefile 之前和之后,都显示工作目录。
2. Makefile 文件
1. 依赖关系
1.样例
main.c:
#include "a.h"
...
2.c
#include "a.h"
#include "b.h"
...
3.c
#include "b.h"
#include "c.h"
...
目标文件是3.c编译后形成的可执行文件myapp
依赖关系:
myapp : main.o 2.o 3.o
#myapp依赖main.o 2.o 3.o文件
main.o : main.c a.h
#main.o依赖main.c a.h文件
2.o : 2.c a.h b.h
#2.o依赖2.c a.h b.h文件
3.o : 3.c 2.o b.h c.h
#3.o依赖3.c 2.o b.h c.h文件
拓展:如果一次想创建多个目标文件,可以用伪目标文件
all
用法是
all : myapp1 myapp2 ...
2. 规则
1. 功能
定义了目标的创建方式
2. 样例
myapp : main.o 2.o 3.o
gcc -o myapp main.o 2.o 3.o
main.o : main.c a.h
gcc -c main.c
2.o : 2.c a.h b.h
gcc -c 2.c
3.o : 3.c 2.o b.h c.h
gcc -c 3.c
3. 语法
目标文件:依赖的文件
<Tab>
规则
注:
Makefile
文件中的空格与
<Tab>
是有区别的
注释:以“#”开头
宏:通过
MACRONAME=value
在
Makefile
文件中定义宏,使用
$(MACRONAME)
或者
${MACRONAME}
来引用宏。
3. 实例
1. tmp.h
#ifndef TMP_H_
#define TMP_H_
class calc{
private:
int n;
public:
calc();
int get();
void set(int _x);
int fac();
};
#endif
2. tmp.cpp
#include "tmp.h"
#include <iostream>
using namespace std;
calc::calc(){
}
int calc::get(){
return n;
}
void calc::set(int _x){
n=_x;
}
int calc::fac(){
int ans = 1;
for(int i=2;i<=n;i++){
ans = ans*i;
}
return ans;
}
3. test.cpp
#include "tmp.h"
#include <iostream>
using namespace std;
int main(){
calc A;
A.set(5);
cout<<A.get()<<endl;
cout<<A.fac()<<endl;
return 0;
}
4. Makefile
all: main
#compiler
COM = g++
main: test.o tmp.o
$(COM) -o main test.o tmp.o
test.o: test.cpp tmp.o
$(COM) -c test.cpp
tmp.o: tmp.cpp tmp.h
$(COM) -c tmp.cpp
clean:
rm *.o
5. 结果
g++ -c tmp.cpp
g++ -c test.cpp tmp.o
g++: warning: tmp.o: linker input file unused because linking not done
g++ -o main test.o tmp.o
5
120