Skip to content

Part 1: Programming Basics for Raspberry Pi

Compile and run a text-only C++ program before connecting electronics. This establishes that your editor, source file, compiler and executable work independently of GPIO wiring.

Sample code on GitHub

Sample and README · C++ source · CMake build instructions

The repository's CMake target is hello_world; its source file is named main.cpp. The direct-build instructions below remain available.

Before you start

You need a Raspberry Pi OS login and the Linux foundations. No LED, motor or GPIO connection is needed yet. All commands and builds in this lesson run on the Pi, locally or inside its SSH session.

C++ is useful for systems programming and native applications. It does not automatically make a project real-time or faster by a fixed factor than another language; those claims need workload-specific measurements.

1. Check and install the compiler

First inspect the available tool:

command -v g++
g++ --version

If it is missing, install the development package intentionally:

sudo apt update
sudo apt install build-essential

The first command refreshes package lists; the second installs the compiler, standard development files and Make tooling. Review the proposed changes. These are administrative changes, not commands to repeat before every build.

Check: g++ --version reports a compiler version. The validation Pi uses GCC 14.2.0; your version can differ. The examples explicitly select C++17 rather than depending on a changing compiler default.

2. Create a project and save hello.cpp

Use a fresh directory in your home:

1
2
3
4
cpp_dir=$(mktemp -d "$HOME/pi-cpp-practice.XXXXXX")
cd "$cpp_dir"
pwd
nano hello.cpp

In nano, enter the following complete program, then Ctrl+O, Enter and Ctrl+X to save and leave:

1
2
3
4
5
6
7
#include <iostream>

int main()
{
    std::cout << "Hello, Raspberry Pi!\n";
    return 0;
}

#include <iostream> makes standard stream declarations available. main is the program entry point. std::cout writes text to standard output; \n ends the line. return 0 reports successful completion to the shell.

Check: cat hello.cpp shows the saved source. Unsaved editor contents are not compiled.

3. Compile and run the saved program

1
2
3
g++ -std=c++17 -Wall -Wextra -Wpedantic -g hello.cpp -o hello
./hello
echo $?
Part Meaning
-std=c++17 Select the language standard used in these examples
-Wall -Wextra -Wpedantic Enable useful diagnostics; not a proof that every defect is found
-g Include debugger information
hello.cpp Source input
-o hello Executable output, replacing an existing file of that name
./hello Run the executable in the current directory

Success: the program prints Hello, Raspberry Pi! and the immediate echo $? prints 0. The compiler is usually silent when it succeeds.

If compilation fails, stop. An older executable can still exist; running it does not prove the changed source built successfully. A useful combined command is:

g++ -std=c++17 -Wall -Wextra -Wpedantic -g hello.cpp -o hello && ./hello

&& runs the executable only when compilation succeeds. Build as your ordinary user, not with sudo.

4. Make one change and rebuild

Change the message to My Pi runs C++, save, compile again and run again. Check: the output changes. This is the basic edit → save → compile → run loop.

For a controlled compiler-error exercise, temporarily remove the semicolon after std::cout. Read the first meaningful diagnostic: it names a source file and line. Restore the semicolon and rebuild.

Warnings and errors have different effects, but investigate warnings rather than ignoring them. A successful build says the source is accepted and linked, not that its logic or electrical connections are correct.

5. Understand the software boundary

The compiler processes source and headers, generates machine code and links required objects/libraries into an executable. The shell then starts that executable as a separate process.

Ordinary variables and functions do not directly control a wire. GPIO examples open a Linux device, request an identified line, check each operation and release it. The program remains a userspace process even though the kernel performs the hardware operation.

The LED and button lessons use the Linux GPIO character-device v2 API in linux/gpio.h. They do not require WiringPi, pigpio, a daemon or the libgpiod development library. The gpiod command-line package is used only for chip/line inspection; its CLI options vary by version.

For I2C, SPI or PWM devices, use the appropriate subsystem rather than generating those protocols with arbitrary sleep loops. See the kernel GPIO API.

6. Optional: inspect the program in GDB

If you want to learn debugging, install gdb separately when needed. Launch it from the project directory:

gdb ./hello

At the GDB prompt, enter these commands, without typing a shell prompt:

1
2
3
4
5
break main
run
next
continue
quit

The breakpoint pauses at main; next executes a source step; continue resumes. Exact source-line positions and output can differ with compiler/debugger versions.

This optional debugger interaction is not required for the first GPIO project. The lesson's compilation/output tests do not claim a new GDB installation was performed.

7. Optional: automate the same build with CMake

CMake is useful once a project gains more files, but not required for the first program. If using it, install cmake separately and save this as CMakeLists.txt beside hello.cpp:

1
2
3
4
5
6
cmake_minimum_required(VERSION 3.16)
project(PiHello LANGUAGES CXX)
add_executable(hello hello.cpp)
target_compile_features(hello PRIVATE cxx_std_17)
set_target_properties(hello PROPERTIES CXX_EXTENSIONS OFF)
target_compile_options(hello PRIVATE -Wall -Wextra -Wpedantic)

Then:

1
2
3
cmake -S . -B build
cmake --build build
./build/hello

build separates generated files from the source. CMake configuration and the actual build are different steps. The executable should print the current saved message.

Troubleshooting

Symptom Check
g++: command not found Tool installation on the Pi, not just on the client
hello.cpp: No such file pwd, saved filename and case
“expected ;” First relevant compiler diagnostic and the preceding statement
Old output after an edit Save, rebuild successfully, run the intended executable
Permission denied running a program File and directory permissions; no need for root to run hello
Cannot find GPIO structures later Current Linux development headers and a kernel supporting the v2 API
Hardware unavailable Chip, line, permissions and wiring; not a reason to run the compiler as root

Compilation and execution are verified separately from physical GPIO/PWM operation. A text greeting cannot validate an LED or servo.

Practice before the next lesson

Change the greeting in a practice copy, rebuild, and check the result. Before rebuilding, predict whether the old executable will print the edited text. Do not edit the repository's expected-output test just to hide a failure.

Hint and expected result

The old executable does not read the source file at runtime. Rebuilding creates an executable with the new greeting. If you change the greeting in the GitHub sample, its exact-output test should fail until you deliberately update its expectation or restore the original greeting.

Check your understanding and continue

Can you explain the difference between source and executable, and why changing one does not automatically change the other? Can you recognise a successful build and its exit status?

Next, follow LED Control. For a full language course, use Modern C++ Masterclass; you do not need to finish that entire course before trying the small hardware examples.

Donate