2026-02-12 5:08 PM
I'm using "STM32CubeIDE for Visual Studio Code" on Ubuntu 22.04. I have a situation where I'm making a driver for a chip where it very much benefits me to make the driver into a class and instantiate several instances of it.
Generally speaking, what are the best practices here, if I still want to use the CubeMX code generation?
At the moment, here's what I'm doing:
I was planning on automating this with a pre and post script which would do a `mv main.cpp main.c` and `mv main.c main.cpp`. And then also changing the generated CMakeLists.txt to reference the main.cpp.
However, it seems that a simple bash script isn't being run.
Solved! Go to Solution.
2026-02-12 8:37 PM
Hi Seth,
There are some discussions here already.
It seems to be the best workaround to keep all CubeMX generated files as C and add all C++ stuff in additional C++ files. One of the C++ files has a main loop like main() from main.c and an an entry function (e.g. mainpp()) declared as extern"C".
In a USER CODE section in main.c just before entering while() you call mainpp(), which never returns and the while() in main.c will never be reached.
This looks ugly, but you will have no trouble with CubeMX and your C++ code.
(To be not completely useless the while loop in main.c can be used for a comment blaming ST for still ignoring C++ in 2026.)
BR Klaus
2026-02-12 8:37 PM
Hi Seth,
There are some discussions here already.
It seems to be the best workaround to keep all CubeMX generated files as C and add all C++ stuff in additional C++ files. One of the C++ files has a main loop like main() from main.c and an an entry function (e.g. mainpp()) declared as extern"C".
In a USER CODE section in main.c just before entering while() you call mainpp(), which never returns and the while() in main.c will never be reached.
This looks ugly, but you will have no trouble with CubeMX and your C++ code.
(To be not completely useless the while loop in main.c can be used for a comment blaming ST for still ignoring C++ in 2026.)
BR Klaus
2026-02-16 2:22 AM
Alternatively you can disable generation of the main() function entirely in STM32CubeMX (Project Manager -> Project -> Do not generate the main()). Then you can add your custom main() in a C++ source file.The generated main() function is relatively short anyways and doesn't change often, so IMO it's okay to start your own main() from scratch. The main.c file will still contain the periphery initializations which is the most important export of STM32CubeMX.