如何生成一个简单的 makefile 文件

  1. 在程序文件夹里新建一个文件

  2. named “makefile” or “Makefile”

  3. 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
    ...
    
  4. 实例:
    对于一个有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:

  1. $ make run this makefile, return
g++ -c main.cpp 
g++ -c IntList.cpp
g++ main.o IntList.o
  1. $ ./program_name 运行程序
  2. $ touch main.cpp 告诉make你修改过main.cpp
  3. $ make 生成新的executable file
  4. $ make clean 清除make生成的所有文件,包括object files and executable files

解释:

  1. g++ -Wall -c main.cpp
    g++ -Wall -c linkedlist.cpp里的-c:
    告诉编译器(我的是g++)只编译去创建一个名为main.o的object file,不需要进行link files

  2. g++ main.o linkedlist.o -o myprog.exe里的-o:
    让编译器link这些object files,创建一个名为myprog.exe的可执行文件

  3. clean :
    清除make生成的所有文件,包括object files and executable files
    make会执行这个命令: rm *.o myprog.exe

  4. 默认 make 会假设你的 makefile 名称就是 makefile 或者Makefile;也可以用 -f 来运行其他名称的 makefile,如 make -f MyMakefile 会让 make 运行一个名为 MyMakefile 的文件.

猜你喜欢

转载自blog.csdn.net/lishuo0204/article/details/114110171