【C++】常用 Makefile 语法

# Rules of makefile:
# target ... : prerequisites ...
# (\t)command
#     ...


# if there is no foo.make or any files whose name end up with .mk, the make will exit with error
include foo.make *.mk
# It won't exit with error code if perhapsError.mk has error, when we use '-' before include
-include perhapsError.mk

#main: main.o
# g++ -o main main.o

#main.o : main.cpp json.hpp
# g++ -c main.cpp

# a kind of var, like macro definition, CXX will be just replace with g++ when making.
# Must assign var a initial value
CXX     = g++
CXXFLAGS = -Wall
# another kind of a var, we can add values to it with "+="
BUILD_DIR := ./build
# We use var by using $(var)
OBJ_DIR   := $(BUILD_DIR)/obj
TARGET  := main2
SOURCE  := main.cpp
SOURCE  += json.hpp main2.cpp # If we don't write json.hpp here, it still make correct. why?
#OBJ      := main.o main2.o
OBJ     := $(SOURCE:%.cpp=$(OBJ_DIR)/%.o)

# $@ means the object, here is $(BUILD)/$(TARGET), also known as ./build/main2
# $^ means all the prerequistites
# $(@D) means the directory part of the object. which is ./build of ./build/main2
# $(@F) means the file part of the object.
# So, the following equals:
#   @mkdir -p ./build
# main2: main.o
#   g++ -o main2 main.o main2.o
$(BUILD_DIR)/$(TARGET): $(OBJ)
  @mkdir -p $(@D)
  $(CXX) $(CXXFLAGS) -o $@ $^
# Pay Attention!!! windows powershell can't use "mkdir -p". we should use git bash on windows


# $< means the first prerequisties
# % means every 
# So, the following equals:
#   @mkdir -p ./build/obj
# ./build/obj/main.o : main.cpp
#   g++ -Wall -o ./build/obj/main.o -c main.cpp
# ./build/obj/main2.o : main2.cpp
#   g++ -Wall -o ./build/obj/main.o -c main.cpp
$(OBJ_DIR)/%.o: %.cpp
  @mkdir -p $(@D) 
  $(CXX) $(CXXFLAGS) -o $@ -c $<

# .PHONY: aaa bbb ccc ddd
# .PHONY defined a group of fake target. Which will always be done when called.
.PHONY: clean

# It is a certainly good idea to put clean at the end of the Makefile.
clean:
  -@rm -rvf $(BUILD_DIR)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深海Enoch

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值