Namespaces and Multiple Files

Your own namespace

You know std is a namespace: a named group that keeps names from clashing. You can make your own:

#include <iostream>
using namespace std;

namespace geometry {
    const double PI = 3.14159;
    double circleArea(double r) { return PI * r * r; }
}

namespace money {
    double circleArea(double r) { return 0; }   // same name, no clash
}

int main() {
    cout << geometry::circleArea(2) << "\n";
    cout << geometry::PI << "\n";
    return 0;
}

Output

12.5664
3.14159

Splitting a program into files

Real projects have many files. A class is usually split in two:

  • A header file (.h) that declares what exists – the class and its method list.
  • A source file (.cpp) that defines how the methods work.

Counter.h

#pragma once            // only include this file once

class Counter {
    int value = 0;
public:
    void increment();
    int get() const;
};

Counter.cpp

#include "Counter.h"     // quotes for your own files, <> for library files

void Counter::increment() { value++; }
int Counter::get() const { return value; }

main.cpp

#include <iostream>
#include "Counter.h"

int main() {
    Counter c;
    c.increment();
    c.increment();
    std::cout << c.get() << "\n";
    return 0;
}

Compile all the .cpp files together on your computer:

g++ main.cpp Counter.cpp -o app
./app

Remember: Headers say what exists; source files say how it works. #pragma once stops a header being included twice.

Tip: Never put using namespace std; in a header file – it would leak into every file that includes it.

HOME LABS COMMUNITY DASHBOARD