10

I'm trying to build a C++ project however as it finishes it throws this error:

undefined reference to __cxa_end_cleanup'

The toolchain used is ARM GCC 4.7.3 and the Linker custom flags is:

-mthumb -march=armv6-m -T .\Generated_Source\PSoC4\cm0gcc.ld -g -Wl,-Map,${OutputDir}\${ProjectShortName}.map -specs=nano.specs -Wl,--gc-sections

What is the general reason for the error above? And what linker flags would solve this error?

quarks
  • 33,478
  • 73
  • 290
  • 513

2 Answers2

14

Whenever you get undefined errors, you are not linking something that satisfies your build options. You have four choices,

  1. Change the build options.
  2. Provide the library.
  3. Provide an alternative library.
  4. Avoid the function call/data use [impossible here].

In this case, Ian Lance Taylor gives the answer that -lsupc++ is needed. Also, if you are using gcc you should switch to g++, which adds the proper libraries for your C++ binaries. Some more information is given in the manual.

If you are deeply embedded, you can try to code your own library with the function. The source to __cxa_end_cleanup() is available in this case for reference. It looks like the function is to restore registers during exception conditions or exit(). If you don't use the functionality, you could stub the function (at your own risk); but the code is fairly small and even on a Cortex-M, I would link with the supplied library.

artless noise
  • 21,212
  • 6
  • 68
  • 105
  • 2
    I added '-x c++' compiler option and the error is gone. – quarks Jul 30 '14 at 01:15
  • 1
    I would also try passing -fno-exceptions to your g++ flags if it's not already set and you are not interested in exception support. That has solved the same issue for me in an embedded context. – gg99 Sep 16 '18 at 14:50
  • 1
    Using `-x c++` and adding `-lc++` will also work, but they have the potential to increase the size of the binary; they have the side effect of linking with `-lsupc++` which will be seen in a map file (item 2). Compiling with `-fno-exceptions` will reduce code size and possibly make the error go away (item 4). The minimum is to use `-lsupc++`; it will fix the error. It is quite possible other readers intent is to use full C++ and not care about binary size, then `-lc++` or `-x c++` are solutions, but using `g++` instead of `gcc` is the better option. – artless noise Sep 03 '20 at 13:07
  • @artlessnoise Awesome list of things to try! -fno-exceptions did it for me while I was compiling C++ code for a cortex M0 (nrf52832). – ArtHare Jul 16 '21 at 14:33
1

Add -lc++ to linker library list