GNU Make模式在src以外的目录中构建输出

mrb*_*mrb 28 makefile gnu-make

我正在尝试创建一个Makefile,它将我的.o文件放在与源文件不同的目录中.我正在尝试使用模式规则,因此我不必为每个源和目标文件创建相同的规则.

我的项目结构看起来像:

project/
 + Makefile
 + src/
   + main.cpp
   + video.cpp
 + Debug/
   + src/       [contents built via Makefile:]
     + main.o
     + video.o
Run Code Online (Sandbox Code Playgroud)

我的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 $@
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为它在我的源文件中查找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 $@
Run Code Online (Sandbox Code Playgroud)

# 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 $@
Run Code Online (Sandbox Code Playgroud)

mrb*_*mrb 26

在重新阅读静态模式规则文档之后,我得出了以下模式规则,这似乎有效.

$(OBJ_DEBUG): $(OBJDIR_DEBUG)/%.o: %.cpp
    $(CXX) $(CFLAGS_DEBUG) $(INC_DEBUG) -c $< -o $@
Run Code Online (Sandbox Code Playgroud)

我不确定这是最好的方法,我愿意接受建议.

  • 这是最好的方法. (3认同)