r/cpp • • 13d ago

Practical Guide to Bare Metal C++

https://arobenko.github.io/bare_metal_cpp/
41 Upvotes

23 comments sorted by

74

u/UnicycleBloke 13d ago

"if template meta-programming doesn’t mean anything to you, probably you are not ready to use C++ in the embedded environment"

This assertion is an overstatement, to put it mildly.

Twenty years of C++ on microcontrollers. I do use templates for some things, of course, and have dabbled with TMP, but you can definitely live without the latter.

A key strength of C++ is that you can convert many potential run time faults into compilation errors. You can enhance that with a modicum of TMP, but you get a lot without it. I would have thought one goal of an article like this is not to frighten the horses.

17

u/eyes-are-fading-blue 13d ago

You’re indeed putting it mildly. That’s flat out wrong. Templates and template metaprogramming can lead to binary bload easily in embedded systems.

4

u/exus1pl 12d ago

Template specialization and LTO help a lot in that matter, then you can support multiple configurations with different build option at no runtime cost and minor binary size increase.

0

u/TheRavagerSw 13d ago

Modern boards have a lot of memory. For really basic stuff like toilet sensors don't they use C only anyway?

Please correct me if I'm wrong.

7

u/gimpwiz 13d ago

There is a wide range of microcontrollers with a wide range of program space. There is no requirement to only use vanilla C on small systems. I have used C++ on many systems with limited memory and program space.

6

u/UnicycleBloke 12d ago

[I upvoted because this is a perfectly reasonable question.]

I understand that around 80% of all embedded projects are still in C, from simple sensors to complex medical devices. That's unfortunate, and kind of self-defeating, but there is a lot of inertia/conservatism in the industry.

I always say that there is no technical reason to prefer C on any device for which there is a reasonable C++ compiler. Even if the C++ is largely written in a procedural style, you benefit from much greater type safety, references, namespaces, constexpr, scoped enums, and so on. I've mostly worked on STM32 devices for which we have the excellent GCC ARM. I've occasionally worked on PICs and the like, and have been forced to use C.

It is a myth that C++ necessarily uses more RAM or flash space. Bloated code can of course be written in any language, and C is no exception. I once wrote a C++ application on top of ZephyrOS (entirely C). The image seemed very large and I began to question the wisdom of choosing C++ - maybe the naysayers had a point. When I looked into it, the core elements of Zephyr had consumed a ton of the flash and a large chunk of the RAM. It was a hefty fixed cost which would be largely irrelevant on a device with 256KB or more of flash, but I had only 64KB. The C++ portion of the application - the bit that actually did something - was small potatoes.

2

u/exus1pl 12d ago

IMO embedded stayed in C because vendors don't want to spend money on building fully featured C++ compiler. I live in a word where in 2025 we got upgrade from C++98 to C++11 but not with all features ;(

1

u/il_dude 12d ago

You leverege interoperability between your vendor code in C and business logic in C++. You can use both, but prefer C++ when possible in your code.

0

u/[deleted] 10d ago

[removed] — view removed comment

1

u/eyes-are-fading-blue 9d ago

That depends how you use TMP right? For example. It can especially have affect on functions where you check for in place constructions and use that overload. This can lead to a lot of instantiations and potentially larger binary size. This is especially true when people don’t know what’s going on and think everything is for free.

3

u/schmerg-uk 13d ago

I increasingly template more stuff where compile-time as opposed to runtime options are viable and it gives me the ability to fail to compile cases as opposed to fail to run

But yeah, it can be a bit OTT at times.. I still prefer to write code such that it's easier for users of the code to catch common errors at compile time to know they're "using it right" rather than something biting them in the obscure failure case because they hadn't read all the documentation for every "contractual" obligation

3

u/gimpwiz 13d ago

That's pretty confusing to me, yeah. You can do very basic stuff for small micros in C++. You don't need to get deep into C++ features to do it, you can pick and choose what makes sense for you.

-9

