处理多个子目录中的Makefile依赖项并输出到单独的子目录

时间:2017-08-24 09:04:35

标签: c++ makefile

我一直在阅读有关使用子目录的Makefile的帖子,但似乎无法正确地将所有部分放在一起。我有以下文件结构:

program
    |
    - src
    |
    - include
    | 
    - build
    |
    - bin
    |
    - Makefile

我的所有源代码(.cpp)都在program / src /中,我的所有头文件(.hpp)都在program / include中,我想把所有的目标文件和依赖文件放到program / build中,我想要我的二进制文件放入program / bin。以下是我目前在Makefile中的内容:

CXX = g++
BIN_DIR = bin
TARGET = $(BIN_DIR)/coreint
BUILD_DIR = build
SRC_DIR = src
INC_DIR = include
CXXFLAGS = -Wall -g

# Get all source files
SRCS := $(shell find $(SRC_DIR) -name *.cpp)
# Get all object files by replacing src directory with build directory    and replace extension
OBJS := $(subst $(SRC_DIR), $(BUILD_DIR), $(SRCS:%.cpp=%.o))
# Get all depend files by replacing extensions
DEPS := $(OBJS:.o=.d)
# Get all includes by searching include directory
INCS := $(shell find $(INC_DIR) -name *.hpp)
# Append -I to the front of each include
INCS := $(foreach d, $(INCS), -I$d)
# Using VPATH to find files in src/ include/ and build/
VPATH = $(SRC_DIR):$(INC_DIR):$(BUILD_DIR)

all: $(TARGET)

$(TARGET): $(OBJS)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) $(OBJS) -o $(TARGET)

# Build object files and put in build directory
$(BUILD_DIR)%.o: %.cpp
    $(CXX) $(CXXFLAGS) -c $< -o $@

# Place dependency files in build directory
# automatically generate dependency rules
$(BUILD_DIR)%.d: %.cpp
    $(CXX) $(CXXFLAGS) -MF"$@" -MG -MM -MD -MP -MT"$@" -MT"$(OBJS)" "$<"
# -MF  write the generated dependency rule to a file
# -MG  assume missing headers will be generated and don't stop with an error
# -MM  generate dependency rule for prerequisite, skipping system headers
# -MP  add phony target for each header to prevent errors when header is missing
# -MT  add a target to the generated dependency

.PHONY: clean all

clean:
    rm -f $(OBJS) $(DEPS) $(TARGET)

-include $(DEPS)

当我运行make时,我收到以下错误:

make: *** No rule to make target `build/assign.o', needed by `bin/coreint'.  Stop.

其中assign.o是构建目录中的第一个文件。提前谢谢。

1 个答案:

答案 0 :(得分:1)

我只是错过了一个&#39; /&#39;在我的BUILD_DIR之后:

# Build object files and put in build directory
$(BUILD_DIR)/%.o: %.cpp
    $(CXX) $(CXXFLAGS) -c $< -o $@