1
votes

Suppose my project directory has 2 sub-directories A and B, A directory contains: A.h and A.cpp, B directory contains: B.h and B.cpp and my root directory contains main.cpp

Now the contents:

A.h:

#include"../B/B.h"
a();

A.cpp:

#include"A.h"
a() 
{   
 b();
 }

B.h:

b();

B.cpp:

b()
{
 cout<<"Blah Blah Blah";
}

main.cpp:

#include"A/A.h"
main()
{
  a();
}

and compile the code using:

c++ main.cpp A.cpp B.cpp

Question is simple: In the first file (A.h), I would not like to write the first line as #include"../B/B.h" How may I change it to #include"B/B.h" or #include"B.h"?

3
Which compiler are you using ? I'd assume G++ ... but one never knows. - J.N.
Why do you need to include B.h in A.h? I don't see any dependency there. - akhisp
@@J.N:I am using ubuntu, so i assume gcc. I just typed "c++ main.cpp A.cpp B.cpp" in the command line I am not very familiar with their difference. if there is a place or command I can check, please let me know ...to let you know the result :) - rahman
@@akhisp: I am calling b() which is defined in B.h. I guess it is called a dependency and needs an inclusion. isn't it? - rahman
Side Note: Your headers are missing include guards - another.anon.coward

3 Answers

1
votes

you can tell the compiler, in which directory/ies the header files are. For gcc/g++ this is the -I path option. path can be absolut (e.g. /home/me/src/projectx/) or relative (e.g.: ..).

You can set it to the top level directory (the onw, where "B" is in) an the write

#include <B/B.h>

and compile it with the -I option ponting to your top level directory.

1
votes

g++ -I[include dir] is exactly for this purpose.

0
votes

Given this layout, with A containing A.h and A.cpp, B containing B.h and B.cpp, and main.cpp in the root directory:

$ ls *.cpp A B
main.cpp

A:
A.cpp  A.h

B:
B.cpp  B.h

You can use `#include "B/B.h" and compile your program with

c++ -I. main.cpp A/A.cpp B/B.cpp 

The -I flag tells the compiler where to look for include files. If you are using GCC, see the GCC Manual.

Source file contents

I edited your example to make it compile and run:

A/A.h:

#include "B/B.h"

void a();

A/A.cpp:

#include "A.h"

void a() 
{
    b();
}

B/B.h:

void b();

B/B.cpp:

#include <iostream>

void b()
{
    std::cout<<"Blah Blah Blah";
}

main.cpp:

#include "A/A.h"

int main()
{
    a();
}