1)准备a.cpp 和main.cpp 两个文件进行测试。
a.cpp文件
#include <iostream> using namespace std; void myprint(){ cout<<"This is a test file about makefile!"<<endl; }
main.cpp文件
#include <iostream> using namespace std; void myprint(); int main(){ myprint(); cout<<"this is a main file !\n"; }
2)编写makefile 文件
#变量定义 CPP = g++ #使用g++ CC = gcc #使用gcc OBJ = a.o main.o #编译后输出的目标文件 LINKOBJ = a.o main.o #编译链接时需要的目标文件 BIN = main #生成的可执行文件名称 RM = rm -rf #删除文件的shell命令 .PHONY: all clean cleanobj #伪文件说明 all: $(BIN) $(BIN): $(OBJ) #生成可执行文件main $(CPP) $(LINKOBJ) -o $(BIN) clean: #清除.o文件和可执行文件 ${RM} $(OBJ) $(BIN) cleanobj: #只清除.o的中间文件 ${RM} *.o
3)先查看当前目录下的文件
[root@localhost tmp2]# ls a.cpp main.cpp makefile
4)执行make
[root@localhost tmp2]# make g++ -c -o a.o a.cpp g++ -c -o main.o main.cpp g++ a.o main.o -o main -lsnmp++ -ldes -lpthread
5)再次查看当前目录下的文件,多了两个.o后缀的目标文件和一个可执行文件
[root@localhost tmp2]# ls a.cpp a.o main main.cpp main.o makefile
6)执行可执行文件
[root@localhost tmp2]# ./main This is a test file about makefile! this is a main file !
7)删除中间生成的目标文件,根据makefile文件的定义,删除了.o后缀的文件
[root@localhost tmp2]# make cleanobj rm -rf *.o [root@localhost tmp2]# ls a.cpp main main.cpp makefile
8)也可以使用make clean命令删除中间产生的目标文件和可执行文件
[root@localhost tmp2]# make clean rm -rf a.o main.o main