Makefile 的四个例子

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值