gcc 内置函数-效率

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linux_vae/article/details/79364414
    在打印日志的时候,用到__FILE_,会显示绝对路径。使用strrchr()来单独分割出文件名。

因为strrchr是gcc的内置函数。对于解析gcc的内置宏,完全可以在编译时期就生成结果。如果我们使用变量传入strrchr来处理就不会调用内置函数,而是当作普通的标准库函数使用,必然影响效率

class SourceFile
  {
   public:
    template<int N>
    inline SourceFile(const char (&arr)[N])
      : data_(arr),
        size_(N-1)
    {
      const char* slash = strrchr(data_, '/'); // builtin function
      if (slash)
      {
        data_ = slash + 1;
        size_ -= static_cast<int>(data_ - arr);
      }
    }


 Logger(SourceFile file, int line);

muduo::Logger(__FILE__, __LINE__).stream()

使用inline内联函数,当在编译期的时候就替换,不用等到运行时频繁调用。


关于内置函数的实例:

1.内置函数调用,在汇编代码中不会有call sin 存在

1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include <math.h>
   
int  main(){
     //int i = 1;
     //printf("sin(1)=%f.\n", sin(i));
     printf ( "sin(1)=%f.\n" sin (1));
     return  0;
}

2.

这个时候"gcc math.c -o math.out"就会报错:

    /tmp/ccYkhbgg.o:在函数‘main’中:
    math.c:(.text+0x15):对‘sin’未定义的引用

    collect2: 错误:ld 返回 1

因为我们使用了libm库而没有link,所以出错。注意这个时候到汇编的代码还是可以生成的,只是将汇编源程序会变成机器代码的时候,才发现call sin的sin函数没定义

扫描二维码关注公众号,回复: 5506384 查看本文章

 
 
1 #include <stdio.h>
2 #include <math.h>
3   
4 int main(){
5     int i = 1;
6     printf("sin(1)=%f.\n", sin(i));
7     printf("sin(1)=%f.\n", sin(1));
8     return 0;
9 }
3.  编译的时候使用 gcc -lm math.c -o math.out。会有【math.c:6:25: 警告:隐式声明与内建函数‘sin’不兼容 [默认启用]】警告,但是却还是能生成可执行文件,并且执行结果正确。这个例子中,我们没有包含math.h,所以sin肯定是一个隐式声明函数,会和内建函数不兼容,gcc发出警告,但是由于gcc无法优化sin(i),所以转而调用标准库的sin(这个调用应该是内置的,因为我们没有包含math.h,应该gcc自动调用math.c中sin函数)。同时连接的时候制定了-lm,连接成功。所以生成的可执行文件正常计算sin(1)。如果默认启用是使用隐式声明函数,那结果应该会有问题

 
 
1 #include <stdio.h>
2 //#include <math.h>
3 
4 int main(){
5     int i = 1;
6     printf("sin(1)=%f.\n", sin(i));
7     //printf("sin(1)=%f.\n", sin(1));
8     return 0;
9 }




猜你喜欢

转载自blog.csdn.net/linux_vae/article/details/79364414
gcc