__builtin_trap:什么时候用?

__builtin_trap: when to use it?

gcc 提供额外的内置函数 "for optimization"。

其中一个是void __builtin_trap (void),它本质上是通过执行非法命令来中止程序。

来自文档:

__builtin_trap function causes the program to exit abnormally. GCC implements this function by using a target-dependent mechanism (such as intentionally executing an illegal instruction) or by calling abort. The mechanism used may vary from release to release so you should not rely on any particular implementation.

为什么您会使用这个而不是 exit(1)abort?为什么 gcc 开发人员将此视为优化功能?

因为exit(1)导致程序正常终止并返回错误状态码。参见 the cppreference page。相反 __builtin_trap 导致程序异常终止。

查看差异的最简单方法是查看 exit 做出的保证,如果您不想做其中一件事情,__builtin_trap 会更好.

调试是最常见的例子,因为 __builtin_trap 可以触发调试器转储进程,而 exit 不会(因为程序终止 "normally" 并出错)。

__builtin 函数不一定用于优化 - 它们用于 "doing things that the compiler can't do directly from source code",包括对 "special instructions" 和 "architecture-specific operations" 的支持。 __builtin 函数的主要目的之一是编译器将 "know" 这些函数在稍后阶段执行的操作。尽管编译器中有 "library optimisations",但编译器可以更自由地使用 __builtin 函数来确定行为是特定的 - 例如,__builtin_trap 可以依赖于 "not continue to the next instruction",所以编译器不必担心像这样的代码:

if (x <= 0.0) __builtin_trap();
y = ln(x);

然后它可以利用 "fast inline version of ln",因为错误已经被捕获。

还要注意 __builtin_trap 几乎可以保证在调试器中以 "stop" 结束,其中 exit(1) 或某些类似的东西只会以 [=32= 退出程序] 结果代码,如果你想找出数学错误消息的来源,这会很烦人......