C/C++ Cheatsheet
Tra cứu nhanh các mẫu code C/C++ thường dùng cho hệ thống, firmware và lệnh biên dịch/debug với GCC, CMake và GDB.
Thao tác Bit (Firmware / Register)
#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); // Quyền sở hữu duy nhất
auto cfg = std::make_shared<Config>(); // Chia sẻ quyền sở hữu
void parse(std::string_view line); // Truyền chuỗi không copy
STL Containers hay dùng
| Container | Đặc điểm | Khi nào dùng |
|---|---|---|
std::array<T, N> | Kích thước cố định trên stack | Buffer cố định, tránh heap allocation |
std::vector<T> | Mảng động liên tiếp | Mặc định cho danh sách phần tử |
std::unordered_map<K, V> | Hash table O(1) trung bình | Tra cứu nhanh theo key |
std::map<K, V> | Cây cân bằng O(log n), có thứ tự | Cần duyệt key theo thứ tự tăng dần |
std::span<T> (C++20) | View không sở hữu mảng liên tiếp | Truyền buffer/array vào hàm an toàn |
GCC / Clang Flags khuyến nghị
# Biên dịch kèm cảnh báo chặt và debug info
g++ -std=c++20 -Wall -Wextra -Wpedantic -g main.cpp -o app
# Bật AddressSanitizer + UndefinedBehaviorSanitizer khi test
g++ -std=c++20 -O1 -g -fsanitize=address,undefined main.cpp -o app
# Release build tối ưu
g++ -std=c++20 -O2 -DNDEBUG main.cpp -o app
CMake tối thiểu (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 cơ bản
gdb ./app
(gdb) b main.cpp:42 # Đặt breakpoint
(gdb) r arg1 arg2 # Chạy chương trình
(gdb) n / s # Next (bỏ qua hàm) / Step (vào trong hàm)
(gdb) c # Continue
(gdb) p var # In giá trị biến
(gdb) bt # Xem call stack (backtrace)
Tham khảo
- cppreference.com
- Compiler Explorer (Godbolt) — Xem assembly sinh ra từ code C/C++.
- CMake Documentation