我正在嘗試創建一個Makefile,它將我的.o
文件放在與我的源文件不同的目錄中。我試圖使用模式規則,因此我不必爲每個源文件創建相同的規則。GNU Make模式在不同的目錄下創建輸出src
我的項目結構看起來像:
project/
+ Makefile
+ src/
+ main.cpp
+ video.cpp
+ Debug/
+ src/ [contents built via Makefile:]
+ main.o
+ video.o
我的Makefile看起來像:
OBJDIR_DEBUG = Debug
OBJ_DEBUG = $(OBJDIR_DEBUG)/src/main.o $(OBJDIR_DEBUG)/src/video.o
all: $(OBJ_DEBUG)
$(OBJ_DEBUG): %.o: %.cpp
$(CXX) $(CFLAGS_DEBUG) $(INC_DEBUG) -c $< -o [email protected]
這是不行的,因爲它看起來對我的源文件在Debug/src/*.cpp
。
我已經試過如下:
# Broken: make: *** No rule to make target `Debug/src/main.cpp', needed by `Debug/src/main.o'. Stop.
# As a test, works if I change "%.cpp" to "Debug/src/main.cpp", though it obv. builds the wrong thing
# Strip OBJDIR_DEBUG from the start of source files
$(OBJ_DEBUG): %.o: $(patsubst $(OBJDIR_DEBUG)/%,%,%.cpp)
$(CXX) $(CFLAGS_DEBUG) $(INC_DEBUG) -c $< -o [email protected]
# Broken:
# Makefile:70: target `src/main.o' doesn't match the target pattern
# Makefile:70: target `src/video.o' doesn't match the target pattern
# Add OBJDIR_DEBUG in target rule
OBJ = src/main.o src/video.o
$(OBJ): $(OBJDIR_DEBUG)/%.o: %.cpp
$(CXX) $(CFLAGS_DEBUG) $(INC_DEBUG) -c $< -o [email protected]
這是最好的辦法。 – Beta
如果在OBJDIR_DEBUG中有子目錄,會發生什麼?我的猜測是,編譯將失敗,因爲輸出目錄不存在。 – aardvarkk