Compile c++ code with make

Asked

Viewed 263 times

4

I am 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 file 'src. h' exists and is within simply include. So I would like to know what the reason for the error is.

2 answers

1

As your . obj are 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

In the end 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)

0

The error is indicating that the error is happening while compiling the file main.cpp. For now you have no evidence that the problem is in the created Makefile.

The main.cpp is trying to include the file src.h in the compilation, but this is not being found. Considering the statement:

#include "src.h"

The compiler will try to fetch this file in the same folder as the main.cpp this save.

I don’t know what folder main.cpp you’re safe, I assume it’s in the folder /src. I also believe that the src.h is saved in the folder /include.

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

Something like:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.