首页 > 解决方案 > 我的 makefile 如何包含子目录?

问题描述

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

我在网上找到了一个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)

标签: makefilesubdirectory

解决方案


要了解这里发生了什么,您必须查看声明的定义与C++(和其他语言)中的定义。你绝对应该这样做。

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

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

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

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

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))

推荐阅读