Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include header file in different directory in c++

Tags:

c++

makefile

I've been learning c++ and encountered the following question: I have a directory structure like:

 - current directory

  - Makefile

  - include

     - header.h

  - src

      - main.cpp

my header.h :

#include <iostream> 

using namespace std;

void print_hello();

my main.cpp:

#include "header.h"

int main(int argc, char const *argv[])
{
    print_hello();
    return 0;
}

void print_hello()
{
    cout<<"hello world"<<endl;
}

my Makefile:

CC = g++
OBJ = main.o
HEADER = include/header.h 
CFLAGS = -c -Wall 

hello: $(OBJ) 
    $(CC) $(OBJ) -o $@

main.o: src/main.cpp $(HEADER)
    $(CC) $(CFLAGS) $< -o $@

clean: 
    rm -rf *o hello

And the output of make is:

g++ -c -Wall src/main.cpp -o main.o src/main.cpp:1:20: fatal error: header.h: No such file or directory compilation terminated. Makefile:10: recipe for target 'main.o' failed make: *** [main.o] Error 1

What mistakes I have made in here. It's frustrating. Really appreciate any advice!

like image 895
J. Lin Avatar asked Jul 02 '16 16:07

J. Lin


Video Answer


2 Answers

You told the Makefile that include/header.h must be present, and you told the C++ source file that it needs header.h … but you did not tell the compiler where such headers live (i.e. in the "include" directory).

Do this:

CFLAGS = -c -Wall -Iinclude
like image 75
Lightness Races in Orbit Avatar answered Sep 18 '22 19:09

Lightness Races in Orbit


You can either add a -I option to the command line to tell the compiler to look there for header files. If you have header files in include/ directory, then this command should work for you.

gcc -Iinclude/

Since, you are using makefile, you can include this option in CFLAGS macro in your makefile.

CFLAGS = -Iinclude/ -c -Wall

OR

You can include header files using #include "../include/header.h".

like image 29
abhiarora Avatar answered Sep 20 '22 19:09

abhiarora