[英]Single Makefile for sources in multiple sub directories
在我的 C++ 項目中,源代碼組織在 src 目錄中。 src 目錄內是子目錄,它們都包含頭文件和源文件,例如
project
├── Makefile
│
├── MyBinary
│
├── src
│ │
│ ├── main.cpp
│ │
│ ├── Application
│ │ │
│ │ ├── Application.h
│ │ └── Application.cpp
│ │
│ │
│ └── Tasks
│ ├── BackgroundWorker.h
│ └── BackgroundWorker.cpp
│
└── obj
├── Application.o
└── BackgroungWorker.o
我正在嘗試創建一個 Makefile,以便在obj目錄中創建所有對象文件,並且在與 Makefile 相同級別的src目錄上方創建可執行文件MyBinary 。
它不必太復雜或自動化。 我不介意在 Makefile 中手動指定每個 .cpp 和 .h 文件。
但我是 Makefiles 的新手,不幸的是我正在努力嘗試:
CXX=c++
CXXFLAGS=-Wall -Os -g0
# Name of the output binary
APPNAME=MyBinary
# Source root directory
SRC_ROOT=src
# Object file directory
OBJ_DIR=obj
DEPS=$(SRC_ROOT)/Application/Application.h \
$(SRC_ROOT)/Tasks/BackgroundWorker.h
_OBJ=$(SRC_ROOT)/Application/Application.o \
$(SRC_ROOT)/Tasks/BackgroundWorker.o\
$(SRC_ROOT)/main.o
OBJ=$(patsubst %,$(OBJ_DIR)/%,$(_OBJ))
# This rule says that the .o file depends upon the .c version of the
# file and the .h files included in the DEPS macro.
$(OBJ_DIR)/%.o: %.cpp $(DEPS)
$(CXX) -c -o $@ $< $(CXXFLAGS)
# Build the application.
# NOTE: The $@ represents the left side of the colon, here $(APPNAME)
# The $^ represents the right side of the colon, here $(OBJ)
$(APPNAME): $(OBJ)
$(CXX) -o $@ $^ $(CXXFLAGS)
clean:
rm -f $(OBJ_DIR)/*.o $(APPNAME)
調用make時的錯誤是:致命錯誤:無法創建obj/src/Application.o:找不到文件或目錄。
任何人都可以幫忙嗎?
OBJ=$(patsubst %,$(OBJ_DIR)/%,$(_OBJ))
在_OBJ
的單詞前加上obj/
。 你想用obj
替換src
一些你可以做的事情
OBJ=$(patsubst $(SRC_ROOT)/%,$(OBJ_DIR)/%,$(_OBJ))
請注意,您獲得的目錄結構需要子目錄Application
和Tasks
到obj
您必須在調用make
或更新 Makefile 以創建它們之前手動創建它們。
當預先創建目錄結構時,這里的行為與我期望的一樣。
APPNAME=MyBinary
SRC_ROOT=src
OBJ_DIR=obj
DEPS=$(SRC_ROOT)/Application/Application.h \
$(SRC_ROOT)/Tasks/BackgroundWorker.h
_OBJ=$(SRC_ROOT)/Application/Application.o \
$(SRC_ROOT)/Tasks/BackgroundWorker.o\
$(SRC_ROOT)/main.o
OBJ=$(patsubst $(SRC_ROOT)/%,$(OBJ_DIR)/%,$(_OBJ))
$(OBJ_DIR)/%.o: $(SRC_ROOT)/%.cpp $(DEPS)
echo Making $@ from $<
touch $@
$(APPNAME): $(OBJ)
echo Making $@ from $^
touch $@
請注意,在實踐中,您必須更好地處理依賴項,並且可能讓它們由編譯器生成(請參閱-MM
和 g++ 的類似選項),在這里您在更改頭文件時重新編譯所有內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.