header files and hierarchy

Hi!

Let's say i have 3 programs:

main.cc
a.cpp
a.h
b.cpp
b.h

main.cc uses a.cpp functions and a.cpp uses b.cpp functions. so it is clear hierarchy.
is it possible for main.cc to use directly b.cpp functions?
> 3 programs:

Three translation units.


> is it possible for main.cc to use directly b.cpp functions?

Yes. (Provided they have external linkage.)
is it possible for main.cc to use directly b.cpp functions?

That's what libraries are for, a place to store shared code.

There are typically two kinds, static and dynamic/shared. A static library is an archive of compiled source files that can be installed separately and shared by other programs and libraries. This is the kind suitable for use here.
You don't have 3 programs, you have 3 source files, AKA translation units, you can use to create one unified program.

As long as your main source file includes the header files, and the make commands used compiles and links your 3 source files you can call functions in the other source files.

BTW, you can use whatever extension you want; I prefer to use .hpp/.cpp for C++ header/source files, .h/.c for C files, etc. Makes it easy to see at a glance if a file is C or C++. Or another type source file such as assembly or Fortran or BASIC.

a.hpp
1
2
3
4
5
6
#ifndef A_HPP
#define A_HPP

void A();

#endif 

a.cpp
1
2
3
4
5
6
7
8
#include <iostream>

#include "a.hpp"

void A()
{
   std::cout << "I'm A!\n";
}

b.hpp
1
2
3
4
5
6
#ifndef B_HPP
#define B_HPP

void B();

#endif 

b.cpp
1
2
3
4
5
6
7
8
#include <iostream>

#include "b.hpp"

void B()
{
   std::cout << "This is B!\n";
}

main.cpp
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

#include "a.hpp"
#include "b.hpp"

int main()
{
   A();

   B();
}
I'm A!
This is B!

Splitting code into separate translation units makes managing large amounts of code easier. You really want to deal with 10,000,000 lines of code in one file? I sure don't.

And having separate source code files lets you reuse code that works in another project so you don't have to rewrite code that already works. A library.
Topic archived. No new replies allowed.