Learning Hub Search Ctrl K

Legacy C++ › 1. Getting Started

Program Structure and Compilation

main(), headers, the compile-link process and your first program.

beginner #main#compilation#headers#hello-world

Explanation

A C++ program is one or more translation units (.cpp files). Building it has three stages:

  1. Preprocess: #include and #define are expanded into plain text.
  2. Compile: each translation unit becomes an object file (.o / .obj).
  3. Link: object files and libraries are combined into one executable.

Execution starts in main. It returns int; 0 means success. Unlike other functions, main may omit its return and then returns 0 implicitly.

Example

#include <iostream>   // declares std::cout

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

Build and run with GCC: g++ -std=c++03 hello.cpp -o hello. With Visual C++: cl /EHsc hello.cpp.

Common pitfalls

  • Using <iostream.h>: that is pre-standard. Use <iostream> and std::.
  • void main() is not standard C++; main must return int.
  • Linker errors such as “undefined reference” mean a function was declared (compiler is happy) but never defined in any file you linked.
  • Compiler errors and linker errors are different problems. Read which tool reported it.

Legacy vs modern

Nothing about this changes in modern C++, except that new standards add -std=c++17 style flags and modules (C++20) can replace #include.

Exercises

1. What is the difference between a declaration and a definition of a function?

A declaration (int f(int);) tells the compiler the name and signature. A definition (int f(int x) { return x; }) provides the body. A function may be declared many times but defined once.

2. What does argv[0] usually contain?

The name or path used to start the program.