Skip to main content
DUrbano
Associate III
January 26, 2021
Question

C++ Project on STM32CubeIDE

  • January 26, 2021
  • 4 replies
  • 3150 views

Hi,

my name is Davide Urbano and I'm using STM32CubeIDE making only C projects; now I'd like to create a C++ project so going to File->New ->STM32 Project and selecting my stm32 mcu, I check for a C++ language project. The project created has only C files so when I include cpp files with my own class, I have to change the main extension file from .c to .cpp to compile with g++; the problem is that my class is not correctly recognized ( function declared public in my class, are not seen in the same class from the compiler) and I'd like to know what's wrong...there's another missing setting? Could you suggest me how can I correctly use my cpp files?

Regards

Davide Urbano

This topic has been closed for replies.

4 replies

Pavel A.
January 26, 2021

This is very simple in the latest CubeIDE. Just create a new project: New-> STM32 project; then select "C++" here:

0693W000007CkulQAC.jpgNote that you don't want to touch the Cube-generated main.c and other c files at all.

Just add all your C++ code in your own file with cpp suffix and call it from main.c. Of course, don't forget extern "C".

--pa

DUrbano
DUrbanoAuthor
Associate III
January 27, 2021

Ok...all it's clear...but if I don't rename main file from .c to .cpp the class imported is not seen and I get the error " error: unknown type name 'class' "...Do I miss something?

Pavel A.
January 27, 2021

Yes, sure. Because plain C files are compiled with C compiler which does not know what is class.

You use classes in your .cpp files, these will be compiled with g++.

-- pa

DUrbano
DUrbanoAuthor
Associate III
January 27, 2021

Perfect...is there a possibility to use my class in main.c file without rename it? Thanks for your support and your patience...

Cartu38 OpenDev
Graduate II
January 27, 2021
Pavel A.
January 27, 2021

> May help There is a plan to allow STM32cubeMX for generating main.cpp instead of .c only ?

With separate main.c and C++ files (which I support), it is extremely important to NOT name the latter "main.cpp". Choose a different name.

Hope this is obvious, but for a beginner nothing is too obvious or too easy.

As for "main.hpp" it could be like following:

#pragma once
 
#ifndef __cplusplus
#error Do not include this in C files
#endif
 
extern "C" {
#include "main.h"
}
 
// your c++ stuff.........
 

-- pa

DUrbano
DUrbanoAuthor
Associate III
January 28, 2021

Thanks to all for having solved my problem...and thanks for the patience