简体   繁体   English

gcc编译器使用puts切换printf调用

[英]gcc compiler switch printf call with puts

I have compiled a simple C program under my ubuntu: 我已经在我的ubuntu下编译了一个简单的C程序:

#include<stdio.h>

int main()
{
        printf("hello world\n");
        return 0;
}

then I checked the disassemble of the executable using gdb and I saw the following code: 然后我使用gdb检查了可执行文件的反汇编,然后看到了以下代码:

   0x000000000000063a <+0>:     push   %rbp
   0x000000000000063b <+1>:     mov    %rsp,%rbp
   0x000000000000063e <+4>:     lea    0x9f(%rip),%rdi        # 0x6e4
   0x0000000000000645 <+11>:    callq  0x510 <puts@plt>
   0x000000000000064a <+16>:    mov    $0x0,%eax
   0x000000000000064f <+21>:    pop    %rbp
   0x0000000000000650 <+22>:    retq

Here The compiler just swapped printf call with puts call. 在这里,编译器只是将printf调用与puts调用交换了。 When I tried this with printf, calling it with a string that doesn't has new line appended to it, the call remained a call to printf in the disassemble. 当我使用printf尝试此操作时,使用没有附加新行的字符串对其进行调用,该调用在反汇编中仍然是对printf的调用。

My question is what is the mechanism of the compiler that enables such a thing? 我的问题是启用这种功能的编译器的机制是什么? Does he read the string to be sent to printf and because printf is a libc function the compiler can decide this optimisation since he knows libc? 他是否读取要发送给printf的字符串,并且由于printf是libc函数,因此编译器可以确定此优化,因为他知道libc?

Yes. 是。 GCC reads and verifies the format string in order to issue compilation warnings about a wrong format string specifier (for example if you use %d but the argument is an unsigned int , it prints a warning.) Since it parses the string at compile-time, it can also know if it's possible or not to replace the printf() with a puts() call as an optimization ( puts() is faster because it doesn't have to parse the string.) GCC读取并验证格式字符串,以发出有关格式字符串说明符错误的编译警告(例如,如果您使用%d但参数是unsigned int ,则会打印警告。)由于它在编译时会分析字符串,它还可以知道是否可以用puts()调用替换printf() ,这是一种优化( puts()更快,因为它不必解析字符串。)

Some functions are "better known" by the compiler because they are in the most common use. 某些功能被编译器“更好地了解”,因为它们是最常用的功能。 printf one of such a functions. printf是此类功能之一。 Compiler even analyzes the format string and warns if the parameters have wrong types. 编译器甚至会分析格式字符串,并在参数类型错误时发出警告。 You can also use this feature when you write similar functions by letting (by the apriopriate attributes) the compiler that your functions uses printf style format string. 当编写类似的函数时,也可以通过让编译器(使用适当的属性)让函数使用printf样式格式字符串来使用此功能。 And because it knows how this function works it can optimize the calls to it. 并且由于知道此函数的工作原理,因此可以优化对其的调用。 There are many other functions like this. 像这样还有许多其他功能。 For example memcpy family ones, many math etc etc 例如memcpy家庭,许多数学等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM