本文档的文件名同二级标题
全部文件打包下载makefile.zip
准备文件
新建,项目文件夹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
#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; }
#include <iostream> #include "functions.h" using namespace std; void printhello() { cout << "Hello World!" << endl; }
#include "functions.h" int factorial(int n) { if (n==1) return 1; else return n * factorial(n-1); }
#ifdef _FUNCTIONS_H_ #define _FUNCTIONS_H_ void printhello(); int factorial(int n); #endif
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