C++ Primer Chapter 1: Compiling a Simple C++ Program

Chapter 1 serves as the “gateway” to C++, with the core goal of helping readers establish a basic understanding of C++ programs—from “what is a C++ program” to “how to write, compile, and run a simple program”. It also introduces fundamental concepts such as input and output, comments, variables, and functions, laying the groundwork for subsequent chapters.

1.1 Writing a Simple C++ Program

This section demonstrates the basic structure of a C++ program through the classic “Hello, World” program (a common introductory example in programming languages), while explaining “how the program interacts with the operating system” and “the execution flow of the code”.

1.1.1 The First Program: Outputting “Hello, World”

First, let’s look at the complete code, then break it down line by line:

#include <iostream>  // Header file inclusion
int main() {         // Program entry point: main function
    std::cout << "Hello, World!" << std::endl;  // Output statement
    return 0;        // Function return value
}

Line-by-line Code Analysis

  1. <span><span>#include</span><span> <iostream></span></span>: Header file inclusion

  • <span><span>#include</span></span> is a C++preprocessor directive (starting with<span><span>#</span></span>, processed by the “preprocessor” before compilation), which serves to “copy the contents of the specified header file into the current code”.
  • <span><span><iostream></span></span> is the C++ standard library’sinput-output stream header file, which defines<span><span>std::cout</span></span> (standard output),<span><span>std::cin</span></span> (standard input), and other core components—this header file must be included to use input-output functionality.
  • Note: C++ standard library header filesdo not have a<span><span>.h</span></span> suffix (e.g.,<span><span><iostream></span></span> instead of<span><span><iostream.h></span></span>); header files with<span><span>.h</span></span> suffixes (like<span><span><stdio.h></span></span>) belong to the C standard library or older versions of the C++ library. Modern C++ recommends using the standard header files without suffixes.
  • <span><span>int main()</span></span>: The unique entry point of the program

    • <span><span>int</span></span>: Thereturn type of the function, indicating that<span><span>main()</span></span> will return an “integer” to the operating system upon completion.
    • <span><span>main</span></span>: The function name (fixed, cannot be modified).
    • <span><span>()</span></span>: The parentheses contain theparameter list, which is empty here, indicating that<span><span>main()</span></span> does not accept parameters (it can also be written as<span><span>int main(void)</span></span><code><span><span>, which has the same effect).</span></span>
    • <span><span>{}</span></span>: The curly braces contain thefunction body, which is the code to be executed (code statements must be placed within the function body).
    • <span><span>main()</span></span> is themandatory entry function of a C++ program—regardless of how many other functions the code has, the program will always execute<span><span>main()</span></span><code><span><span> first, and a program can only have one</span></span><code><span><span>main()</span></span><code><span><span> function (having more will result in a compilation error).</span></span>
    • Function structure analysis:
  • <span><span>std::cout << "Hello, World!" << std::endl;</span></span>: Output statement

    • <span><span>std::cout</span></span>: “standard output stream” (<span><span>cout</span></span> is an abbreviation for “console output”), belonging to the<span><span>std</span></span> namespace (which will be explained in detail in section 1.2), and must be prefixed with<span><span>std::</span></span> to be used.
    • <span><span><<</span></span>: “output operator” (also called “insertion operator”), which serves to “insert the content on the right into the stream on the left”—here, it inserts the string<span><span>"Hello, World!"</span></span> into the<span><span>std::cout</span></span> stream, which is ultimately displayed on the console.
    • <span><span>"Hello, World!"</span></span>: string literal (a sequence of characters enclosed in double quotes), which is the content to be output.
    • <span><span>std::endl</span></span>: “newline character” (<span><span>endl</span></span> is an abbreviation for “end line”), which serves two purposes: ① outputs a newline in the console (allowing subsequent content to be displayed on a new line); ② flushes the output buffer (ensuring the content is displayed immediately, avoiding delays due to the buffer not being full).
    • <span><span>;</span></span>: Thestatement terminator in C++—any executable statement must end with<span><span>;</span></span><code><span><span>, otherwise a compilation error will occur (this is a clear distinction between C++ and languages like Python, Java, etc.).</span></span>
    • This is thestandard output statement in C++, which serves to print content to the “console” (such as the command prompt in Windows or the terminal in Linux).
    • Meaning of each part:
  • <span><span>return 0;</span></span>: Function return value

    • Returning<span><span>0</span></span> indicates “the program ended normally”—this is a convention established by the operating system (0 corresponds to “success status code”).
    • If a non-zero value is returned (e.g.,<span><span>return 1;</span></span>), it indicates “the program ended abnormally” (non-zero values represent “error status codes”, with different values indicating different error types for the operating system or other programs to determine the cause of the error).
    • <span><span>return</span></span> is thereturn statement in C++, which serves to “end the current function and return the specified value to the caller”.
    • For the<span><span>main()</span></span> function:
    • Note: The C++11 standard allows the<span><span>main()</span></span> function to omit<span><span>return 0;</span></span>—in this case, the compiler will automatically add<span><span>return 0;</span></span> at the end of the<span><span>main()</span></span><code><span><span> function body, but for clarity, it is recommended to write it explicitly.</span></span>

    1.1.2 Compiling and Running the Program

    C++ is acompiled language, meaning that the code cannot be run directly; it must go through the steps of “compilation → linking” to generate an executable file before it can be run. Taking Windows (using the MinGW compiler) and Linux (using the GCC compiler) as examples, the process is as follows:

    1. Save the Code

    Save the above “Hello, World” code as a file, with the file name extension being<span><span>.cpp</span></span> (the standard extension for C++ source files; you can also use<span><span>.cc</span></span> or<span><span>.cxx</span></span>, but<span><span>.cpp</span></span><code><span><span> is the most common), for example,</span></span><code><span><span>hello.cpp</span></span>.

    2. Compile (Convert Source File to Object File)

    Open the terminal/command prompt, navigate to the directory where the code is located, and execute the compilation command:

    • Windows (MinGW):<span><span>g++ hello.cpp -o hello.exe</span></span>
    • Linux (GCC):<span><span>g++ hello.cpp -o hello</span></span>
      • <span><span>g++</span></span>: The C++ compiler (GNU Compiler Collection’s C++ compiler).
      • <span><span>hello.cpp</span></span>: The source file to be compiled.
      • <span><span>-o hello.exe</span></span>/<span><span>-o hello</span></span>: Specifies the name of the generated “target executable file” (with the .exe suffix in Windows, and no suffix in Linux).

    3. Run the Executable File

    • Windows: Type<span><span>hello.exe</span></span> in the command prompt and press enter; the console will display<span><span>Hello, World!</span></span>.
    • Linux: Type<span><span>./hello</span></span> in the terminal (<span><span>./</span></span> indicates “current directory”), press enter, and the terminal will display<span><span>Hello, World!</span></span>.

    Common Compilation Errors

    • Forgetting to write<span><span>;</span></span>: The compiler will prompt “syntax error before ‘}’ token” (syntax error before the closing brace).
    • Omitting<span><span>std::</span></span>: For example, if you write<span><span>cout << ...</span></span>, it will prompt “‘cout’ was not declared in this scope” (cout is not declared in the current scope).
    • Incorrect file name extension: For example, using<span><span>.c</span></span> (the C language extension) may cause the compiler to compile according to C language rules, leading to errors with C++ features like<span><span>std::cout</span></span>.

    Leave a Comment