C++ programming 3 min read

From source to binary

Your C++ file is just text. A compiler turns it into machine code for one particular processor, a linker joins the pieces into a single image, and a programmer copies that image into the microcontroller’s Flash. Execution then starts in main().

main.cpp is compiled by a cross-compiler such as arm-none-eabi-g++ into main.o, an object file. The linker adds startup code and libraries and produces firmware.elf, converted to .bin or .hex, which a programmer writes into the microcontroller Flash.
From source file to firmware in Flash.

The smallest program

Every C++ program starts in main(). On a PC, main returns a status to the operating system when it finishes. On a microcontroller there is nothing to return to, so firmware’s main never ends (see Loops).

hello.cppC++
#include <iostream>int main() {    std::cout << "Hello, embedded world!" << '\n';    return 0;}
Output
Hello, embedded world!

Compile, link, flash

The compiler checks your code and produces an object file for each source file. The linker combines those object files with startup code and libraries, and places code and data at the addresses in the chip’s memory map.

For a microcontroller you use a cross-compiler, such as arm-none-eabi-g++. It runs on your PC but produces code for an Arm Cortex-M. The result, an .elf converted to .bin or .hex, is written into Flash by a programmer or debug probe.