Chapter 03 of 48

C++ Program Structure

In the previous chapter, Your First C++ Program, we wrote a tiny program and ran it. Real programs are bigger: they have comments, several headers, global constants, many functions and often many files. In this chapter we look at the overall layout of a C++ program, and then at what actually happens between typing g++ hello.cpp and getting an executable. Understanding this pipeline makes errors like "not declared in this scope" and "undefined reference" easy to fix.


The Parts of a C++ Program

Here is a small program that contains all the usual parts, each one numbered with a comment:

// 1. Comments: this program calculates the area of a circle

// 2. Preprocessor directives
#include <iostream>

// 3. Global declarations
const double PI = 3.14159;

// 4. Function declaration (prototype)
double area(double radius);

// 5. The main function: execution starts here
int main() {
    double r = 2.0;                          // local variable
    std::cout << "Radius: " << r << '\n';
    std::cout << "Area: " << area(r) << '\n';
    return 0;                                // 0 means success
}

// 6. Function definition
double area(double radius) {
    return PI * radius * radius;
}

Output:

Radius: 2
Area: 12.5664

The usual order of the parts is:

PartPurposeRequired?
1. CommentsExplain the code to humans; ignored by the compilerNo (but strongly recommended)
2. Preprocessor directivesInclude headers, define macrosAlmost always (you need headers to use the library)
3. Global declarationsConstants, variables, types visible to the whole fileNo
4. Function declarationsTell the compiler a function exists before it is usedOnly if a function is used before its definition
5. main()The entry point where execution startsYes, exactly one
6. Function definitionsThe actual code of your functionsFor every function you call

Let's go through these parts one by one.


1. Comments

C++ has two kinds of comments:

// single-line comment: runs until the end of the line

/* multi-line comment:
   runs until the closing marker */

Comments are removed before compilation, so they never make your program bigger or slower. Two rules to remember: /* */ comments cannot be nested (the first */ ends the comment), and comment markers inside a string literal like "// not a comment" are just text.

Good comments explain why the code does something, not what each line obviously does. i++; // increment i is noise; // marks are out of 50, convert to percentage is helpful.


2. Preprocessor Directives

Lines beginning with # are processed by the preprocessor, a text-processing step that runs before compilation. The most important directive is #include, which comes in two forms:

FormUsed forWhere it searches
#include <iostream>Standard library and system headersDirectories added with -I, then the compiler's system include directories
#include "greet.h"Your own headersUsually the directory of the current file first, then the system directories

Other directives you will meet include #define (text macros), #ifdef/#ifndef/#endif (conditional compilation) and #pragma (compiler-specific instructions). Directives do not end with a semicolon, because they are not C++ statements.


3. Namespaces and using

Large programs use thousands of names. If two libraries both define a function called count, the names would clash. C++ solves this with namespaces.

A namespace is a named region that groups related names, so that the same name can exist in different namespaces without conflict.

The entire standard library is inside the namespace std, which is why we write std::cout, std::string and std::vector. There are three ways to refer to cout:

WayExampleEffect
Qualified namestd::coutClear and safe. Recommended.
Using-declarationusing std::cout;Makes only cout usable without std::
Using-directiveusing namespace std;Makes every name from std usable without std::

A using-declaration is a good middle path:

#include <iostream>

using std::cout;   // bring in only the names we need

int main() {
    cout << "No std:: needed for cout here\n";
    std::cout << "But std::cout still works too\n";
}

Output:

No std:: needed for cout here
But std::cout still works too

Why is using namespace std; risky?

You will see using namespace std; in many textbooks and competitive programming code. It saves typing, but it pulls hundreds of names into your code, and they can collide with your own names:

#include <algorithm>
#include <iostream>
using namespace std;

int count = 0;          // our own global variable

int main() {
    count++;            // which count? ours, or std::count?
    cout << count << '\n';
}

Compiler output (the first lines; GCC then lists every candidate):

main.cpp: In function ‘int main()’:
main.cpp:8:5: error: reference to ‘count’ is ambiguous
    8 |     count++;            // which count? ours, or std::count?
      |     ^~~~~

The compiler cannot tell whether count means our variable or the algorithm std::count from <algorithm>. The rule of thumb used in industry:

  • Never put using namespace std; in a header file, because it then affects every file that includes that header.

  • In small programs and contest code, it is acceptable if you understand the risk.

  • In real projects, write std:: or use individual using-declarations.

Namespaces get a full chapter of their own later, Namespaces, where you will create your own.


4. Declarations Before Use

The C++ compiler reads a file from top to bottom. A name must be declared before the point where it is used. Look at this program:

#include <iostream>

int main() {
    std::cout << twice(5) << '\n';   // twice is not declared yet
}

int twice(int n) { return 2 * n; }
order.cpp: In function ‘int main()’:
order.cpp:4:18: error: ‘twice’ was not declared in this scope
    4 |     std::cout << twice(5) << '\n';   // twice is not declared yet
      |                  ^~~~~

