【发布时间】:2021-06-19 07:59:46
【问题描述】:
(为清楚起见已更新)(在底部添加了解决方案)
我在网上找到了一个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)
提前致谢!
自接受答案后更新生成文件:
(更改包括目录,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)
【问题讨论】:
-
“不走运”不是我们可以帮助解决的问题。请编辑您的问题并添加(a)您调用的 make 命令,(b)make 打印的编译行,以及(c)您收到的错误消息; (d) 源代码中与错误相关的实际
#include行也很有用。请按照格式正确剪切和粘贴它们(没有屏幕截图或速记参考)。然后我们可以提供帮助。顺便说一句,-I/gui不太可能是正确的,除非你的系统上有一个目录/gui(你可以运行ls /gui并查看你想要的文件)。 -
你说的是源文件还是头文件?
-
@MadScientist 感谢您的回复,我已经更新了这个问题,希望现在更清楚一点吗?如果没有,请告诉我:)
-
@Beta 因为包含头文件时错误发生了变化,我认为它是找不到源?
标签: makefile subdirectory