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

1
  • 1
    Use the gcc -I../path/to/include/ to add a new directory to the include search path. You can use as many -I as you need. Commented Mar 5, 2021 at 3:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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..
@DavidC.Rankin Thanks for the heads-up, I edited the answer to specifically point out small projects.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.