When the compiler reaches line 4, it has not yet seen twice. There are two fixes: move the definition of twice above main, or put a declaration (also called a prototype) above main, as we did with area in the first program of this chapter:

double area(double radius);                   // declaration: name, parameters, return type
double area(double radius) { return PI * radius * radius; }   // definition: the body
DeclarationDefinition
Introduces a name and its typeA declaration that also provides the body (or allocates storage, for variables)
Can appear many timesMust appear exactly once in the whole program (the One Definition Rule, with some exceptions such as inline functions and templates)
double area(double radius);double area(double radius) { ... }

5. The main Function

The standard allows two forms of main:

int main() { ... }
int main(int argc, char* argv[]) { ... }   // char** argv is the same thing

The second form receives the command-line arguments: argc is the argument count and argv is an array of C strings. argv[0] is usually the program's own name.

#include <iostream>

int main(int argc, char* argv[]) {
    std::cout << "argc = " << argc << '\n';
    for (int i = 0; i < argc; ++i)
        std::cout << "argv[" << i << "] = " << argv[i] << '\n';
}

Running it as ./program hello 42 prints:

argc = 3
argv[0] = ./program
argv[1] = hello
argv[2] = 42

Note that "42" arrives as text, not as a number. Converting text to numbers is covered in Type Conversion & Casting.

The value returned from main becomes the program's exit status, which the shell can read:

#include <iostream>

int main() {
    std::cout << "Something went wrong\n";
    return 3;
}

Running ./program; echo "exit: $?" in a Linux shell prints:

Something went wrong
exit: 3

6. Statements, Blocks and Whitespace

  • A statement is one instruction, usually ending with a semicolon: int r = 2;, std::cout << r;, return 0;.

  • A block (or compound statement) is a group of statements inside { }. Function bodies, loop bodies and if bodies are blocks. Variables declared inside a block exist only inside that block.

  • C++ is free-form: spaces, tabs and newlines between tokens are mostly ignored. The program below has almost all optional whitespace removed, and it still compiles and runs.

#include <iostream>
int main(){std::cout<<"Same"<<'\n';return 0;}

Output:

Same

But please don't write code like that. Indentation and spacing exist for humans. (Whitespace does matter in a few places: inside string literals, in preprocessor lines, and between tokens like int x, where intx would be one different word.)

The compiler sees your code as a sequence of tokens, the smallest meaningful units:

Token kindExamples
Keywordsint, return, class, const
Identifiersmain, area, radius
Literals2.0, 'A', "Radius: "
Operators+, *, <<, ::
Punctuators;, {, }, (, ), ,

For example, return PI * radius * radius; consists of 7 tokens: return, PI, *, radius, *, radius, ;.


From Source Code to Executable

When you run g++ hello.cpp -o hello, four separate steps happen behind the scenes:

 hello.cpp
    │  1. Preprocessing  (g++ -E)  handles #include, #define, removes comments
    ▼
 hello.ii   ← "translation unit": pure C++ code, all headers pasted in
    │  2. Compilation    (g++ -S)  checks syntax and types, optimises
    ▼
 hello.s    ← assembly language for your CPU
    │  3. Assembly       (g++ -c)  converts assembly to machine code
    ▼
 hello.o    ← object file: machine code, but calls to other code are unresolved
    │  4. Linking        (g++ hello.o -o hello)  joins object files + libraries
    ▼
 hello      ← executable

You can stop after each step to see the intermediate files:

g++ -std=c++23 -E hello.cpp -o hello.ii    # only preprocess
g++ -std=c++23 -S hello.cpp -o hello.s     # preprocess + compile to assembly
g++ -std=c++23 -c hello.cpp -o hello.o     # ... + assemble to an object file
g++ hello.o -o hello                       # link into an executable

Try the first command on the 6-line "Hello, C++!" program from Introduction to C++. With g++ 15, hello.ii is almost 69,000 lines long (68,847 lines in our run)! That is the content of <iostream> and every header it includes, pasted into your file. This is why #include is described as "copy-paste".

StageTypical errors found here
Preprocessingfatal error: greet.h: No such file or directory
CompilationSyntax errors, type errors, "was not declared in this scope"
Linking"undefined reference to ...", "multiple definition of ...", "undefined reference to main"

Knowing the stage tells you where to look. A compiler error is about one file's code. A linker error means each file compiled fine, but a definition is missing (or duplicated) when everything is joined together.


Programs With Multiple Files

Real projects split code into many files. The standard pattern is:

  • a header file (.h or .hpp) with declarations,

  • a source file (.cpp) with the matching definitions,

  • other source files that #include the header to use those functions.

greet.h:

#ifndef GREET_H
#define GREET_H

#include <string>

