makefile:子目录的模式规则

Yve*_*ves 0 c++ makefile pattern-matching

这是我的项目:

project
  |--- main.cpp
  |--- makefile
  |--- test
        |--- Test.cpp
        |--- Test.h
Run Code Online (Sandbox Code Playgroud)

这是makefile:

g++1x:=g++ -std=c++14 -stdlib=libc++ -MMD -MP
cflags:= -Wall -lncurses

PATHS:=./ ./test/
TARGET:=matrix.out
SRC:=$(foreach PATH,$(PATHS),$(wildcard $(PATH)/*.cpp))
OBJDIR:=.obj
OBJ:=$(addprefix $(OBJDIR)/,$(notdir $(SRC:.cpp=.o)))


.PHONY: install
install: $(OBJDIR) $(TARGET)

$(OBJDIR):
    mkdir -p $(OBJDIR)

$(TARGET): $(OBJ)
    $(g++1x) $(cflags) -o $@ $^ -g


$(OBJDIR)/%.o: %.cpp
    $(g++1x) -c -o $@ $< -g

$(OBJDIR)/%.o: ./test/%.cpp
    $(g++1x) -c -o $@ $< -g

-include $(addprefix $(OBJDIR)/,$(notdir $(SRC:.cpp=.d)))

.PHONY: clean
clean:
    rm -f $(TARGET)
    rm -rf $(OBJDIR)
Run Code Online (Sandbox Code Playgroud)

它运作良好,但我有两个问题:
1)是否可以避免foreach,PATHS以便我可以使用相同makefile的所有cpp项目?
2)如你所见,生成main.oTest.o编写两个块:
$(OBJDIR)/%.o: ./test/%.cpp$(OBJDIR)/%.o: %.cpp.
是否可以只写一次?
我试过如下,但它不起作用:

$(OBJDIR)/%.o: $(foreach PATH,$(PATHS),$(wildcard $(PATH)/%.cpp))
        $(g++1x) -c -o $@ $< -g
Run Code Online (Sandbox Code Playgroud)

我甚至尝试过这样但它仍然不起作用:

$(OBJDIR)/%.o: %.cpp ./test/%.cpp
    $(g++1x) -c -o $@ $< -g
Run Code Online (Sandbox Code Playgroud)

jml*_*jml 7

您应该将源树保留在对象树中.这样,创建全局规则和保持依赖关系将更容易.

# Use the shell find command to get the source tree
SOURCES := $(shell find * -type f -name "*.c")

OBJDIR  := .objects

# Keep the source tree into the objects tree
OBJECTS := $(addprefix $(OBJDIR)/,$(SOURCES:.c=.o))

all: mytarget

mytarget: $(OBJECTS)
    $(CC) $^ -o $@

# As we keep the source tree we have to create the
# needed directories for every object
$(OBJECTS): $(OBJDIR)/%.o: %.c
    mkdir -p $(@D)
    $(CC) -MMD -MP -c $< -o $@

-include $(OBJECTS:.o=.d)
Run Code Online (Sandbox Code Playgroud)
$ make
mkdir -p .objects
cc -MMD -MP -c main.c -o .objects/main.o
mkdir -p .objects/test
cc -MMD -MP -c test/test.c -o .objects/test/test.o
cc .objects/main.o .objects/test/test.o -o mytarget

$ tree -a
.
??? main.c
??? Makefile
??? mytarget
??? .objects
?   ??? main.d
?   ??? main.o
?   ??? test
?       ??? test.d
?       ??? test.o
??? test
    ??? test.c
    ??? test.h

3 directories, 9 files
Run Code Online (Sandbox Code Playgroud)

编辑:您可以mkdir通过添加对象目录作为仅限订单的先决条件,将数量减少到最少:

# Do not create the directory
$(OBJECTS): $(OBJDIR)/%.o: %.c
    $(CC) -MMD -MP -c $< -o $@

# Every target finishing with "/" is a directory
$(OBJDIR)%/:
    mkdir -p $@

# Add the "directory/" as an order only prerequisite
$(foreach OBJECT,$(OBJECTS),$(eval $(OBJECT): | $(dir $(OBJECT))))
Run Code Online (Sandbox Code Playgroud)