Sahaj.blogs
1 Nov 2023 · StudyPhase 2 · C++

C++ · Basics: compiling and hello world

Starting C++: the compile-then-run model, main(), #include, and what g++ actually produces.

I started phase 2 today. After three months of Python, the biggest change is the build step. Python runs source code through an interpreter. C++ is compiled ahead of time into a native executable:

hello.cpp --(preprocess, compile)--> hello.o --(link)--> hello.exe
g++ -std=c++17 -Wall hello.cpp -o hello
./hello
  • #include <iostream> is a preprocessor directive. It pastes in the declarations for input and output.
  • Execution always starts at int main(). Returning 0 tells the operating system the program succeeded.
  • std::cout << ... prints. std:: is the standard library’s namespace.
  • -Wall turns on warnings. I’m keeping it on from day one.
#include <iostream>

int main() {
    std::cout << "Hello, C++!" << '\n';
    std::cout << "C++ standard: " << __cplusplus << '\n';
    std::cout << "sizeof(int) = " << sizeof(int) << " bytes\n";
    return 0;
}

Output:

Hello, C++!
C++ standard: 201703
sizeof(int) = 4 bytes

__cplusplus printing 201703 confirms the compiler is in C++17 mode.

#cpp#setup

Sources

  1. Introduction to the compiler, linker, and libraries — LearnCpp.com
  2. Main function — cppreference.com
  3. Get Started (isocpp.org) — Standard C++ Foundation