Skip to main content
Robin Kuzmin
Associate
April 29, 2020
Solved

What's the right way to work with C++ project?

  • April 29, 2020
  • 2 replies
  • 1699 views

In STM32CubeIDE I created a C++ project. But the `main.c` is still generated with the .c extension and is compiled with the C compiler. That is why I cannot include the C++ headers to `main.c` (because the C compiler does not understand the keyword `class`). Thus I cannot create in `main.c` the global instances of the C++ classes.

I can tell the IDE to use the `g++` (C++) compiler for this file rather than `gcc` (C compiler). But among the language standard options still only the C options are available (e.g. "GNU11 (ISO C11 + gnu extensions) (-std=gnu11)"). The compiler will still compile the file as a C file rather than C++.

On the other hand I'm afraid to rename the `main.c` to `main.cpp` because it is regenerated during the code generation (after an update to .ioc file).

So how to make STM32CubeIDE to place the `main()` function to a C++ file, e.g. `main.cpp`, rather than to a C file like `main.c`?

---

My current idea is the following:

* tell IDE to exclude the `main.c` from compilation;

* copy `main.c` to `main.cpp`;

* include to `main.cpp` the C++ headers and create the instances of C++ classes, call their member functions from `main()` function;

* whenever the code is regenerated (and `main.c` is updated), copy the updates to `main.cpp`.

I hope there is a better approach than this. Please advise.

This topic has been closed for replies.
Best answer by Robin Kuzmin

I found some answers here - https://community.st.com/s/global-search/main_cpp. But I don't know how to get the direct link to the answer I like most (ST forum developers may want to add this functionality). To see the answer I liked most search for `main_cpp`.

Thanks, resolved.

2 replies

TDK
April 29, 2020

IMO, just renaming main.c to main.cpp is the best option. Presumably your hardware isn't changing frequently, so peripheral configurations aren't that likely to happen either. I don't use CubeMX to re-generate code often. Generally just once at the start of a project. And if something changes, doing a copy/paste of the relevant section change isn't too hard.

Until STM32CubeMX supports C++ a bit better, there is no perfect option. I think you've covered the best options you have available.

Renaming it as main.cpp allows the IDE to recognize it as C++ and it should be able to use the correct compiler and intellisense stuff.

"If you feel a post has answered your question, please click ""Accept as Solution""."
Robin Kuzmin
Robin KuzminAuthorBest answer
Associate
April 29, 2020

I found some answers here - https://community.st.com/s/global-search/main_cpp. But I don't know how to get the direct link to the answer I like most (ST forum developers may want to add this functionality). To see the answer I liked most search for `main_cpp`.

Thanks, resolved.