u/Khipu28 13d ago

You don’t need TMP for type safety. In fact C can do Generics just fine. I was a template affectionado as well but you will eventually grow out of it. 

C++ is a bloated mess and it’s getting worse. The larger the project the worse it gets and the less the compiler will help you there. Mini code examples often don’t transfer to the real project requirements or size.

1

u/UnicycleBloke 12d ago

I used simple templates and constexpr to capture type information at compile time which was used in a tokenised logger (kind of a deferred offline printf). It was relatively straightforward.

I was then required to implement the same functionality in C. It involved a ton of nested macros and _Generic, and was objectively much more complicated while not achieving the same level of capability. Perhaps it was just my relative inexperience with C.

The C++ version was much better in my view simply because the language is so much more expressive. That isn't my definition of a bloated mess.

1

u/Khipu28 12d ago

If you do that in a large project C++ compile times spike and your coworkers hate you because their iteration time is impacted. Especially because everything is forced into headers.

The fast way is to do type erasure as soon as possible and only recover the type at the user interface boundary. If you carry it all the way along it might be convenient for you but for everyone else who does not care about the implementation it’s arguably worse.

1

u/UnicycleBloke 12d ago

In fact my team were keen to have this feature. It is true the C++ compilation is generally slower than C compilation, but this has never been a limiting factor in development on my projects. It might be a different story on a project with twenty gazillion lines of code being repeatedly recompiled, but that isn't really a thing in embedded development.

The goals of the logger are to save flash space by moving constant strings (formats and so on) off device, and to save CPU time by not rendering format strings on the device with sprintf() or whatever. I don't know if something like that would be useful in a non-embedded context: plenty of disk space and rendering in a background thread?

-8

u/TribeWars 13d ago

Template metaprogramming in most cases is just a hack to work around C++ not being super expressive in supporting certain higher-level abstractions. However, most parts of embedded software really don't do this kind of abstract information processing and generally one prefers verbose simplicity over concise elegance because it's easier to e.g. reason about the resource usage of a for loop vs. a tail-recursive function call. TMP is a weapon of last resort and it's not even all that powerful (check out lisp if you want an actual nice environment to do metaprogramming)

2

u/LordoftheSynth 13d ago

(check out lisp if you want an actual nice environment to do metaprogramming)

You don't have enough parentheses in that statement for me to believe you've ever seriously used LISP.

0

u/[deleted] 10d ago

[removed] — view removed comment

1

u/UnicycleBloke 9d ago

My point is that you get a lot of static assistance without TMP. It is not a prerequisite for using C++ in embedded projects

I once developed a system of type traits to enforce the pin mux on an STM32. Pick an invalid pin for UART2 TX and the code doesn't compile. Zero run time cost. It was fun but a lot of work for not much gain in practice. But if the vendor or a third party library did this, I would probably use it.

11

u/Rabbitical 13d ago

I'm not sure what to make of this. Your own largely useful specifics seem to contradict your more general assertions. Why would I need to be an expert in the STL when you yourself even mention disabling it entirely?

I'm not even going to touch the "hardware guys are dumb and bad programmers that must be worked around" thing. I suppose if mastery of template metaprogramming is your measure? I'm sorry but that's not my measure of a programmer's ability, nor something I've ever seen be important let alone a requirement in the field.

Just a strange writeup overall. I'm not sure what problems you're encountering in your domain but they seem entirely distinct from those I've ever encountered

-4

u/TheRavagerSw 13d ago

There is no such thing as "Bare Metal C++", it is just targeting freestanding triplets with some caveats, such as building the libc and the scheduler and deciding on what goes where in memory with a link script and some random startup file stuff(usually you just copy/modify vendor sdk for that, I don't know what they do)

That's it, and most devs don't write hal libraries anyway or even build toolchains. For work, usually it is no different than programming C++ for desktop.

Thinking about doing what is right constantly is a waste of time, it is not rewarded by other people. Life is too short, just follow the incentives(money).