Reputation: 101
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.
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:
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
I have tried to put together a Makefile
by following the GNU make and the answer to this post.
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
Which will generate the following error when make
is executed
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.
I'd appreciate any help and guidance.
Upvotes: 0
Views: 291
Reputation: 1
Add Headers
to your CXXFLAGS
:
CXXFLAGS = -c -Wall -I. -IHeaders
# ^^^^^^^^^
Also you rather might want to generate header dependencies using GCC's -M<x>
option family and include these into your Makefile.
Here's a pretty good explanation for the technique from GNU make's documentation:
4.14 Generating Prerequisites Automatically
more info can be also found here:
Makefile (Auto-Dependency Generation)
Upvotes: 3