-
在程序文件夹里新建一个文件
-
named “makefile” or “Makefile”
-
write down these codes:
program_name: 你想创建的object files name tab+command(link object files to create an executable file named with program name) 1st_object_file_name: name.cpp tab+command(g++ -c name.cpp) 2nd_object_file_name: name2.cpp tab+command(g++ -c name2.cpp) ... clean: tab+rm *.o program_name ...
-
实例:
对于一个有main.cpp, IntList.cpp, IntList.h三个文件的名为P5的简单程序:P5: main.o IntList.o g++ main.o IntList.o -o P5 main.o: main.cpp g++ -c main.cpp IntList.o: IntList.cpp g++ -c IntList.cpp clean: rm *.o P5
使用makefile:
$ make
run this makefile, return
g++ -c main.cpp
g++ -c IntList.cpp
g++ main.o IntList.o
$ ./program_name
运行程序$ touch main.cpp
告诉make你修改过main.cpp$ make
生成新的executable file$ make clean
清除make生成的所有文件,包括object files and executable files
解释:
-
g++ -Wall -c main.cpp
g++ -Wall -c linkedlist.cpp
里的-c
:
告诉编译器(我的是g++)只编译去创建一个名为main.o
的object file,不需要进行link files -
g++ main.o linkedlist.o -o myprog.exe
里的-o
:
让编译器link这些object files,创建一个名为myprog.exe
的可执行文件 -
clean :
清除make生成的所有文件,包括object files and executable files
make会执行这个命令:rm *.o myprog.exe
-
默认 make 会假设你的 makefile 名称就是 makefile 或者Makefile;也可以用
-f
来运行其他名称的 makefile,如make -f MyMakefile
会让 make 运行一个名为 MyMakefile 的文件.