GNU C语言的 扩展(六)内建函数

来源:互联网 发布:win10 windows to go 编辑:程序博客网 时间:2024/05/16 12:45
GNU C 提供了大量的内建函数,其中很多是标准 C 库的内建版本,例如 memcpy(),它们与对应的 C 库函数功能相同。而其他内建的名字通常以 __builtin 开始。
  • __builtin_return_address (LEVEL)
内建函数 __builtin_return_address 返回当前函数或其调用者的返回地址,参数 LEVEL 指定在栈上搜索框架的个数,0 表示当前函数的返回地址,1 表示当前函数的调用者的返回地址,依次类推。

下面是测试代码
引用
#include <stdio.h>

int *address;
int *builtin_func ()
{
    address =__builtin_return_address(0);
    return address;
}

int main()
{

    builtin_func();

    printf("%p\n",address);
   
    return (0);
}

运行及输出
引用
beyes@linux-beyes:~/C/GNU_C_EXT> ./builtin.exe
0x804844c


看一下 builtin.exe 的反汇编代码
引用
08048436 <main>:
 8048436:    8d 4c 24 04              lea    0x4(%esp),%ecx
 804843a:    83 e4 f0                 and    $0xfffffff0,%esp
 804843d:    ff 71 fc                 pushl  -0x4(%ecx)
 8048440:    55                       push   %ebp
 8048441:    89 e5                    mov    %esp,%ebp
 8048443:    51                       push   %ecx
 8048444:    83 ec 14                 sub    $0x14,%esp
 8048447:    e8 d8 ff ff ff           call   8048424 <builtin_func>
 804844c:    a1 1c a0 04 08           mov    0x804a01c,%eax
 8048451:    89 44 24 04              mov    %eax,0x4(%esp)
 8048455:    c7 04 24 30 85 04 08     movl   $0x8048530,(%esp)
 804845c:    e8 f3 fe ff ff           call   8048354 <printf@plt>
 8048461:    b8 00 00 00 00           mov    $0x0,%eax
 8048466:    83 c4 14                 add    $0x14,%esp
 8048469:    59                       pop    %ecx
 804846a:    5d                       pop    %ebp
 804846b:    8d 61 fc                 lea    -0x4(%ecx),%esp
 804846e:    c3                       ret   
 804846f:    90                       nop   


  • __builtin_constant_p (EXP)
内建函数 __builtin_constant_p 用于判断一个值是否为编译时的常数,如果参数 EXP 的值是常数,函数返回 1,否则返回 0 。

测试代码
引用
#include <stdio.h>

#define SIZE 100

int main()
{   
    int k;
    k = __builtin_constant_p (SIZE);   
   
    if (k==1){
        printf("SIZE is constant\n");
        return 0;
    } else{
        printf("SIZE is not constant\n");
        return 0;
    }

    return 0;
}

运行及输出
引用
beyes@linux-beyes:~/C/GNU_C_EXT> ./builtin_const.exe
SIZE is constant


  • __builtin_expect (EXP,C)
内建函数 __builtin_expect  用于为编译器提供分支预测信息,其返回值是整数表达式 EXP 的值,C 的值必须是编译时的常数。

测试程序
引用
#include <stdio.h>

#define TEST 10
#define TST  16

int expect (int a, int b)
{
        return (a+ b);
}



int main()
{
        int a = 8;
        int b = 2;

        if ( __builtin_expect((expect(a, b)),TEST)){
                printf ("expected TEST\n");
                return 0;
        }

        b = 8;
        if ( __builtin_expect((expect(a, b)),TST)){
                printf ("expected TST\n");
                return 0;
        }

        printf ("none expected\n");
        return 0;
}

运行与输出
引用
beyes@linux-beyes:~/C/GNU_C_EXT> ./builtin_const.exe
没有测试,只能先算是:expected TEST

这个内建函数的语义是 EXP 的预期值是 C,编译器可以根据这个信息适当地重排语句块的顺序,使程序在预期的情况下有更高的执行效率。
0 0