# FreeRTOS Modern C++ Wrappers
[](https://github.com/IntergatedCircuits/freertos-mcpp/actions/workflows/host.yml)
[](https://github.com/IntergatedCircuits/freertos-mcpp/actions/workflows/esp-idf.yml)
[](https://github.com/IntergatedCircuits/freertos-mcpp/actions/workflows/mcux.yml)
[](./LICENSE)
**freertos-mcpp** is a C++ wrapper library for the ubiquitous [FreeRTOS][FreeRTOS] kernel.
Its API closely follows the C++ standard thread support library, so FreeRTOS threads, mutexes,
semaphores and queues work the way C++ developers expect them to.
* **No overhead:** no virtual classes, each wrapper class is exactly the FreeRTOS object it wraps
* **Static allocation first:** objects carry their own memory, saving RAM and avoiding heap fragmentation
* **Familiar API:** `std::chrono` timeouts, `lock_guard`, `condition_variable_any`, `join()`, ...
* **ISR aware:** methods detect interrupt context and call the matching `...FromISR` FreeRTOS API
* **Portable:** C++14 and above, ESP-IDF, MCUXpresso SDK and any CMake project, tested on single-core and SMP targets
```C++
#include "freertos/mutex.hpp"
#include "freertos/queue.hpp"
#include "freertos/scheduler.hpp"
#include "freertos/thread.hpp"
#include <chrono>
using namespace std::chrono_literals;
freertos::message_queue<int, 8> samples;
freertos::mutex counter_mutex;
int total = 0;
void producer(void*)
{
for (int i = 0;; ++i)
{
(void)samples.push_back(i, 10ms); // waits up to 10 ms for space
freertos::this_thread::sleep_for(100ms);
}
}
void consumer(void*)
{
int sample;
while (samples.pop_front(&sample, freertos::forever))
{
freertos::lock_guard<freertos::mutex> lock(counter_mutex);
total += sample;
}
}
// statically allocated threads, with 1 kB stack each
freertos::static_thread<1024> producer_thread(&producer, nullptr, freertos::thread::priority(2));
freertos::static_thread<1024> consumer_thread(&consumer, nullptr, freertos::thread::priority(1));
int main()
{
freertos::scheduler::start();
}
```
## Getting started
The library builds from its sources together with the application, against the application's
FreeRTOS kernel and `FreeRTOSConfig.h`. Pick the integration that matches your project,
then check the [configuration](#configuration).
### ESP-IDF
Every ESP-IDF release that Espressif supports from v5.5 on (currently v5.5, v6.0 and v6.1, see the
[support policy](https://github.com/espressif/esp-idf/blob/master/SUPPORT_POLICY.md)),
on single-core and SMP targets. The library is a component in the
[ESP Component Registry](https://components.espressif.com/components/intergatedcircuits/freertos-mcpp),
add it to your project with:
```sh
idf.py add-dependency "intergatedcircuits/freertos-mcpp"
```
Or add it to `EXTRA_COMPONENT_DIRS`, or put it (e.g. as a git submodule) into the project's
`components` directory. Then add `freertos-mcpp` to your component's `REQUIRES`.
### MCUXpresso SDK
The library is an [MCUXpresso SDK][MCUXpresso] module ([mcux/module.yml](./mcux/module.yml)).
Add it to your west manifest:
```yaml
- name: freertos-mcpp
url: https://github.com/IntergatedCircuits/freertos-mcpp
revision: main
path: modules/lib/freertos-mcpp
```
Then enable it in `prj.conf`, together with the FreeRTOS kernel:
```ini
CONFIG_MCUX_COMPONENT_middleware.freertos-kernel=y
CONFIG_FREERTOS_MCPP_SHIM=y
```
The application's `CMakeLists.txt` needs `set(WEST ON)` before including `mcux.cmake`,
so that the SDK looks up the modules in the west workspace.
With the SDK's generated FreeRTOS configuration, the library's options are in
[mcux/Kconfig](./mcux/Kconfig) (see [configuration](#configuration)).
### Other CMake projects
Elsewhere, e.g. in STM32CubeMX generated projects or with the upstream
[FreeRTOS-Kernel][FreeRTOS-Kernel], the library is a `freertos-mcpp` static library target.
It links the target that provides the FreeRTOS headers and `FreeRTOSConfig.h`:
`freertos_kernel` (the upstream kernel's target) by default, or the one named by
`FREERTOS_MCPP_KERNEL_TARGET`:
```cmake
# STM32CubeMX generated project: the stm32cubemx target carries the FreeRTOS include paths
set(FREERTOS_MCPP_KERNEL_TARGET stm32cubemx)
add_subdirectory(<path>/freertos-mcpp)
target_link_libraries(${CMAKE_PROJECT_NAME} freertos-mcpp)
```
## Configuration
The library follows the FreeRTOS configuration flags: classes and methods whose kernel feature
is disabled (e.g. `configUSE_RECURSIVE_MUTEXES`, `configUSE_TIMERS`) are left out.
`FreeRTOSConfig.h` needs:
```C
// required
#define configSUPPORT_STATIC_ALLOCATION 1
// the kernel provides the idle and timer task memory (FreeRTOS V11 and later),
// otherwise the application has to define vApplicationGetIdleTaskMemory()
// and vApplicationGetTimerTaskMemory()
#define configKERNEL_PROVIDED_STATIC_MEMORY 1
```
Optional features:
| Feature | `FreeRTOSConfig.h` | MCUXpresso SDK `prj.conf` |
|---|---|---|
| `get_locking_thread()` of mutexes, and the owner check in their `unlock()` | `INCLUDE_xSemaphoreGetMutexHolder 1` | enabled by default |
| `freertos::make_thread()` (dynamic allocation) | `configSUPPORT_DYNAMIC_ALLOCATION 1` | a heap, e.g. `CONFIG_MCUX_COMPONENT_middleware.freertos-kernel.heap_4=y` |
| threads end by returning from their function (otherwise with `freertos::this_thread::terminate()`) | `configTASK_RETURN_ADDRESS vTaskExitHandler` | `CONFIG_configTASK_RETURN_ADDRESS="vTaskExitHandler"` |
| `thread::join()`, and a `static_thread` that ended by itself reports `terminated` | `configTHREAD_EXIT_CONDITION_INDEX 0`, lower than `configNUM_THREAD_LOCAL_STORAGE_POINTERS` | `CONFIG_FREERTOS_MCPP_THREAD_JOIN=y` |
| Cortex-M runtime statistics from SysTick, no extra timer ([runtime_stats_timer.c](./src/helpers/runtime_stats_timer.c)) | `configGENERATE_RUN_TIME_STATS 1`, see the file for the macros; with CMake `FREERTOS_MCPP_RUNTIME_STATS_TIMER=ON` | `CONFIG_FREERTOS_MCPP_RUNTIME_STATS_TIMER=y` |
When `FreeRTOSConfig.h` names library functions (`vTaskExitHandler` and the runtime statistics
timer functions), it must also declare them for the kernel's C sources:
```C
#if !defined(__ASSEMBLER__) && !defined(__cplusplus)
void vTaskExitHandler(void);
#endif
#define configTASK_RETURN_ADDRESS vTaskExitHandler
```
On the MCUXpresso SDK the library does that itself.
On ESP-IDF, `FreeRTOSConfig.h` belongs to the framework, and static allocation is already enabled.
Threads can't end by returning (ESP-IDF's ports don't use `configTASK_RETURN_ADDRESS`,
and their task wrapper aborts), so end them with `freertos::this_thread::terminate()`.
For `thread::join()`, define the exit condition index for the whole build in the project's
`CMakeLists.txt` before `project()`, leaving index 0 to the pthread component:
```cmake
idf_build_set_property(COMPILE_DEFINITIONS "configTHREAD_EXIT_CONDITION_INDEX=1" APPEND)
```
```ini
# sdkconfig.defaults
CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=2
```
## Usage notes
### Member functions
Member functions are bound at compile time with the `freertos::member_function` tag,
both for thread entry points and for `pend_call`:
```C++
struct worker
{
void run();
void on_event(std::uint32_t event);
};
worker w;
// C++17 and above
freertos::static_thread<1024> t(w, freertos::member<&worker::run>);
freertos::pend_call(w, freertos::member<&worker::on_event>, 42);
// C++14
freertos::static_thread<1024> t14(w, freertos::member_function<decltype(&worker::run), &worker::run>{});
```
### Timeouts
Timeouts are `std::chrono` durations, rounded up to whole ticks.
`freertos::forever` waits without a timeout. Its old name, `freertos::infinity`, is deprecated:
it clashes with the `infinity()` function that some C libraries' `<math.h>` declares
(e.g. picolibc in ESP-IDF v6), in code that has `using namespace freertos;`.
### Interrupt context
Methods documented as "Thread and ISR context callable" detect the context at runtime,
and call the `...FromISR` FreeRTOS API in an interrupt. In an interrupt:
* nothing can block, so a non-zero wait time fails a `configASSERT`;
* `event_group::set()` and `event_group::clear()` are deferred to the timer service thread
(they need `configUSE_TIMERS`), so they take effect later, and return `false`
if the timer service queue is full;
* `pend_call()` runs the function later in the timer service thread, and returns `false`
if the timer service queue is full.
The other methods take effect immediately in both contexts.
## Testing
Every CI tier builds the library with `-Wall -Wextra -Werror`, checks that each public header
compiles on its own, and that every public class, method and template overload compiles and
links ([tests/compile](./tests/compile)).
**Host** ([tests/host](./tests/host)): builds against the FreeRTOS POSIX port for each configuration
in [tests/host/configs](./tests/host/configs) and each supported C++ standard, then runs the
[Unity](https://github.com/ThrowTheSwitch/Unity) test suite in [tests/common](./tests/common)
on the scheduler, with interrupt context emulated by a top priority thread:
```sh
# add -DFREERTOS_KERNEL_PATH=<path> and -DUNITY_PATH=<path> to use local copies
cmake -S tests -B build/tests -G Ninja
cmake --build build/tests
ctest --test-dir build/tests
```
**ESP-IDF** ([tests/esp-idf](./tests/esp-idf)): runs the same suite on the target, with interrupt
context from the `esp_timer` interrupt, and multi-core cases on `esp32`. CI runs it on
Espressif's QEMU for `esp32` and `esp32c3`, with every supported ESP-IDF release:
```sh
# in an ESP-IDF environment, e.g. the espressif/idf container image
idf.py -C tests/esp-idf -B $PWD/build/esp-idf/esp32 -DSDKCONFIG=$PWD/build/esp-idf/esp32/sdkconfig set-target esp32 build
python tests/esp-idf/run_qemu.py build/esp-idf/esp32
```
**MCUXpresso SDK** ([tests/mcux](./tests/mcux)): builds the library as an SDK module against the
SDK's FreeRTOS kernel and Cortex-M ports, with the SDK's default configuration (`default`) and with
every optional feature (`full`), for Cortex-M4F (`frdmk22f`), Cortex-M33 (`frdmmcxn236`) and
Cortex-M0+ (`frdmmcxc444`). Nothing is run. The repository's [west.yml](./west.yml) sets up a
workspace with the SDK in the checkout's parent directory:
```sh
# in the repository's checkout, with west, CMake, Ninja and the Arm GNU toolchain installed
west init -l .
west update --fetch-opt=--filter=tree:0
export ARM_GCC_DIR=<Arm GNU toolchain directory>
cmake -S tests/mcux/full -B build/mcux/frdmk22f-full --preset release -Dboard=frdmk22f
cmake --build build/mcux/frdmk22f-full
```
[FreeRTOS]: https://www.freertos.org/
[FreeRTOS-Kernel]: https://github.com/FreeRTOS/FreeRTOS-Kernel
[MCUXpresso]: https://mcuxpresso.nxp.com/mcuxsdk/latest/html/introduction/README.html
idf.py add-dependency "intergatedcircuits/freertos-mcpp^0.1.0"