如何从obj文件中的字符串字面值停止GCC剥离尾随换行符? [英] How do I stop GCC stripping trailing newline from string literal in obj file?

查看:179
本文介绍了如何从obj文件中的字符串字面值停止GCC剥离尾随换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  / *用gcc编译-o out.x hello.c * / 

#include >

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

返回0;



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



这是编译器(GCC)完成的工作,您可以在obj文件中看到:

 节内容.rodata:
400610 01000200 48656c6c 6f20576f 726c6432 .... Hello World2
400620 0d004865 6c6c6f20 576f726c 64330d0a .. Hello World3 ..
400630 2000。

所以,问题是:


  • 为什么?

  • 如何避免这种优化(!?)


    感谢

    解决方案

    在运行时创建格式化输出需要时间; printf 呼叫很慢。 GCC知道这一点,所以用第一个函数替换 。由于 puts 会自动添加 \\\
    ,因此GCC需要移除 \\\
    来补偿。



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


    Working under Linux, i just met the following issue. (For sure, someone will give me the answer, but up to now,i didn't find any simple and clear answer :)

    /*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;
    }
    

    Running the following code under Linux give two strings BUT the ending char are differents: the first output ends with 0x0d while the 2nd ends with 0x0d,0x0a.

    This is something done by the compiler (GCC) as you can see in the obj file:

    Contents of section .rodata:
     400610 01000200 48656c6c 6f20576f 726c6432  ....Hello World2
     400620 0d004865 6c6c6f20 576f726c 64330d0a  ..Hello World3..
     400630 2000                                  .              
    

    So, questions are:

    • Why ?
    • How can i avoid this kind of "optimization"(!?)

    Thanks

    解决方案

    Creating formatted output at runtime takes time; the printf call is slow. GCC knows this, so replaces the first function with a call to puts. Since puts automatically adds a \n, GCC needs to remove the \n from the string to compensate.

    GCC does this because it considers printf a built-in. Because this has no effect on the bytes output or even on the number of calls to write; I strongly recommend leaving it as-is. If you do want to disable it, you can pass -fno-builtin-printf, but the only effect will be to slow down your code as it tries to format the string unnecessarily.

    这篇关于如何从obj文件中的字符串字面值停止GCC剥离尾随换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