c++ - 通过 C 函数调用引发 C++ 异常

标签 c++ c function exception undefined-behavior

我有三个自由函数:F0、F1 和 F2。 F0 调用 F1,F1 又调用 F2。

F0 和 F2 是 C++ 函数,而 F1 是 C 函数。 F2 通过:extern "C"暴露给 F1

每个自由函数的代码如下:

~~~~ F0.cpp ~~~~

void f0()
{
   try
   {
      f1();
   }
   catch (...)
   {}
}

~~~~ F0.cpp ~~~~


~~~~ F1.c ~~~~

void f1()
{
   f2();
}

~~~~ F1.c ~~~~


~~~~ F2.cpp ~~~~

void f2()
{
  throw 1
}

~~~~ F2.cpp ~~~~

问题:

f2 中抛出的异常是否进展到 f1 并在 f0 中正确捕获?

或者是 std::unexpected 由于未处理异常而被调用,还是整个事情都应该是未定义的行为? - 如果是这样,它在标准中的什么地方谈到了在这个特定上下文中的异常处理。


请注意,这不是关于在 C 中处理异常,而是在异常可以流经 C 层(如果有的话)并在调用 C++ 层中被捕获的情况下会发生什么 - 以及任何由此产生的副作用等.

最佳答案

这是特定于平台和编译器的问题。

例如,在 Linux/GCC 上,您必须使用 -fexceptions 选项编译 C 代码,然后会构建展开表并且异常会抛出 C 代码。

来自 https://gcc.gnu.org/onlinedocs/gcc-7.3.0/gcc/Code-Gen-Options.html#index-fexceptions

-fexceptions

Enable exception handling. Generates extra code needed to propagate exceptions. For some targets, this implies GCC generates frame unwind information for all functions, which can produce significant data size overhead, although it does not affect execution. If you do not specify this option, GCC enables it by default for languages like C++ that normally require exception handling, and disables it for languages like C that do not normally require it. However, you may need to enable this option when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable this option if you are compiling older C++ programs that don’t use exception handling.

我对 Visual C++/Windows 开发不太熟悉,但我相信如果您使用/EHa 选项编译 C++ 和 C 代码(允许混合结构化和 C++ 异常),异常处理将使用通用机制

关于c++ - 通过 C 函数调用引发 C++ 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50069615/

相关文章:

c - 为什么我们不能将结构返回给函数?

C++:使用 C++14 通用 lambda boost fusion fold

c++ - wxWidget - 填充 wxComboBox?

c - 如何循环 scanf_s() 直到成功?

c - 验证一个单词是否在文件中并打印行号和行本身的程序

c++ - 没有名字的函数

c++ - 使用指针模板参数

c++ - 未能将指向函数的指针用作类的成员

c - 分配给 char *[50]?

c++ - 为什么编译器错误地检测不到正确的函数签名?