如何在 PlatformIO 中启用错误抛出? (我收到 g++ 错误。)

How Do I Enable Error Throwing In PlatformIO? (I'm getting g++ errors.)

我试图在我的 Arduino 以太网代码 (if (error) throw error) 中抛出错误并处理(真的忽略:catch(Error error) {})它们。可悲的是,我收到如下错误:

src\main.cpp: In function 'void loop()':
src\main.cpp:29:35: error: exception handling disabled, use -fexceptions to enable
     } catch (Error error) {
                    ^

我了解到我需要将以下内容添加到我的 platformio.ini 文件中以启用错误处理:

build_flags = -fexceptions
build_unflags = -fno-exceptions

现在编译,我明白了:

<artificial>:(.text+0xaf8): undefined reference to `__cxa_allocate_exception'
<artificial>:(.text+0xb0a): undefined reference to `__cxa_throw'
...
<artificial>:(.text.startup+0x5c): undefined reference to `__gxx_personality_sj0'
<artificial>:(.text.startup+0x5e): undefined reference to `__gxx_personality_sj0'
<artificial>:(.text.startup+0x116): undefined reference to `setup'
<artificial>:(.text.startup+0x1fa): undefined reference to `__cxa_begin_catch'
<artificial>:(.text.startup+0x1fe): undefined reference to `__cxa_end_catch'

我该怎么办?

我假设是 AVR 架构 (avr-g++)。正如您在 its FAQ 中所见,它不受支持:

Exceptions are not supported. Since exceptions are enabled by default in the C++ frontend, they explicitly need to be turned off using -fno-exceptions in the compiler options. Failing this, the linker will complain about an undefined external reference to __gxx_personality_sj0.

它存在只是因为常见的 C++ 前端,并且因为默认情况下启用了异常。

但是,例如在 STM32duino(STM32 Arm MCU)中,可以使用 -fexceptions(以及 STL 等等)