1. Makefile 的编译过程
# 编译并生成可执行文件
g++ main.cpp factorial.cpp printhello.cpp -o main
./main
# 编译生成obj对象,只编译不链接
g++ main.cpp -c
g++ factorial.cpp -c
g++ printhello.cpp -c
# 链接编译好的obj对象
g++ *.o -o main
2. Makefile 第一版本
## VERSION 1
hello: main. cpp printhello. cpp. factorial.cpp
g++ -0 hello main.cpp printhello.cpp•factorial.cpp
3. Makefile 第二版本
## VERSION 2
CXX = g++
TARGET = hello
OBJ = main.o printhello.o factorial.o
$(TARGET): $(OBJ)
$(CXX) -o $(TARGET) $(OBJ)
main.o: main.cpp
$(CXX) -c main.cpp
printhello.o: printhello.cpp
$(CXX) -c printhello.cpp
factorial.o: factorial.cpp
$(CXX) -c factorial.cpp
4. Makefile 第三版本
## VERSION 3
CXX = g++
TARGET = hello
OBJ = main.o printhello.o factorial.o
# 打开所有警告
CXXFLAGS = -c -Wall
$(TARGET): $(OBJ)
$(CXX) -o $@ $^
%.o: %.cpp
$(CXX) $(CXXFLAGS) $< -o $@
.PHONY: clean
clean:
rm -f *.o $(TARGET)
5. Makefile 第四版本
## VERSION 4
CXX = g++
TARGET = hello
SRC = $(wildcard *.cpp)
OBJ = $(patsubst %.cpp, %.o, $(SRC))
CXXFLAGS = -c -Wall
$(TARGET): $(OBJ)
$(CXX) -o $@ $^
%.o: %.cpp
$(CXX) $(CXXFLAGS) $< -o $@
.PHONY: clean
clean:
rm -f *.o $(TARGET)
6. CMake 不用再写复杂的Makefile
由于Makefile是强依赖于当前工程结构,操作系统,编译器的,因此直接使用Makefile构建出来的编译流程,在不同平台下执行的结果是不尽相同的,因为编译器不同,操作系统路径不同等等。如何打通不同平台,不同环境下的工程编译?
上面的例子,用CMake来实现,新建CMakeLists.txt
cmake_minimum_required (VERSION 3.10)
project (hello)
add _executable(hello main.cpp factorial.cpp printhello.cpp)