void greet(const std::string& name);   // declaration only

#endif

greet.cpp:

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

void greet(const std::string& name) {  // definition
    std::cout << "Hello, " << name << "!\n";
}

main.cpp:

#include "greet.h"

int main() {
    greet("Riya");
    greet("Arjun");
}

Compile both source files together (headers are never compiled on their own; they are included):

g++ -std=c++23 -Wall -Wextra main.cpp greet.cpp -o app
./app

Output:

Hello, Riya!
Hello, Arjun!

Each .cpp file is compiled separately into its own object file, and the linker joins them. In big projects this separate compilation saves a lot of time: when you change greet.cpp, only that file is recompiled.

What happens if we forget greet.cpp?

g++ -std=c++23 -Wall -Wextra main.cpp -o app
/usr/bin/x86_64-linux-gnu-ld.bfd: /tmp/ccwkTe2D.o: in function `main':
main.cpp:(.text+0x48): undefined reference to `greet(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
/usr/bin/x86_64-linux-gnu-ld.bfd: main.cpp:(.text+0x85): undefined reference to `greet(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2: error: ld returned 1 exit status

main.cpp compiled fine, because the header promised that greet exists. But at link time nobody provided its definition. (The long name is the full type of std::string; the /tmp/...o name is a temporary object file and changes each time.)

Header guards

The lines #ifndef GREET_H, #define GREET_H and #endif are an include guard. If a header gets included twice in the same .cpp file (which easily happens indirectly), the second copy is skipped, avoiding "redefinition" errors. Most compilers also support the shorter, non-standard but universal #pragma once at the top of the header, which does the same job.


A Glimpse of the Future: Modules (C++20) and import std; (C++23)

Pasting tens of thousands of lines of headers into every file is slow. C++20 introduced modules, and C++23 added the standard library module std, which replaces all standard headers with one line:

import std;   // C++23: the whole standard library as one module

int main() {
    std::println("Hello from import std!");
}

Output:

Hello from import std!

Compiler support is still settling. With g++ 15 it works when modules are switched on and the std module is built first, for example: g++ -std=c++23 -fmodules -fsearch-include-path bits/std.cc main.cpp. MSVC and Clang have their own steps, and build systems like CMake are adding support. Because of this, most code today (and this tutorial) still uses #include.


Common Mistakes

  • Using a function before declaring it, leading to "was not declared in this scope". Add a prototype or move the definition up.

  • Putting a semicolon after #include or #define. Directives are not statements.

  • Putting function definitions in a header that is included in several .cpp files. Each file then defines the function, and the linker reports "multiple definition". Put declarations in headers and definitions in .cpp files (or mark the function inline, covered in Default Arguments & Inline Functions).

  • Compiling a header or forgetting a .cpp. Pass every .cpp file to the compiler (or let your build system do it), never the .h files.

  • using namespace std; in a header, which silently affects every file that includes it.

  • Using <> for your own header. #include <greet.h> searches only the system directories (unless you add -I.), so it fails with "No such file or directory".


Interview / GATE Questions

What are the stages of compiling a C++ program?

Preprocessing (headers and macros expanded), compilation (C++ to assembly), assembly (assembly to an object file) and linking (object files and libraries joined into an executable).

What is the difference between #include <file> and #include "file"?

The exact search order is implementation-defined, but with GCC and Clang: angle brackets search the directories given with -I and then the system/standard include directories (not the current file's directory). Quotes search the directory of the current file first, then the same directories as angle brackets. Use quotes for your own headers.

"undefined reference to greet": compiler error or linker error?

A linker error. The code compiled because a declaration was visible, but no object file or library provided the definition.

What is a translation unit?

A single source file after preprocessing, that is, the .cpp file with all its included headers pasted in and macros expanded. The compiler compiles one translation unit at a time.

Why should using namespace std; not be used in header files?

Every file that includes the header gets all std names dumped into its global scope, which can create ambiguous names and hard-to-find errors in code the header author has never seen.

What are the two standard forms of main?

int main() and int main(int argc, char* argv[]). Implementations may allow additional forms, but the return type must always be int.

How many tokens are in std::cout << x + 1;?

8: std, ::, cout, <<, x, +, 1, ;.


In Simple Words

A C++ program is a set of declarations and definitions, read from top to bottom, with execution starting in main. The preprocessor pastes headers in, the compiler turns each .cpp file into an object file, and the linker joins them into one executable.

Layout    → comments, #includes, globals, prototypes, main(), function definitions
Rule      → declare before use; define exactly once (ODR)
Headers   → declarations (.h); sources → definitions (.cpp); guard every header
Pipeline  → preprocess (-E) → compile (-S) → assemble (-c) → link
Errors    → "not declared" = compiler, "undefined reference" = linker

Next, in Variables & Data Types, we start storing data: how to create variables, the built-in types C++ offers, and how much memory each one uses.