int main(void) { printf("hello from %s(). \n", __func__); return 0; }
编译生成main.o文件:
1
[latelee@FightNow lib-test]$ gcc -c main.c
链接:
1 2 3 4
[latelee@FightNow lib-test]$ ld main.o ld: warning: cannot find entry symbol _start ; defaulting to 08048074 main.o: In function `main': main.c:(.text+0x21): undefined reference to `printf'
现在解决第一个warning,使用-e指定入口函数(地址):
1 2 3
[latelee@FightNow lib-test]$ ld -e main main.o main.o: In function `main': main.c:(.text+0x21): undefined reference to `printf'
因为printf定义于C库中,因此需要使用C库:
1 2
[latelee@FightNow lib-test]$ ld -e main main.o -lc (默认为动态库)
执行之,可惜出错了:
1 2
[latelee@FightNow lib-test]$ ./a.out -bash: ./a.out: /usr/lib/libc.so.1: bad ELF interpreter: 没有那个文件或目录
它说“没有那个文件或目录”,查看一下:
1 2
[latelee@FightNow lib-test]$ ls /usr/lib/ | grep "libc.so" libc.so
[latelee@FightNow lib-test]$ ld -e main main.o /usr/lib/libc.a /usr/lib/libc.a(syslog.o): In function `closelog': (.text+0xcd): undefined reference to `_Unwind_Resume' /usr/lib/libc.a(syslog.o): In function `openlog': (.text+0x3d2): undefined reference to `_Unwind_Resume' /usr/lib/libc.a(syslog.o): In function `__vsyslog_chk': (.text+0x908): undefined reference to `_Unwind_Resume' /usr/lib/libc.a(syslog.o): In function `__vsyslog_chk': (.text+0x91a): undefined reference to `_Unwind_Resume' . . . /usr/lib/libc.a(iofclose.o): In function `fclose': (.text+0x1a7): undefined reference to `_Unwind_Resume' /usr/lib/libc.a(iofclose.o):(.eh_frame+0x166): undefined reference to `__gcc_personality_v0' /usr/lib/libc.a(ioftell.o): In function `ftell': (.text+0x1ab): undefined reference to `_Unwind_Resume' /usr/lib/libc.a(ioftell.o):(.eh_frame+0xde): undefined reference to `__gcc_personality_v0' /usr/lib/libc.a(iofwrite.o): In function `fwrite': (.text+0x144): undefined reference to `_Unwind_Resume' /usr/lib/libc.a(iofwrite.o):(.eh_frame+0xde): undefined reference to `__gcc_personality_v0'
我的本意是想研究一下各个库之间的相互依赖关系,网上有资料说使用ld命令的–start-group和–end-group选项来解决,在U-Boot的Makefile中的确也看到了。不过自己没有顺利找到一个可以测试的例子。限于能力及时间,这个研究暂时搁置了。等以后对linux底层的东西更加了解时再来研究亦不晚。 参考资料: 1、如果想了解关于bin文件及汇编、连接的知识,请用google搜索“Making plain binary files using a C compiler”,作者是Cornelis Frank,写于2000年,年代虽久,经典依旧。 2、《程序员的自我修养–链接、装载与库》,一本需要慢慢研读的好书。