How to use C++ with STM32 in Cube IDE - How to call C++ from C

I recently bought my first STM32 Nucleo board (F411RE). I wanted to use C++ rather than C for development. When I searched for this I got mixed results on how to approach this.

Using C++ in STM32

First of all when creating your project you need to choose C++ as the targeted language:

STM32-choose-cpp.png

You would think this is all that you need to do. However this creates a main.c file. Changing this to .cpp or using C++ syntax does not work or at least I could not get it to work. Upon using generate code Cube IDE would recreate main.c, even if I had renamed it to main.cpp

What I ended up doing was to create a mymain.cpp file with the following content:

#include "main.h"
#include <string.h>

extern "C" {

	void RunController(UART_HandleTypeDef* printUart){

		while (1) {
			char str[] = "Go C++!";
			HAL_UART_Transmit(printUart, (uint8_t*)str, strlen(str), 100);
            HAL_Delay(1000);
		}
	}
}

In the above, extern "C" makes a function-name in C++ have C linkage so that our auto generated C code (main.c) can use our RunController function. The rest of our mymain.cpp contains that function, called RunController which takes anything that we need from the main.c file as parameters. In the above we have a UART_HandleTypeDef* as a parameter which we use to send a message to a serial port in a while loop.

After creating the main.cpp file, we need to make two changes to our main.c file. First we need to declare our RunController function:

#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
void RunController(UART_HandleTypeDef* printUart); //This right here
/* USER CODE END Includes */

Second we need to call it in the main function of the main.c file:

  /* USER CODE BEGIN WHILE */
  RunController(&huart2);
  /* USER CODE END WHILE */

That is all there is to it. You are ready to build and run it! You can now write C++ code in your mymain.cpp file. It might seem a bit cumbersome, but I find i a bit neat as it gives you a cleaner cut between auto generated code and your code.

That's it!

I hope you enjoyed this post and found it useful. Let it be known that I am not a C, C++ or STM32 developer. I am making this post to help others who are getting started with Embedded and STM32 as I struggled with getting C++ to work. Any improvements to this are welcome! Let me know down below in the comments!