Compile c ++ code with make

3

I'm trying to compile a project in C ++ 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 'src.h' file exists and is within the include suffix. Then I would like to know the reason for the error.

    
asked by anonymous 27.12.2017 / 16:31

2 answers

0

The error is indicating that the error is occurring while compiling the main.cpp file. For now it has no evidence that the problem is in the makefile created.

The main.cpp is attempting to include the src.h file in the build, but it is not being found. Considering the statement:

#include "src.h"

The compiler will try to fetch this file in the same folder where main.cpp is saved.

I do not know what folder main.cpp is saved, I assume it is in the /src folder. I also believe that src.h is saved in the /include folder.

It is necessary to change the #include with the exact path of the file src.h .

Something like:

#include "../include/src.h"

Note that this is the answer taking into consideration the things I have assumed before. The important thing is that the inside of your main.cpp (and any other .cpp file that includes something of /include ) the full path is defined.

    
08.11.2018 / 00:17
0

Since your .obj is in a subdirectory you need to add this 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

At 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)
    
08.11.2018 / 00:54