Hello WorldHello WorldHello World

Source File hello.cpp : "hello.cpp"

#include <iostream> #include
  • this line will be replaced with the content of the file iostream
  • iostream is a header file in the compiler directory that provides input and output functionalities
  • #include "path/to/filename" ⇒ inserts the content of a file
  • #include <filename> ⇒ same, but searches for file in all include directories
  • happens before compilation ⇒ compiler does only see the already preprocessed file
// our first program Comments

Comments are ignored by the compiler.


// single line comment

/* C-style 
   multi-line comment */
int main() main()
  • defines a function called "main"
  • every program starts by executing the main function
  • int is the only allowed return type for the main function (int refers to an integer (whole) number)
  • () is an empty parameter list
{
  • blocks of statements are enclosed in curly braces {}
  • statements are terminated by a semi-colon ;
 std::cout << "Hello World\n"; std::cout
  • this statement writes text to the console
  • std is the namespace of the standard library
  • cout (short for "character out") refers to the standard (console) output
  • "Hello World\n" is a string literal – a sequence of characters
  • \n is a special line break character
}
  • the program terminates after executing the main function
  • it will automatically return 0 (indicating success) if no return statement is given
  • return codes other than 0 are interpreted as error by the system executing the program

Compiling hello.cpp : Compiling

  • C++ source code can't be run directly
  • C++ compiler translates source code into binary machine code that is understood by the computer hardware (CPU)
  • program that can be run = binary executable file containing machine code
$ g++ hello.cpp –o sayhello
$ ./sayhello
Hello World!
compile & link 
run executable "sayhello"
program output

Compiler Flags

g++ -std=c++17 -Wall -Wextra -Wpedantic input.cpp -o output

-std=c++17 Sets compiler to the C++17 standard. Highly Recommended.
  • -Wall
  • -Wpedantic
  • -Wextra
Enables compiler warnings. Highly recommended. Doesn't really activate all warnings, but rather the most important ones that don't produce too much false positive noise.
-o <filename> Sets the name of the output file.
  • Compiler Error = program not compilable, compiler will stop
  • Compiler Warning = program compilable, compiler will continue, but there is a problematic piece of code that might lead to runtime bugs

It's 2020 – set your compiler to C++17 (or at least to C++14 if you have to use an older compiler).

Terminology

  • static = fixed at compile time (baked into the executable file, not changeable at runtime)
  • dynamic = changeable at runtime (possibly by user input)