[Debug] printf undefined reference to `putchar‘

本文探讨了在使用GCC编译时遇到的因内联函数优化导致的undefined reference错误。当添加printf后出现对putchar和puts的引用错误,而注释掉printf后错误消失。解决方案是通过添加-fno-builtin选项禁用GCC的内建函数替换,并可能需要-nostdlib或-nodefaultlibs避免链接系统库。博主分享了其使用的编译参数及其作用,并提供了问题的解决方法。
摘要由CSDN通过智能技术生成

今天遇到一个诡异的问题,简单的说就是,在添加了printf以后,会跳出两个error来
一个叫undefined reference to putchar
另一个叫undefined reference to puts
然后把printf注掉以后,这两个error又莫名其妙的没了。

在网上查了半天,终于找到一个关于这个问题的讨论,问题也解决了。
printf and puts problem…

简单摘录其中的几个比较有用的说法如下:

1, GCC确实会自作聪明的做一些替换

GCC does do basic function substitution when certain optimizations are enabled.
For example.
printf(“a”); -> putchar(‘a’);
printf(“hello\n”) -> puts(“hello”);
basically if there is no format character in the string then it may be reduced to a simpler function.

how can I disable that optimizations?

using the -O argument you can control the optimisation level.
-O0 is none.

Hmm… the only things I use are:
-fno-leading-underscore -ffreestanding -fpack-struct
I don’t want the leading underscore, since it makes my C -> asm easier (as well as linking libraries), freestanding was so it doesn’t link the regular C library (or so I thought, and it works for me, so i dunno), and pack-struct because I wanted all my structures packed unless I specifically tell it not to be (so I am 100% positive my structs are what I think they are, and if I compile for 64-bit I don’t want it all breaking unless I already know it’s going to). Anyways, those are the only arguments I use for gcc and my kernel and drivers compile without issue.

2, 是buildin函数在作怪(解决方案)

Actually it’s -fno-builtin that does the trick…
And -nostdlib to avoid linking with the libraries used on the OS that gcc is on (or -nodefaultlibs to avoid gcc provided library functions).

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山猫Show

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值