C++ Header / Sourse separation

  • Move all declarations to header files (*.h)
  • Implementation goes to *.cpp or *.cc

Declaration: tools.h

#pragma once // Ensure file is included only once
void MakeItSunny ();
void MakeItRain ();

Definition: tools.cpp

#include <iostream >
#include "tools.h"
void MakeItRain () {
  // important weather manipulation code
  std::cout << "Here! Now it rains! Happy?\n";
void MakeItSunny () {
  std::cerr << "Not available\n";

Calling main.cpp

#include "tools.h"
int main () {
  MakeItRain ();
  MakeItSunny ();
  return 0;

Use modules and libraries!

Compile modules:

c++ -std=c++11 -c tools.cpp -o tools.o

Organize modules into libraries:

ar rcs libtools.a tools.o <other_modules>

Link libraries when building code:

c++ -std=c++11 main.cpp -L . -ltools -o main

Run the code:



  • Library: multiple object files that are logically connected

Types of libraries:

  • Static: faster, take a lot of space, become part of the end binary, named: lib*.a
  • Dynamic: slower, can be copied, referenced by a program, named lib*.so

Create a static library with:

ar rcs libname.a module.o module.o …
  • Static libraries are just archives just like zip/tar/…
  • The library is a binary object that contains the compiled implementation of some methods
  • Linking maps a function declaration to its compiled implementation
  • To use a library we need a header and the compiled library object