如何为结构化文件系统编写Makefile [英] How to write a Makefile for structured file system
问题描述
我正在尝试学习如何为我的项目编写makefile.鉴于我正在使用诸如sublime-text和终端之类的文本编辑器.
I'm trying to learn how to write makefiles for my projects. Given that I'm using a text editor like sublime-text and the terminal.
如果所有文件都在同一目录中,我知道如何编写一个makefile来编译一个文件及其相关的头文件.
I know how to write a makefile to compile a single file and it's relevant header files IF all files are in the same directory.
想象一下,我们有一个目录和一些子目录,其结构如下:
Imagine that we have a directory and some sub-directories which are structured like this:
Headers
包含所有.h
文件Objects
是用于保存.o
文件的目录,而Sources
是具有源代码.cpp
的目录Makefile
在顶部级别目录.
the Headers
contains all the .h
files Objects
is a directory to hold the .o
files and Sources
is a directory that has the source codes .cpp
The Makefile
is in the top level directory.
.
├── Headers
│ └── function.h
├── Makefile
├── Objects
│ └── main.o
└── Sources
├── function.cpp
└── main.cpp
此刻我的Makefile如下所示:
At the moment my Makefile looks like this:
INC_DIR = Headers
SRC_DIR = Sources
OBJ_DIR = Objects
CXXFLAGS = -c -Wall -I.
CC = g++
SRCS = $(SRC_DIR)/*.cpp
OBJS = $(OBJ_DIR)/*.o
DEPS = $(INC_DIR)/*.h
output: $(OBJ_DIR)/main.o $(OBJ_DIR)/function.o
$(CC) $^ -o $@
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(DEPS)
$(CC) $(CXXFLAGS) $< -o $@
clean:
rm $(OBJ_DIR)/*.o output
执行make
时会产生以下错误
g++ -c -Wall -I. Sources/function.cpp -o Objects/function.o
Sources/function.cpp:2:22: fatal error: function.h: No such file or directory
compilation terminated.
Makefile:30: recipe for target 'Objects/function.o' failed
make: *** [Objects/function.o] Error 1
我知道我做错了事,但不知道该怎么办以及如何解决.
I know that I'm doing something wrong but can't figure out what and how to fix it.
感谢您的帮助和指导.
推荐答案
将Headers
添加到您的CXXFLAGS
:
CXXFLAGS = -c -Wall -I. -IHeaders
# ^^^^^^^^^
您也可能想使用GCC的-M<x>
选项系列生成标头依赖项,并将其包含在Makefile中.
Also you rather might want to generate header dependencies using GCC's -M<x>
option family and include these into your Makefile.
这是GNU make的文档中有关该技术的一个很好的解释:
Here's a pretty good explanation for the technique from GNU make's documentation:
更多信息也可以在这里找到:
more info can be also found here:
这篇关于如何为结构化文件系统编写Makefile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!