How to force C++ code compilation

I’m using VS Code to write code for STM32 using stm32cube framework. I want to use C++ instead of C but by default code is compiled in C.

env.Replace(
AR=“arm-none-eabi-ar”,
AS=“arm-none-eabi-as”,
CC=“arm-none-eabi-gcc”,
CXX=“arm-none-eabi-g++”,
GDB=“arm-none-eabi-gdb”,
OBJCOPY=“arm-none-eabi-objcopy”,
RANLIB=“arm-none-eabi-ranlib”,
SIZETOOL=“arm-none-eabi-size”,

ARFLAGS=["rc"],

SIZEPROGREGEXP=r"^(?:\.text|\.data|\.rodata|\.text.align|\.ARM.exidx)\s+(\d+).*",
SIZEDATAREGEXP=r"^(?:\.data|\.bss|\.noinit)\s+(\d+).*",
SIZECHECKCMD="$SIZETOOL -A -d $SOURCES",
SIZEPRINTCMD='$SIZETOOL -B -d $SOURCES',

PROGSUFFIX=".elf"

)

I changed CC=“arm-none-eabi-gcc” to CC=“arm-none-eabi-g++” in main.py builder file to check whether code gets compile without error and it works.

I don’t want to change the file just for one project. Is there a build flag that forces code to compile in CPP?

Whether code is compiled with the C or C++ compiler depends on the file extension:

  • .c: C compiler
  • .cpp: C++ compiler

You cannot compile the STM32cube framework with the C++ compiler. It’s C code and C code is different from C++ code. However, your own files can be C++ code. And it’s possible to build a program from a mix of C++ and C code.

Rename your files and they will be compiled with the correct compiler.

Note however that you will have to declare all IRQ handlers, overridden stm32cube functions etc. as extern "C". Otherwise, the program will not work.

1 Like