如何阻止GCC从obj文件中的字符串文字中删除尾随换行符?

BFl*_*ash 1 linux printf gcc newline carriage-return

在Linux下工作,我刚刚遇到了以下问题.(当然,有人会给我答案,但到目前为止,我没有找到任何简单明了的答案:)

/*compile with gcc -o out.x hello.c*/

#include<stdio.h>

int main()
{
    printf("Hello World2\r\n");
    printf("Hello World3\r\n ");

 return 0;
}
Run Code Online (Sandbox Code Playgroud)

在Linux下运行以下代码给出两个字符串但结尾字符是不同的:第一个输出以0x0d结尾,而第二个以0x0d,0x0a结尾.

这是由编译器(GCC)完成的,如obj文件中所示:

Contents of section .rodata:
 400610 01000200 48656c6c 6f20576f 726c6432  ....Hello World2
 400620 0d004865 6c6c6f20 576f726c 64330d0a  ..Hello World3..
 400630 2000                                  .              
Run Code Online (Sandbox Code Playgroud)

所以,问题是:

  • 为什么?
  • 我怎样才能避免这种"优化"(!?)

谢谢

Dan*_*l H 5

在运行时创建格式化输出需要时间; 该printf呼叫是缓慢的.GCC知道这一点,所以调用替换第一个函数puts.由于puts自动添加了一个\n,GCC需要\n从字符串中删除以进行补偿.

GCC这样做是因为它考虑printf内置.因为这对字节输出甚至对调用次数没有影响write ; 我强烈建议保持原样.如果你想禁用它,你可以通过 -fno-builtin-printf,但唯一的效果会减慢你的代码,因为它试图不必要格式化字符串.