linux: 将32位.o文件和64位.o文件链接成64位的可执行程序

来源:互联网 发布:可以看youtube 软件 编辑:程序博客网 时间:2024/06/05 16:46
  1. torshie@Orz:/tmp$ cat t.c
  2. int f() {
  3.         int x = 35;
  4.         int y = 20;
  5.         return x + y;
  6. }
  7. torshie@Orz:/tmp$ cat main.c
  8. extern int f();
  9. int main() {
  10.         printf("%d\n", f());
  11. }
  12. torshie@Orz:/tmp$ gcc t.c -m32 -c
  13. torshie@Orz:/tmp$ gcc main.c -m64 -c
  14. main.c: In function ‘main’:
  15. main.c:3: warning: incompatible implicit declaration of built-in function ‘printf’
  16. torshie@Orz:/tmp$ gcc main.o t.o
  17. /usr/bin/ld: i386 architecture of input file `t.o' is incompatible with i386:x86-64 output
  18. collect2: ld returned 1 exit status
  19. torshie@Orz:/tmp$ objcopy t.o -O elf64-x86-64
  20. torshie@Orz:/tmp$ gcc main.o t.o
  21. torshie@Orz:/tmp$ ./a.out
  22. Segmentation fault
  23. torshie@Orz:/tmp$ gcc t.c -O2 -c -m32
  24. torshie@Orz:/tmp$ objcopy -O elf64-x86-64 t.o
  25. torshie@Orz:/tmp$ gcc t.o main.o
  26. torshie@Orz:/tmp$ ./a.out
  27. 55
  28. torshie@Orz:/tmp$ uname -a
  29. Linux Orz 2.6.27-7-generic #1 SMP Tue Nov 4 19:33:06 UTC 2008 x86_64 GNU/Linux
  30. torshie@Orz:/tmp$ cat /proc/cpuinfo |grep 'model name'
  31. model name        : Intel(R) Core(TM)2 Duo CPU     E8200  @ 2.66GHz
  32. model name        : Intel(R) Core(TM)2 Duo CPU     E8200  @ 2.66GHz
复制代码

如上面的示例, 注意: 可以链接跟最终程序能够正确的运行是两个不通的概念. (32位x86跟64位x86的调用约定不一样, 如果是自己手写的汇编的话就可以完全避免seg fault)

出乎我意料的是objcopy -O elf32-i386 main.o这个命令也能正确运行, 但是无法正确链接. 看来elf文件格式跟文件中指令的格式没有太大关系~~~

原创粉丝点击