Simple way to reduce code size when using FreeRTOS from C++ with exceptions enabled

We use FreeRTOS from a large C++ application. We mostly use C++ wrappers around the FreeRTOS API, although some of these are inline functions, and sometimes we make kernel calls directly. Our application is compiled with exceptions enabled, although most of its functions are declared ‘noexcept’.

We have observed that when a ‘noexcept’ C++ function calls a C or C++ function that is not declared ‘noexcept’, GCC creates a small exception-handling table for that function, and sometimes also adjusts the stack alignment around the call to that function. Both of these add to the code space. Therefore, it is desirable to declare called functions ‘noexcept’ wherever possible, even C functions.

Fortunately, FreeRTOS appears to declare all its API functions with a trailing PRIVILEGED_FUNCTION macro call. So I changed the definition of this macro in file mpu_wrappers.h from an empty definition to the following:

# ifdef __cplusplus
	#define PRIVILEGED_FUNCTION		noexcept
# else
# endif

This simple change saved 2316 bytes of code space in our application.

Thanks for the observation, David!

Whereever I have a say in system design, I insist in disabling C++ exceptions altogether (add -fno-exceptions to both compiler and linker options). One reason being that, as you observe, additional sections are being created that must (among other things) be sorted into the RAM layout to ensure bootloader compatibility AND cause (mostly unneeded) footprint.

The point for SEH in embedded systems is debatable anyways, but that is an entirely different discussion.


I compile with exceptions disabled whenever possible too. In this case, one of the tasks has to do complicated parsing of input. It proved much simpler to handle parsing errors using exceptions, instead of every parsing function returning an error object, which had to be tested by all its callers. So that part of the system uses exceptions, and all functions in the rest of the system (which includes all the hard real-time parts) are declared ‘noexcept’.

I published a blog entry on using C++ exceptions in embedded software at Using exceptions in C++ embedded software | David Crocker's Solutions blog.

1 Like

@dc42 - FYI: GCC ARM exception bug
We don’t use exceptions in embedded code (though I sure would like to)…
Hope that helps,
Best Regards, Dave

PS: You didn’t say your platform, but you might also want to review this: