• {{article.mytitle}}
  • Makefile 例子

    本文档的文件名同二级标题

    全部文件打包下载makefile.zip

    1. gcc例子

    准备文件
    新建,项目文件夹hello,及文件main.cpp,factorial.cpp,printhello.cpp,functions.h。

    hello目录如下

    hello/
    ├──main.cpp
    ├──factorial.cpp
    ├──printhello.cpp
    └──functions.h
    编译命令

    g++ main.cpp factorial.cpp printhello.cpp -o main
    ./main
    

    1.1. main.cpp

    #define _FUNCTIONS_H_
    
    #include <iostream>
    #include "functions.h"
    using namespace std;
    
    int main()
    {
    	printhello();
    	
    	cout << "This is main:" << endl;
    	cout << "The factorial of 5 is:" << factorial(5) << endl;
    	return 0;
    }
    

    1.2. printhello.cpp

    #include <iostream>
    #include "functions.h"
    using namespace std;
    
    void printhello()
    {
    	cout << "Hello World!" << endl;
    }
    

    1.3. factorial.cpp

    #include "functions.h"
    
    int factorial(int n)
    {
    	if (n==1)
    		return 1;
    	else
    		return n * factorial(n-1);
    }
    

    1.4. functions.h

    #ifdef _FUNCTIONS_H_
    #define _FUNCTIONS_H_
    void printhello();
    int factorial(int n);
    #endif
    

    2. make例子

    2.1. makefile

    cCOMP = g++
    cFLAGS=  -Wno-deprecated -g -o
    
    DIR_INC= -I/usr/include
    
    INCLUDE = $(DIR_INC)
    
    SRC = *.cpp *.h
    OBJS	= main
    
    $(OBJS):$(SRC) change
    		$(cCOMP) $(cFLAGS) $(OBJS) $(SRC) $(INCLUDE)
    
    
    change:
    		touch main.cpp
    .PHONY : clean
    clean:
    		rm -f $(OBJS)
    
    

    如果c++的文件名尾缀为 .c, 则需要把上面代码中的 SRC = *.cpp *.h 修改为 SRC = *.c *.h

    编译命令

    make
    ./main