rahman
rahman

Reputation: 4948

C++ compilation in linux for newbie

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"?

Upvotes: 1

Views: 131

Answers (3)

Danilo Piazzalunga
Danilo Piazzalunga

Reputation: 7844

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();
}

Upvotes: 0

user529758
user529758

Reputation:

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

Upvotes: 1

J&#246;rg Beyer
J&#246;rg Beyer

Reputation: 3671

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.

Upvotes: 1

Related Questions