[英]How to write a Makefile (for a c++ project) with a header in the parent directory?
I am currently struggling with make, any tip or tutorial is very much appreciated.我目前正在努力制作,非常感谢任何提示或教程。 My project folder structure looks like this:
我的项目文件夹结构如下所示:
/project
bar.hpp
/folder1
main.cpp // #include "foo.hpp" #include "bar.hpp"
foo.cpp // #include "foo.hpp" #include "bar.hpp"
foo.hpp // #include "bar.hpp"
Makefile
This compiles when called from folder1.从 folder1 调用时编译。
g++-10 -std=c++2a -O3 -fno-pic -no-pie -Wall -I../ main.cpp foo.cpp
I have written the following Makefile but It doesn't work as I expect:我写了以下 Makefile 但它没有像我预期的那样工作:
CXX = g++-10
CXXFLAGS = -std=c++2a -O3 -fno-pic -no-pie -Wall
CPPFLAGS = -I../
.PHONY : all clean distclean
EXE = a.out
SRC = main.cpp foo.cpp
OBJ = $(SRC: .cpp=.o)
INC = $(wildcard *.hpp) ../bar.hpp
all : $(EXE)
clean :
$(RM) *.o
distclean : clean
$(RM) $(EXE)
$(EXE) : $(OBJ)
$(CXX) $(CXXFLAGS) $^ -o $@
$(OBJ) : $(INC) // I hope this means that all object files depend on all header files?
%.o : %.cpp $(INC)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@
I am calling make all from within folder1, but it does not work.我正在从 folder1 中调用 make all,但它不起作用。
I tried to look for c++ make tutorials but couldn't find any with implicit and pattern rules in depth.我试图寻找 c++ 制作教程,但找不到任何深入的隐式和模式规则。
This is the error I get这是我得到的错误
g++-10 -std=c++2a -O3 -fno-pic -no-pie -Wall main.cpp foo.cpp -o a.out
main.cpp:1:10: fatal error: bar.hpp: No such file or directory
1 | #include "bar.hpp"
| ^~~~~~~~~
compilation terminated.
In file included from foo.cpp:1:
foo.hpp:1:10: fatal error: bar.hpp: No such file or directory
1 | #include "bar.hpp"
| ^~~~~~~~~
compilation terminated.
I tried in folder1 to run these commands, and it compiles properly.我尝试在 folder1 中运行这些命令,并且编译正确。
g++-10 -std=c++2a -O3 -fno-pic -no-pie -Wall -c foo.cpp -o foo.o -I../
g++-10 -std=c++2a -O3 -fno-pic -no-pie -Wall -c main.cpp -o main.o -I../
g++-10 -std=c++2a -O3 -fno-pic -no-pie -Wall -o main main.o foo.o
This line is wrong:这一行是错误的:
OBJ = $(SRC: .cpp=.o)
By adding a space before the .cpp
you're saying that OBJ
should replace all words in the variable SRC
that end in " .cpp
" with an ending of .o
.通过在
.cpp
之前添加一个空格,您是说OBJ
应该将变量SRC
中以“ .cpp
”结尾的所有单词替换为结尾.o
。 But there are no words in the variable SRC
that end in " .cpp
", so no changes are made, and the value of OBJ
is the same as the value of SRC
.但是变量
SRC
中没有以“ .cpp
”结尾的词,所以没有做任何改动,obj的值和OBJ
的值是SRC
的。
So, your rule is:所以,你的规则是:
a.out : main.cpp foo.cpp
so no .o
files are built because your target doesn't depend on them.所以没有构建
.o
文件,因为你的目标不依赖于它们。
Remove the space:删除空格:
OBJ = $(SRC:.cpp=.o)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.