C++ · Beginner level

Beginner level · Module 5: C++ Console Project · Lesson 1 of 3

Planning the Program and Splitting Files

Design the program's classes and functions, and organise them into header and source files.

In this lesson you will

  • Turn a requirement into classes and functions
  • Split code into .h and .cpp files with include guards

Key concepts

header filesource fileinclude guard / #pragma oncedeclaration vs definition

The lesson

Start by listing what the program must do and which data it handles. For the Water Point Log: a WaterPoint class for each point and a set of functions for the menu, input and reports.

Put a class definition and function declarations in a header (water_point.h) and member function definitions in a source file (water_point.cpp). Other files #include the header to use the class. #pragma once (or an include guard) stops the header being included twice.

Build all source files together: g++ -Wall -Wextra -std=c++20 main.cpp water_point.cpp -o waterlog. If you forget a source file, the linker reports undefined references.

Step by step

  1. Write the plan: classes, functions and menu options.
  2. Create water_point.h and water_point.cpp.
  3. Move the class into them and include the header from main.cpp.
  4. Build all files with one command.

Practice activity

Submit the plan and a multi-file skeleton that builds and runs with an empty menu.

Expected result: The skeleton compiles without warnings and the plan maps every requirement to a function.

Check your understanding

  1. What belongs in a header file?

    Show answer

    Declarations such as class definitions and function prototypes.

  2. What does #pragma once do?

    Show answer

    Prevents the header from being included more than once in a translation unit.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.