# makefile 開始
# 編譯相關的選項
CC = g++
CPPFLAG =
# 所有的cpp源文件或者手動添加文件
SOURCES = $(wildcard *.cpp)
#SOURCES = main.cpp \
# test_func.cpp \
# test_class.cpp
# 與源文件對應的目標文件和依賴文件
OBJECTS = $(SOURCES:.cpp=.o)
DEPENDS = $(SOURCES:.cpp=.d)
# 第一個編譯模板
all: test.exe
# 添加依賴文件
sinclude $(DEPENDS)
test.exe: $(OBJECTS)
$(CC) $(OBJECTS) -o test.exe
$(OBJECTS): %.o: %.cpp
$(CC) -c $(CPPFLAG) $< -o $@
# 生成依賴文件,由于依賴文件也依賴源文件,因此需要增加xxx.d,如:
# main.o: main.cpp test_func.hpp test_class.hpp
# main.d main.o: main.cpp test_func.hpp test_class.hpp
# 一般的例子會使用sed實現這個功能,在這里我編寫了print.exe實現該功能。
%.d: %.cpp print.exe
print.exe $@ > $@
$(CC) -MM $< >> $@
# 輔助生成依賴文件的程序
print.exe: print.c
$(CC) print.c -o print.exe
#清除所有文件
clean:
del test.exe print.exe $(OBJECTS) $(DEPENDS)
#makefile 結束
// print.c 開始
#include <cstdio>
int main(int argc, const char* argv[]) {
if (argc > 1) {
printf("%s ", argv[1]);
}
return 0;
}
// print.c 結束
// main.cpp 開始
#include "test_func.hpp"
#include "test_class.hpp"
int main() {
TestClass::Print();
Print();
}
// main.cpp 結束
// test_class.hpp 開始
#ifndef TEST_CLASS_HPP
#define TEST_CLASS_HPP
class TestClass {
public:
static void Print();
};
#endif // TEST_CLASS_HPP
// test_class.hpp 結束
// test_class.cpp 開始
#include <cstdio>
#include "test_class.hpp"
void TestClass::Print() {
printf("TestClass\n");
}
// test_class.cpp 結束
// test_func.hpp 開始
#ifndef TEST_FUNC_HPP
#define TEST_FUNC_HPP
void Print();
#endif // TEST_FUNC_HPP
// test_func.hpp 結束
// test_func.cpp 開始
#include <cstdio>
#include "test_func.hpp"
void Print() {
printf("TestFunc\n");
}
// test_func.cpp 結束