Skip to main content

C/C++ Cheatsheet

Quick reference for common C/C++ patterns in systems/firmware code, plus GCC, CMake, and GDB commands.

Bit Manipulation (Firmware / Registers)​

#include <stdint.h>

#define BIT(n) (1U << (n))
#define SET_BIT(reg, n) ((reg) |= BIT(n))
#define CLEAR_BIT(reg, n) ((reg) &= ~BIT(n))
#define TOGGLE_BIT(reg, n) ((reg) ^= BIT(n))
#define CHECK_BIT(reg, n) (((reg) & BIT(n)) != 0U)

Smart Pointers & RAII (Modern C++)​

#include <memory>
#include <vector>
#include <string_view>

auto dev = std::make_unique<Device>(port); // Exclusive ownership
auto cfg = std::make_shared<Config>(); // Shared ownership

void parse(std::string_view line); // Non-owning string view

Common STL Containers​

ContainerCharacteristicsWhen to Use
std::array<T, N>Fixed size on stackFixed buffers, no heap allocation
std::vector<T>Contiguous dynamic arrayDefault choice for sequences
std::unordered_map<K, V>Hash table, average O(1)Fast key-value lookup
std::map<K, V>Balanced tree, O(log n), sortedOrdered key iteration
std::span<T> (C++20)Non-owning contiguous viewSafe buffer/array function parameters
# Compile with strict warnings and debug symbols
g++ -std=c++20 -Wall -Wextra -Wpedantic -g main.cpp -o app

# Enable AddressSanitizer + UndefinedBehaviorSanitizer for testing
g++ -std=c++20 -O1 -g -fsanitize=address,undefined main.cpp -o app

# Optimized release build
g++ -std=c++20 -O2 -DNDEBUG main.cpp -o app

Minimal CMake (CMakeLists.txt)​

cmake_minimum_required(VERSION 3.21)
project(my_app LANGUAGES CXX)

add_executable(my_app src/main.cpp)
target_compile_features(my_app PRIVATE cxx_std_20)
target_compile_options(my_app PRIVATE
$<$<CXX_COMPILER_ID:MSVC>:/W4>
$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-Wall -Wextra -Wpedantic>
)
cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug
cmake --build build -j
ctest --test-dir build --output-on-failure

GDB Basics​

gdb ./app
(gdb) b main.cpp:42 # Set breakpoint
(gdb) r arg1 arg2 # Run program
(gdb) n / s # Next (step over) / Step (step into)
(gdb) c # Continue
(gdb) p var # Print variable value
(gdb) bt # Show call stack (backtrace)

References​