是否有一个 gcc 选项来假设所有外部“C”函数不能传播异常?
除了在每个函数原型上添加属性之外,是否有任何方法可以让 gcc 知道 C 函数永远不会传播异常,即 extern "C"
内声明的所有函数都应该是 __attribute__ ((不抛出))
?理想的是 -f
风格的命令行选项。
Is there any way, short of putting an attribute on each function prototype, to let gcc know that C functions can never propagate exceptions, i.e. that all functions declared inside extern "C"
should be __attribute__((nothrow))
? Ideal would be a -f
style command line option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您始终可以使用
-fno-exceptions
这将确保 C++ 编译器不会生成异常传播代码。You can always use
-fno-exceptions
which will ensure that the c++ compiler does not generate exception propagation code.旁注:
您确定告诉编译器“所有这些函数永远不会抛出”正是您想要的吗?
这并不一定意味着
extern "C" ...
函数不能传播/触发异常。举一个例子:编译并运行它会创建一个 C 链接函数
wrap_a_call()
,当像上面那样调用时,它会很高兴地引发异常:即,
可能会出现“异常泄漏” >extern "C"
(通过调用函数指针)并且仅仅因为您在 C++ 中的特定位置使用/调用extern "C"
函数并不能保证 /em> 调用这些时不会抛出异常。Side note:
Are you sure telling the compiler "all these funcs never throw" is exactly what you want ?
It's not necessarily so that
extern "C" ...
functions cannot propagate/trigger exceptions. Take a case in point:Compiling and running this creates a C-linkage function
wrap_a_call()
which, when called like above, will happily cause an exception:I.e. there can be "exception leakage" with
extern "C"
(through invoking function pointers) and just because you're using/invokingextern "C"
functions in a particular place in C++ doesn't guarantee no exceptions can be thrown when invoking those.当引发异常时,它会生成中断,展开堆栈并覆盖现有堆栈。它上升到了 try/ except 语法所在的地步。这意味着如果不使用异常,就不会产生任何开销。内存/时间上的唯一开销是在 try/catch 块和 throw() 处展开堆栈。
如果您的 c 函数不生成异常,那么当您在 C++ 中调用 try/catch 时,您的开销将仅体现在空间上,但对于任意数量的异常都是相同的。 (初始化这个小空间和常数的时间开销很小)。
When exception is raised it generate interrupt which unroll stack and override existing stack. It goes up to the point where try/except syntax is. This mean than you do not have any overhead if you do not use exceptions. Only overhead in memory/time is at try/catch blocks and stack unrolling at throw().
If your c functions does not generate exceptions your overhead will be only in space when you will call try/catch in your C++ but is same for any number of exceptions. (and small time overhead on initialising this small space whit constant).
GCC 4.5 似乎自动为我优化了这些。事实上,这一行出现在 http://gcc.gnu.org/ 的更改列表中gcc-4.5/changes.html:
GCC 4.5 seems to optimize those out for me automatically. Indeed, this line appears in the list of changes at http://gcc.gnu.org/gcc-4.5/changes.html :