- torshie@Orz:/tmp$ cat t.c
- int f() {
- int x = 35;
- int y = 20;
- return x + y;
- }
- torshie@Orz:/tmp$ cat main.c
- extern int f();
- int main() {
- printf("%d\n", f());
- }
- torshie@Orz:/tmp$ gcc t.c -m32 -c
- torshie@Orz:/tmp$ gcc main.c -m64 -c
- main.c: In function ‘main’:
- main.c:3: warning: incompatible implicit declaration of built-in function ‘printf’
- torshie@Orz:/tmp$ gcc main.o t.o
- /usr/bin/ld: i386 architecture of input file `t.o' is incompatible with i386:x86-64 output
- collect2: ld returned 1 exit status
- torshie@Orz:/tmp$ objcopy t.o -O elf64-x86-64
- torshie@Orz:/tmp$ gcc main.o t.o
- torshie@Orz:/tmp$ ./a.out
- Segmentation fault
- torshie@Orz:/tmp$ gcc t.c -O2 -c -m32
- torshie@Orz:/tmp$ objcopy -O elf64-x86-64 t.o
- torshie@Orz:/tmp$ gcc t.o main.o
- torshie@Orz:/tmp$ ./a.out
- 55
- torshie@Orz:/tmp$ uname -a
- Linux Orz 2.6.27-7-generic #1 SMP Tue Nov 4 19:33:06 UTC 2008 x86_64 GNU/Linux
- torshie@Orz:/tmp$ cat /proc/cpuinfo |grep 'model name'
- model name : Intel(R) Core(TM)2 Duo CPU E8200 @ 2.66GHz
- 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文件格式跟文件中指令的格式没有太大关系~~~