Question:
I'm trying to compile a C++ project using the following makefile code:
OBJS = main.o src.o
SDIR = ./src
IDIR = ./include
BDIR = ./bin/
ODIR = $(BDIR)/obj
all: main
%.o: $(SDIR)/%.cpp $(IDIR)/%.h
g++ -c -o $(ODIR)/$@ $(SDIR)/$< -I $(IDIR)
main: $(OBJS)
g++ -o $@ $^ -I $(IDIR)
When I try to compile the program, the following error appears in the terminal:
xxxx@zzz:$ make
g++ -c -o main.o main.cpp
main.cpp:2:17: fatal error: src.h: Arquivo ou diretório não encontrado
#include "src.h"
^
compilation terminated.
<builtin>: recipe for target 'main.o' failed
make: *** [main.o] Error 1
But the file 'src.h' exists and is inside the simple include. So I would like to know what is the reason for the error.
Answer:
Since your .obj is in a subdirectory you need to add that subdirectory as a prefix:
OBJS = $(addprefix $(ODIR)/, main.o src.o)
The rule also needs to use the subdirectory:
$(ODIR)/%.o: $(SDIR)/%.cpp $(IDIR)/%.h
In the end the makefile looks like this:
SDIR = ./src
IDIR = ./include
BDIR = ./bin
ODIR = $(BDIR)/obj
OBJS = $(addprefix $(ODIR)/, main.o src.o)
all: main
$(ODIR)/%.o: $(SDIR)/%.cpp $(IDIR)/%.h
g++ -c -o $@ $< -I $(IDIR)
main: $(OBJS)
g++ -o $@ $^ -I $(IDIR)