Menu
Coddy logo textTech

Header Files & Source Files

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 3 of 104.

In C++, code is split into header files (.h) for declarations and source files (.cpp) for implementations.

Header file with header guards (helpers.h)

#ifndef HELPERS_H
#define HELPERS_H

#include <string>

std::string greet(std::string name);
int addNumbers(int a, int b);

#endif

Source file with implementations (helpers.cpp)

#include "helpers.h"

std::string greet(std::string name) {
    return "Hello, " + name + "!";
}

int addNumbers(int a, int b) {
    return a + b;
}

Using them in main

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

int main() {
    std::cout << greet("Alice") << std::endl;
    std::cout << addNumbers(5, 3) << std::endl;
    return 0;
}

Output:

Hello, Alice!
8

Header guards (#ifndef, #define, #endif) prevent a header from being included multiple times. The .h file declares what exists (prototypes), the .cpp file defines how it works (implementations).

challenge icon

Challenge

Medium

Create three helper functions split across a header file and source file:

  • helpers.h — Function declarations with header guards
  • helpers.cpp — Function implementations

Functions to create:

  • greet(name) — returns "Hello, <name>!"
  • ageInTenYears(age) — returns age + 10
  • checkAdult(name, age) — returns "<name> is an adult" if age >= 18, otherwise "<name> is a minor"

Cheat sheet

C++ code is organized into header files (.h) for declarations and source files (.cpp) for implementations.

Header guards prevent multiple inclusions:

#ifndef HELPERS_H
#define HELPERS_H
// declarations here
#endif

Header file (helpers.h) contains function declarations:

#ifndef HELPERS_H
#define HELPERS_H

#include <string>

std::string greet(std::string name);
int addNumbers(int a, int b);

#endif

Source file (helpers.cpp) contains implementations:

#include "helpers.h"

std::string greet(std::string name) {
    return "Hello, " + name + "!";
}

int addNumbers(int a, int b) {
    return a + b;
}

Using the functions in main:

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

int main() {
    std::cout << greet("Alice") << std::endl;
    std::cout << addNumbers(5, 3) << std::endl;
    return 0;
}

Try it yourself

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

int main() {
    std::string name;
    int age;
    std::getline(std::cin, name);
    std::cin >> age;
    
    std::cout << greet(name) << std::endl;
    std::cout << "In 10 years you will be " << ageInTenYears(age) << std::endl;
    std::cout << checkAdult(name, age) << std::endl;
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming