C++ C++

Splitting a C++ Program Into Header and Source Files: One Pricing Function for Two Hotel Programs

Dima Nov 17, 2026

Introduction

Every C++ program starts as one .cpp file, and sooner or later it stops being one. A second program needs the same function, or the file gets too long to find anything in, and code has to move into other files. That is where many beginners meet a new kind of error: messages about "undefined reference", "multiple definition" and "redefinition" that come from code which looks perfectly correct line by line.

Those errors make sense as soon as you know two facts: the compiler handles each .cpp file on its own, without looking at the others, and a separate tool, the linker, joins the results afterwards. In this tutorial we will take two programs that share a pricing function by copy and paste, split that function into its own file, give it a header, and run into each of those errors on purpose, reading what it says and why.

I will assume you are working in the C/C++ sandbox on Bytestark, in /home/coder/learning, and that you can write and compile a one-file C++ program with functions, std::string and std::vector. We will compile with g++ -std=c++17.


Background

The text of a .cpp file, together with everything its #include lines pull in, is called a translation unit. g++ compiles each translation unit separately, into an object file (.o). While compiling one unit, it knows nothing about any other .cpp file, even one named on the same command line.

Two words matter for everything below:

  • A declaration tells the compiler that something exists and what its type is, without providing it. int nightly_rate(const std::string& room_type, bool weekend);, ending in a semicolon, declares a function. It is enough for the compiler to check a call and generate code that calls the function.
  • A definition provides the thing itself. For a function, that is the declaration followed by a body in braces.

The rule that connects them is called the one definition rule: something can be declared as many times as you like, but in the whole program, a function must be defined exactly once.

After compiling, the linker combines all the object files into one executable. Every call compiled against a mere declaration is left as a note saying "call nightly_rate here, wherever it ends up"; the linker finds the one definition in some object file and connects the call to it. When the linker cannot find a definition, or finds two, it is the linker, not the compiler, that complains.

A header file (.h) is a file of declarations meant to be included by .cpp files. #include "pricing.h" literally pastes the text of pricing.h into the file at that point, before compilation starts.


Practical Scenario

A small family hotel runs two little C++ programs. The front desk uses checkin, which prints a guest's bill when they check in. Each night, the night auditor runs report, which prices every current booking and prints the total that must match the takings in the accounting system.

Both programs need the same rule for the price of a night: a standard room costs 90 EUR, a suite 160 EUR, and Friday and Saturday nights carry a weekend surcharge. The function that implements that rule was written once for checkin and then copied into report.

Last month the owner raised the weekend surcharge from 10 EUR to 20 EUR. The developer changed checkin. Nobody remembered that report had its own copy. Since then, every night with a weekend booking ends with the auditor's total not matching the money the front desk collected, and someone spends half an hour looking for an error in the cash.


The Problem

Here are the two programs as they are today. Create both files:

touch checkin.cpp report.cpp


Put this in checkin.cpp:

#include <iostream>
#include <string>

int nightly_rate(const std::string& room_type, bool weekend) {
    int rate = 90;
    if (room_type == "suite") {
        rate = 160;
    }
    if (weekend) {
        rate += 20;
    }
    return rate;
}

int main() {
    int total = nightly_rate("suite", false) + 2 * nightly_rate("suite", true);
    std::cout << "Ilinca Marin, suite, Thu-Sun: " << total << " EUR\n";
    return 0;
}


And this in report.cpp:

#include <iostream>
#include <string>

int nightly_rate(const std::string& room_type, bool weekend) {
    int rate = 90;
    if (room_type == "suite") {
        rate = 160;
    }
    if (weekend) {
        rate += 10;
    }
    return rate;
}

int main() {
    int ilinca = nightly_rate("suite", false) + 2 * nightly_rate("suite", true);
    int radu = 2 * nightly_rate("standard", false);
    int elena = 2 * nightly_rate("standard", true);

    std::cout << "Ilinca Marin  " << ilinca << " EUR\n";
    std::cout << "Radu Pop      " << radu << " EUR\n";
    std::cout << "Elena Dobre   " << elena << " EUR\n";
    std::cout << "Total         " << ilinca + radu + elena << " EUR\n";
    return 0;
}


