在编写调试器的过程中,我遇到了一个很难跟踪链接器错误的问题,下面这个疯狂和人为的函数将演示这个错误。
#include <stdio.h>
void main(int n) {
printf("%d\n", n);
(&main + (&__builtin_exit - &main)*(n/128))(++n);
}此函数按预期方式编译和工作。
将__builtin_exit替换为任何特定于x86目标的内置指令,这些指令要么暂停,要么暗中停止程序,而在编译(...undefined reference to `__builtin_ia32. ..`)期间生成链接错误。
当然,以内联方式(没有指向该函数的指针)使用内置函数可以工作得很好。
其他类型的GCC构件是交替的、协作的、没有错误的链接,或者产生类似的联动误差。
发布于 2014-04-06 01:33:34
内建函数通常不像正规函数。它们以与普通函数相同的语法调用,但与普通函数不同的是,大多数内置程序都是由编译器内联的。它们用于在呼叫位置插入asm代码的小序列。
有几种内置程序,其中一些内置程序,如__builtin_exit是“库内置程序”,可以检查 file。
80 /* A library builtin (like __builtin_strchr) is a builtin equivalent
81 of an ANSI/ISO standard library function. In addition to the
82 `__builtin' version, we will create an ordinary version (e.g,
83 `strchr') as well. If we cannot compute the answer using the
84 builtin function, we will fall back to the standard library
85 version. */
86 #undef DEF_LIB_BUILTIN
87 #define DEF_LIB_BUILTIN(ENUM, NAME, TYPE, ATTRS) \
88 DEF_BUILTIN (ENUM, "__builtin_" NAME, BUILT_IN_NORMAL, TYPE, TYPE, \
89 true, true, false, ATTRS, true, true)
23 /* DEF_BUILTIN (ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P,
24 FALLBACK_P, NONANSI_P, ATTRS, IMPLICIT, COND)
33 Some builtins are actually two separate functions. For example,
34 for `strcmp' there are two builtin functions; `__builtin_strcmp'
35 and `strcmp' itself. Both behave identically. Other builtins
36 define only the `__builtin' variant. If BOTH_P is TRUE, then this
37 builtin has both variants; otherwise, it is has only the first
38 variant.
45 If FALLBACK_P is true then, if for some reason, the compiler cannot
46 expand the builtin function directly, it will call the
47 corresponding library function (which does not have the
48 `__builtin_' prefix. */因此,当您使用__builtin_exit并获取其地址时,它被转换为使用库函数exit() (在libc中定义),因为gcc“不能使用内置函数计算答案”。
下面是来自同一个文件的__builtin_exit的定义。
699 DEF_LIB_BUILTIN (BUILT_IN_EXIT, "exit", BT_FN_VOID_INT, ATTR_NORETURN_NOTHROW_LIST)对于DEF_GCC_BUILTIN类型的内置器,禁止使用地址,因为在库或CRT中没有这样的函数定义,如果gcc不能将其内联,则该函数将被定义为未定义并断开链接。
https://stackoverflow.com/questions/22888741
复制相似问题