0

below is the (sample) code structure

/src    
 /poreA
     - a1.h
     - a1.cpp    
 /poreB
     - b1.h
     - b1.cpp    
 /poreC
     - c1.h
     - c1.cpp
     - c2.h    
 /maincpp
     -communicate.h
     -communicate.cpp
     -network.h
     -network.cpp
     -mainfile.cpp
     -mainfile.h

Each folders (poreA,poreB,poreC) has its own make files

c1.h

 #include "a1.h"  

//  struct definitions are defined here

communicate.h

#include "../poreC/include/c1.h"

#ifndef POREC_H_

#define POREC_H_

network.h

#include "communicate.h"

mainfile.h

#include "network.h"

mainfile.cpp

#include "mainfile.h"

#include "network.h"

When I try to compile,

$ gcc -c mainfile.cpp

I get error as

../../poreC/include/c1.h: fatal error: a1.h, no such file or directory
#include "a1.h"

I tried to understand the concept from similar posts but not able to solve this issue

How to invoke function from external .c file in C?

Including a header file from another directory

Sweety
  • 75
  • 1
  • 2
  • 13

1 Answers1

2

When you have include files in multiple directories, you can tell gcc to look there with the -I flag:

$ # if in ./src..
$ g++ -IporeA -IporeB -IporeC -Imaincpp maincpp/mainfile.cpp
$ # if in ./src/maincpp...
$ g++ -I../poreA -I../poreB -I../poreC mainfile.cpp

Usually, small projects may have a single directory that might be called inc or include, where all headers go. That way, gcc would only need a single -Iinc flag instead of one for each directory.

Samuel Hunter
  • 527
  • 2
  • 11
  • 1
    Good write up, only other point is while a single `/inc` or `/include` path is convenient, most large projects and libraries will specify many separate `-I` location. (especially when using `pkg-config`), etc.. – David C. Rankin Mar 05 '21 at 03:52
  • @DavidC.Rankin Thanks for the heads-up, I edited the answer to specifically point out small projects. – Samuel Hunter Mar 05 '21 at 04:00
  • I am extremely sorry. It was a type error from my end. In fact, the header file c1.h calls a1.h and not c2.h. I edited the post. I tried both the approaches you had mentioned (from src and from src/maincpp), it is failing to compile #include "a1.h" which is defined inside c1.h The error is ../poreC/include/c1.h:17:10: fatal error: a1.h: No such file or directory #include "a1.h" ^~~~~~~~~~ compilation terminated. – Sweety Mar 05 '21 at 06:14