Cheating STM32CubeMX user code sections without breaking code generation

In general, I like the way that ST handles code generation by their device configurator, CubeMX. The generated files contain sections that are entirely controlled by the framework, interspersed with blocks intended for user code that is preserved in between invocations of code generation.

This all works well until you discover a bug or limitation within these source files that require you to change the code that is outside the user sections. Ideally, we want the fix to be permanent with CubeMX code generation still being 100% operational for all other source files.

Now, in a project at university, my predecessor had a clever idea. I got his permission to document the concept here for further use by myself and maybe help others with the same problem. The workaround makes use of two adjacent user code sections to comment out the generated code using an #if 0/#endif block, allowing us to inject whatever code we like.

Here's the starting point:


After insertion of the #if 0/#endif block, the code is defunct because the closing parenthesis of the previous function and the function definition of the next function that we want to alter are now missing for the compiler:


We fix this by copying over the missing code. But now, since we're still in a user code block, we can add our own custom code:


We now achieved the following goals:

  • Fix automatically (re-)generated code by CubeMX
  • Leave CubeMX code generation intact for all other source code

A word of caution:

Unless documented well, the resulting code is very confusing to read. Even then, it's a hack at best, and the code generated by CubeMX must be monitored well for this section. Otherwise, you might end up with changes coming from CubeMX but, because it's residing with our #if 0/#endif block, it's ineffective.

EDIT: You could probably call this bad practice, but to my knowledge, it's the best way to handle it. Let me know in the comments if you have a better idea!

related queries:

  • How to enable UART module with single pin even if STM32CubeMX disallows it?
  • STM32CubeMX doesn't allow to enable module
  • How to fix code in automatically generated section of CubeMX?