今天遇到一个诡异的问题,简单的说就是,在添加了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).