makefile - 我的 makefile 如何包含子目录?
问题描述
(为清楚起见进行了更新)(在底部添加了解决方案)
我在网上找到了一个makefile,它在该目录中构建所有cpp文件并编译它们。
但我不知道如何在子目录中包含文件。
以下是发生的情况的细分:
- 我创建文件 test.cpp 和 test.hpp 并将它们放在我的工作目录中包含的子目录“/gui”中,它们包含函数 testFunction()。
- 在不包括 test.hpp 的情况下,我在终端中键入“make”,我收到错误:
:
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
- 如果我包含 (#include "gui/test.hpp"),我会收到一个不同的错误:
:
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
- 但是,如果我随后将“-I/gui”或(猜测)“-I./gui”添加到 CFLAGS,我会收到完全相同的错误消息。
这是供参考的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++(和其他语言)中的定义。你绝对应该这样做。
声明(通常放在头文件中)就像你家的地址。如果有人想给你寄信,他们需要你的地址。如果你的主函数想要调用另一个函数,比如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))
推荐阅读
- calendar - 使用 MS Graph 自动接受用户的会议邀请
- javascript - 单击时显示和隐藏组件的 REACTJS 按钮
- javascript - 我的 Discord 机器人不回复我的消息
- excel - 将范围值中的值附加到已经具有值的数组而不使用 for 循环
- flutter - Flutter:小部件通信:表单中的切换按钮
- python - 当我想从子包和python包中生成多个命令行应用程序时,如何编写准确的“setup.py”(entry_points)
- android - Pixel 5 的 Camera2 API 缩小到 1 倍以下
- reactjs - ReactJS 回调 useEffect 钩子
- vim - Vim 块识别问题
- python - 从二维数组Python中提取索引