我的 makefile 如何包含子目录?

How can my makefile include subdirectories?

(为清楚起见进行了更新)(在底部添加了解决方案)

我在网上找到了一个 makefile,它在该目录中构建所有 cpp 文件并编译它们。

但我不知道如何将文件包含在子目录中。

以下是发生的事件的细目分类:

:

g++    -c -o main.o main.cpp
main.cpp: In function 'int main(int, char**)':
main.cpp:6:2: error: 'testFunction' was not declared in this scope
  testFunction();
  ^~~~~~~~~~~~
make: *** [<builtin>: main.o] Error 1

:

g++    -c -o main.o main.cpp
g++  main.o -Wall  -o testfile
/usr/bin/ld: main.o: in function `main':
main.cpp:(.text+0x14): undefined reference to `testFunction()'
collect2: error: ld returned 1 exit status
make: *** [makefile:34: testfile] Error 1

这里是供参考的makefile:

TARGET = testfile
LIBS = 
CC = g++
CFLAGS = -g -Wall

.PHONY: default all clean

default: $(TARGET)
all: default

OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp))
HEADERS = $(wildcard *.hpp)

%.o: %.c $(HEADERS)
    $(CC) $(CFLAGS) -c $< -o $@

.PRECIOUS: $(TARGET) $(OBJECTS)

$(TARGET): $(OBJECTS)
    $(CC) $(OBJECTS) -Wall $(LIBS) -o $@

clean:
    -rm -f *.o
    -rm -f $(TARGET)

提前致谢!


接受答案后更新的 makefile:

(更改包括目录,CC 替换为 CXX,%.c 替换为 %.cpp)

TARGET = testfile
DIRS =
LDLIBS =

CXX = g++

CXXFLAGS= -g -Wall

# this ensures that if there is a file called default, all or clean, it will still be compiled
.PHONY: default all clean

default: $(TARGET)
all: default

# substitute '.cpp' with '.o' in any *.cpp 
OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp $(addsuffix /*.cpp, $(DIRS))))
HEADERS = $(wildcard *.h)

# build the executable
%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@
    
# if make is interupted, dont delete any object file
.PRECIOUS: $(TARGET) $(OBJECTS)

# build the objects
$(TARGET): $(OBJECTS)
    $(CXX) $(OBJECTS) -Wall $(LDLIBS) -o $@ 

clean:
    -rm -f *.o $(addsuffix /*.o, $(DIRS))
    -rm -f $(TARGET)

要了解此处发生的情况,您必须查找 C++(和其他语言)中 declarationdefinition 的定义。你绝对应该这样做。

声明(通常放在头文件中)就像您家的地址。如果有人想给您寄信,他们需要您的地址。如果你的主函数想要调用另一个函数,比如testFunction(),它需要函数的声明。

第一个错误是因为你没有包含头文件,所以编译器没有你要调用的函数的声明,这意味着它不会编译你的调用函数。

但是要让信真正到达,您需要有实际的房子。地址是声明,你的房子是定义......在这种情况下是实际的功能实现。它存在于 test.cpp 文件中。当你 link 你的代码在一起时, linker (在这种情况下我猜 linker 就像邮政服务 :p :) )将尝试 link对定义的调用。

但是,您可以看到您没有编译 test.cpp 文件,也没有 link 编译目标文件:

g++  main.o -Wall  -o testfile

这里我们看到了 main.o,但没有看到 gui/test.o

为什么不呢?这一行:

OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp))

匹配所有*.cpp个文件并将它们转换为.o个文件。但是 *.cpp 只匹配当前目录中的文件,如 main.cpp。如果你想把文件放在不同的目录中,你必须告诉 make 它们在哪里;例如:

OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp gui/*.cpp))