Build and run both:

g++ -std=c++17 -Wall -Wextra -o checkin checkin.cpp && ./checkin
g++ -std=c++17 -Wall -Wextra -o report report.cpp && ./report


Ilinca Marin, suite, Thu-Sun: 520 EUR
Ilinca Marin  500 EUR
Radu Pop      180 EUR
Elena Dobre   200 EUR
Total         880 EUR


Ilinca stays three nights in a suite, Thursday, Friday and Saturday: one weekday night and two weekend nights. The front desk charged her 160 + 2 × 180 = 520 EUR. The night report says 500 EUR, because its copy of nightly_rate still adds 10 for the weekend, not 20. Elena's two weekend nights are 20 EUR short as well, and the total is 880 EUR when the front desk collected 920.

Both programs compile without a warning, and each one is internally consistent. The defect is not in any line of code; it is that the same rule exists in two places. The two nightly_rate functions are only "the same function" in our heads. To the compiler they are two unrelated functions in two unrelated programs, so nothing could ever have noticed that they drifted apart.


One Definition in Its Own File

The fix is to keep a single definition of nightly_rate in a file of its own and build both programs from it. Create the file:

touch pricing.cpp


Put the function in it, with the current 20 EUR surcharge:

#include <string>

int nightly_rate(const std::string& room_type, bool weekend) {
    int rate = 90;
    if (room_type == "suite") {
        rate = 160;
    }
    if (weekend) {
        rate += 20;
    }
    return rate;
}


Now delete the whole nightly_rate function from checkin.cpp, so that it holds only the two includes and main. Build it, listing both .cpp files on the command line:

g++ -std=c++17 -Wall -Wextra -o checkin checkin.cpp pricing.cpp && ./checkin


checkin.cpp: In function ‘int main()’:
checkin.cpp:5:17: error: ‘nightly_rate’ was not declared in this scope
    5 |     int total = nightly_rate("suite", false) + 2 * nightly_rate("suite", true);
      |                 ^~~~~~~~~~~~


The function is in pricing.cpp, and pricing.cpp is on the same command line, yet g++ says it does not know nightly_rate. This is translation units at work. g++ compiles checkin.cpp as a unit of its own, reading it from top to bottom, and in that text there is no mention of nightly_rate before line 5. It does not look into pricing.cpp; that file is compiled separately, later. The message comes from the compiler, as the checkin.cpp:5:17: error: prefix shows: file, line, column.

The compiler does not need the function's body to compile a call. It needs a declaration. Add one to checkin.cpp, right after the includes, so the file reads:

#include <iostream>
#include <string>

int nightly_rate(const std::string& room_type, bool weekend);

int main() {
    int total = nightly_rate("suite", false) + 2 * nightly_rate("suite", true);
    std::cout << "Ilinca Marin, suite, Thu-Sun: " << total << " EUR\n";
    return 0;
}


g++ -std=c++17 -Wall -Wextra -o checkin checkin.cpp pricing.cpp && ./checkin


Ilinca Marin, suite, Thu-Sun: 520 EUR


It builds and prints 520 EUR. The new line is a declaration: the function's return type, name and parameter types, and a semicolon instead of a body. With it, the compiler can check that nightly_rate("suite", false) passes a string and a bool and produces an int, and it generates a call to "some function named nightly_rate with these parameter types". It does not know or care where the body is.

The body is found afterwards. pricing.cpp is compiled into its own object file, which contains the definition, and the linker connects the call in checkin's object file to that definition. Two translation units, compiled separately, joined at the end.

