【发布时间】:2019-02-20 15:39:00
【问题描述】:
在我的 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 目录中创建所有对象文件,并在 src上方创建可执行文件 MyBinary > 与 Makefile 处于同一级别的目录。
它不必太复杂或自动化。我不介意在 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时报错:Fatal error: can't create obj/src/Application.o: File or directory not found.
谁能帮忙?
【问题讨论】:
-
一个可行的解决方案:stackoverflow.com/a/7321954/412080
标签: c++ makefile subdirectory