Try it: Change the declaration in checkin.cpp to int nightly_rate(const std::string& room_type);, without the bool parameter, and rebuild. Predict whether the compiler or the linker complains. The compiler does: error: too many arguments to function ‘int nightly_rate(const std::string&)’, twice, once per call, with a note pointing at the declaration. While compiling checkin.cpp, the declaration is the only description of the function the compiler has, and it checks every call against it. Restore the bool weekend parameter.


A Header So the Declaration Is Written Once

We have one definition now, but the declaration still has to be typed into every file that calls the function, and report.cpp will need it too. If someone changes the function's parameters, every copy of the declaration has to change with it, which is the copy-and-paste problem again on a smaller scale. A header file gives the declaration a single home.

Create the header:

touch pricing.h


Put the declaration in it:

#include <string>

int nightly_rate(const std::string& room_type, bool weekend);


Now use it everywhere. In pricing.cpp, replace #include <string> with #include "pricing.h", so the file starts like this:

#include "pricing.h"

int nightly_rate(const std::string& room_type, bool weekend) {


Replace the whole of checkin.cpp with:

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

int main() {
    int total = nightly_rate("suite", false) + 2 * nightly_rate("suite", true);
    std::cout << "Ilinca Marin, suite, Thu-Sun: " << total << " EUR\n";
    return 0;
}


And in report.cpp, delete its own copy of nightly_rate and replace the two includes at the top with these two, leaving main as it is:

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


Build both programs. Each one is built from its own main file plus the shared pricing.cpp:

g++ -std=c++17 -Wall -Wextra -o checkin checkin.cpp pricing.cpp && ./checkin
g++ -std=c++17 -Wall -Wextra -o report report.cpp pricing.cpp && ./report


Ilinca Marin, suite, Thu-Sun: 520 EUR
Ilinca Marin  520 EUR
Radu Pop      180 EUR
Elena Dobre   220 EUR
Total         920 EUR


The report now agrees with the front desk: 520 EUR for Ilinca, 220 for Elena's weekend, 920 in total, which is what was collected. There is exactly one place where the weekend surcharge is written, and both programs are built from it.

Let's look at how #include "pricing.h" works. It is handled by the preprocessor before compilation, and it pastes the whole text of pricing.h in place of the line. You can see the effect by asking g++ to stop after preprocessing (-E), dropping its line markers (-P), and searching for our function in what it would compile for pricing.cpp:

g++ -std=c++17 -E -P pricing.cpp | grep -n nightly_rate


16772:int nightly_rate(const std::string& room_type, bool weekend);
16773:int nightly_rate(const std::string& room_type, bool weekend) {


The translation unit for pricing.cpp is now more than 16 000 lines, nearly all of them from <string>, which pricing.h includes. At the very end, the declaration from the header sits directly above the definition. That is not an accident: we include the header in its own .cpp file on purpose, so the compiler sees both and checks that they match. checkin.cpp and report.cpp get exactly the same declaration line, so all three files now share one description of the function.

Two details of the header are decisions, not habits:

  • The header includes <string> itself, because its declaration mentions std::string. A header should compile no matter what was included before it, so it includes whatever it uses. That is also why checkin.cpp no longer needs its own #include <string>.
  • Our own header is included with quotes, "pricing.h", and library headers with angle brackets, <string>. Quotes make the preprocessor look in the current file's folder first and then in the system folders; angle brackets look only in the system folders. With <pricing.h>, the build fails with pricing.h: No such file or directory.

Try it: In pricing.cpp only, change the definition's return type from int to double and rebuild checkin. Predict whether anything notices the mismatch. The compiler stops in pricing.cpp with error: ambiguating new declaration of ‘double nightly_rate(const std::string&, bool)’ and a note pointing at pricing.h:3, the old declaration returning int. It catches it only because pricing.cpp includes its own header. Change it back to int.


Compiling Separately and Reading the Linker's Errors

So far each g++ command has compiled and linked in one go. Doing the two steps by hand shows exactly which tool produces which error, and it is how bigger projects are built. -c means "compile only, do not link". Compile all three source files:

g++ -std=c++17 -Wall -Wextra -c pricing.cpp checkin.cpp report.cpp && ls -1 *.o


checkin.o
pricing.o
report.o


Each .cpp file became one object file, each compiled without looking at the others. Now link them into the two programs. When g++ is given only .o files, it skips compilation and runs the linker:

g++ -o checkin checkin.o pricing.o && g++ -o report report.o pricing.o && ./checkin && ./report


Ilinca Marin, suite, Thu-Sun: 520 EUR
Ilinca Marin  520 EUR
Radu Pop      180 EUR
Elena Dobre   220 EUR
Total         920 EUR


The same programs, built in two visible steps. pricing.o is linked into both executables: it is compiled once and reused. In a large project, this is why changing one .cpp file only requires recompiling that one file and relinking, instead of recompiling everything.

Now leave out pricing.cpp and build checkin from its own file alone:

g++ -std=c++17 -Wall -Wextra -o checkin checkin.cpp


/usr/bin/ld: /tmp/cc2D3F8F.o: in function `main':
checkin.cpp:(.text+0x35): undefined reference to `nightly_rate(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
/usr/bin/ld: checkin.cpp:(.text+0x67): undefined reference to `nightly_rate(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
collect2: error: ld returned 1 exit status


This error looks nothing like a compiler error, because it is not one. Let's take it apart.

  • /usr/bin/ld is the linker. Compilation of checkin.cpp succeeded: the header gave the compiler a declaration, which was all it needed.
  • /tmp/cc2D3F8F.o is the object file g++ produced from checkin.cpp in a temporary folder, since we did not ask for -c. The random part of the name is different on every run, so yours will not match.
  • in function 'main' and checkin.cpp:(.text+0x35) say where the unresolved call is: in main, at byte offset 0x35 of the compiled code. Linker errors refer to machine code, not to your source lines, which is why there is no line number.
  • undefined reference to 'nightly_rate(...)' is the complaint: there is a call to this function, and no object file being linked contains its definition. The long parameter list is just const std::string&, bool with std::string written out in full.
  • It appears twice because main calls the function twice.
  • collect2: error: ld returned 1 exit status is g++ reporting that the linker failed, so no executable was written.

The rule of thumb: "not declared" comes from the compiler and means a declaration is missing in this file; "undefined reference" comes from the linker and means a definition is missing from the whole program, usually because a .cpp file was not built or not linked.

Try it: Rebuild with pricing.cpp included again, but first change the second parameter of the definition in pricing.cpp, and only there, from bool weekend to int weekend. Predict which tool complains this time. It is the linker, with the same undefined reference to nightly_rate(..., bool). In C++, a function with an int parameter is a different function from one with a bool parameter, so pricing.cpp now defines a new function that nothing declares, and the one the header declares has no definition. Change it back to bool.


Function Bodies in Headers: Multiple Definition

The front desk wants amounts printed as 520 EUR everywhere, and someone writes a small helper for it. Since it is short and both programs need it, they put the whole function into the header. Replace the whole of pricing.h with:

#include <string>

int nightly_rate(const std::string& room_type, bool weekend);

std::string euros(int amount) {
    return std::to_string(amount) + " EUR";
}


And change the output line in checkin.cpp to use it:

    std::cout << "Ilinca Marin, suite, Thu-Sun: " << euros(total) << "\n";


g++ -std=c++17 -Wall -Wextra -o checkin checkin.cpp pricing.cpp && ./checkin


/usr/bin/ld: /tmp/cccwOm1P.o: in function `euros[abi:cxx11](int)':
pricing.cpp:(.text+0x0): multiple definition of `euros[abi:cxx11](int)'; /tmp/ccG73W1N.o:checkin.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status


Another linker error, the opposite of the last one: multiple definition of 'euros(int)', found in the object file from pricing.cpp after it was already first defined here in the one from checkin.cpp. (The [abi:cxx11] tag is a marker the library adds to functions that return std::string; you can ignore it.)

Follow what #include does and the cause is plain. The header is pasted into checkin.cpp, so that translation unit contains a definition of euros. The header is also pasted into pricing.cpp, so that unit contains a definition of euros too. Each unit compiles fine on its own. When the linker joins them, it finds two definitions of the same function, which breaks the one definition rule, and it cannot know which one to use.

A declaration in a header is harmless no matter how many files include it. A plain function definition in a header is a definition in every file that includes it. There are two correct fixes. One is to keep only the declaration in the header and move the body into pricing.cpp. The other, for small functions, is to mark the function inline. Change the helper's first line in pricing.h to:

inline std::string euros(int amount) {


g++ -std=c++17 -Wall -Wextra -o checkin checkin.cpp pricing.cpp && ./checkin


Ilinca Marin, suite, Thu-Sun: 520 EUR


inline changes the rule for this one function. An inline function may be defined in several translation units, as long as every definition is identical, and the linker keeps one of them instead of reporting a conflict. Since every copy comes from the same header, they are identical by construction. Despite its name, the keyword is not mainly about speed today; in a header, its job is to say "this definition is meant to appear in many files".

Try it: Take the other fix instead. In pricing.h, replace the whole euros function with just its declaration, std::string euros(int amount);, and add the full function, without inline, to the end of pricing.cpp. Predict whether it builds. It does, and prints Ilinca Marin, suite, Thu-Sun: 520 EUR, because the header now contains a declaration, which any number of files may include, and the definition exists in one file only. Either fix is correct; put the inline version back so the next section matches.


Including a Header Twice: Include Guards

The night report should work from a list of bookings instead of three hand-written lines. A booking is a few values that belong together, so we describe it as a struct, and both pricing and report need that type. It goes in its own header.

Create the file:

touch booking.h


Put this in it:

#include <string>

struct Booking {
    std::string guest;
    std::string room_type;
    int weekday_nights;
    int weekend_nights;
};


pricing will now offer a function that prices a whole booking, so its header needs the Booking type and includes booking.h. Replace the whole of pricing.h with:

#include <string>
#include "booking.h"

int nightly_rate(const std::string& room_type, bool weekend);
int booking_total(const Booking& booking);

inline std::string euros(int amount) {
    return std::to_string(amount) + " EUR";
}


Add the definition of booking_total to the end of pricing.cpp:

int booking_total(const Booking& booking) {
    return booking.weekday_nights * nightly_rate(booking.room_type, false)
         + booking.weekend_nights * nightly_rate(booking.room_type, true);
}


And replace the whole of report.cpp with a version that loops over tonight's bookings. It includes booking.h because it creates Booking values, and pricing.h because it calls booking_total and euros:

#include <iostream>
#include <vector>
#include "booking.h"
#include "pricing.h"

int main() {
    std::vector<Booking> tonight = {
        {"Ilinca Marin", "suite", 1, 2},
        {"Radu Pop", "standard", 2, 0},
        {"Elena Dobre", "standard", 0, 2},
    };

    int total = 0;
    for (const Booking& booking : tonight) {
        int amount = booking_total(booking);
        std::cout << booking.guest << ": " << euros(amount) << "\n";
        total += amount;
    }
    std::cout << "Total: " << euros(total) << "\n";
    return 0;
}


g++ -std=c++17 -Wall -Wextra -o report report.cpp pricing.cpp && ./report


In file included from pricing.h:2,
                 from report.cpp:4:
booking.h:3:8: error: redefinition of ‘struct Booking’
    3 | struct Booking {
      |        ^~~~~~~
In file included from report.cpp:3:
booking.h:3:8: note: previous definition of ‘struct Booking’
    3 | struct Booking {
      |        ^~~~~~~


This time it is the compiler, and the message comes with an include chain that reads from the bottom up. The first block says: report.cpp, at line 4, included pricing.h; pricing.h, at line 2, included booking.h; and in there, at line 3, struct Booking is defined again. The note says where it was defined the first time: booking.h, included directly by report.cpp at line 3.

So booking.h was pasted into report.cpp twice, once directly and once through pricing.h. A function may be declared twice, but a struct definition may appear only once in a translation unit, so the second copy is an error. Neither include line is wrong on its own: report.cpp uses Booking itself, and pricing.h needs it for its declaration. In real projects, headers include headers, and sooner or later some file reaches the same header by two paths.

The standard protection is an include guard, which makes a header's contents count only once per translation unit, however many times it is included. Add this as the very first line of both booking.h and pricing.h:

#pragma once


g++ -std=c++17 -Wall -Wextra -o report report.cpp pricing.cpp && ./report
g++ -std=c++17 -Wall -Wextra -o checkin checkin.cpp pricing.cpp && ./checkin


Ilinca Marin: 520 EUR
Radu Pop: 180 EUR
Elena Dobre: 220 EUR
Total: 920 EUR
Ilinca Marin, suite, Thu-Sun: 520 EUR


Both programs build, and the report, now driven by a list of bookings, still totals 920 EUR. #pragma once tells the preprocessor: if this file has already been included in the current translation unit, skip it. The second inclusion of booking.h, through pricing.h, now pastes nothing, so Booking is defined exactly once.

You will also meet the older, fully standard way of writing the same guard, which works with every compiler:

#ifndef BOOKING_H
#define BOOKING_H

/* ... contents of the header ... */

#endif


The first time the header is included, BOOKING_H is not defined, so #ifndef ("if not defined") lets the contents through and #define defines the name. Any later inclusion finds the name defined and skips everything up to #endif. #pragma once is not part of the C++ standard, but GCC, Clang and MSVC all support it, and it cannot go wrong through two headers accidentally using the same guard name. Either way, every header you write should have one.

A few words on the new code itself. {"Ilinca Marin", "suite", 1, 2} creates a Booking by giving its members in the order they are declared in the struct: guest, room type, weekday nights, weekend nights. booking_total multiplies each kind of night by its rate, the same arithmetic as the hand-written lines it replaces, and for (const Booking& booking : tonight) visits each booking through a const reference, so no booking is copied or changed.

Try it: Remove #pragma once from pricing.h only, and rebuild report. Predict whether it builds. It does, because nothing includes pricing.h twice yet. Now add a second #include "pricing.h" line to report.cpp and rebuild: the compiler reports error: redefinition of ‘std::string euros(int)’. An inline function may be defined once in each translation unit, not twice in the same one, so a header without a guard breaks as soon as it is reached twice. Remove the extra include and put the guard back.


Summary

We took two hotel programs that each carried their own copy of the pricing rule, and rebuilt them from one definition in pricing.cpp, one set of declarations in pricing.h, and a shared Booking type in booking.h, so the night report and the front desk can no longer disagree. We built everything with plain g++ commands to keep each step visible. Larger projects describe the same files and steps in a Makefile or with CMake, which is a topic of its own.

  • Each .cpp file, with everything it includes, is compiled on its own as a translation unit; the compiler never looks into another .cpp file.
  • A declaration is enough to compile a call; the definition can live in any one object file, and the linker connects the two.
  • "Not declared in this scope" is a compiler error: add a declaration, usually by including the right header.
  • "Undefined reference" is a linker error: the definition is missing from the program, usually because a .cpp file was not compiled or linked, or because the definition's parameter types differ from the declaration's.
  • Put declarations in a header and include it everywhere the function is used, including its own .cpp file, so the compiler checks that declaration and definition match.
  • Include your own headers with quotes and library headers with angle brackets, and make each header include what it uses.
  • A plain function defined in a header is defined in every file that includes it and causes "multiple definition"; move the body to a .cpp file or mark it inline.
  • Start every header with #pragma once or an #ifndef guard, so that a header reached by two include paths is pasted only once per translation unit.

You need to be logged in to access the cloud lab.

Log in