如何在64位的linux系统上使用汇编和C语言混合编程-32汇编移植64位系统

foo.s
extern choose 

;;;;;the data area 
num1st            dd        3 
num2nd        dd        4 

global        _start 
global        myprint 


_start: 

    push        dword [num1st] 
    push        dword [num2nd] 

    call    choose 
    add        esp,8 

    mov        ebx,0 
    mov        eax,1 
    int        0x80 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 
    ;;;; function protype    :void myprint(char *msg, int len) 
    ;;;; display the message 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 

myprint: 
     
    mov        ecx,[esp+4] 
    mov        edx,[esp+8] 
    ;mov        edx,esi 
    ;mov        ecx,edi 

    mov        ebx,1 
    mov        eax,4 
    int        0x80 
    ret


bar.c
/************  bar.c *****************/

void myprint(char *msg,int len); 

int choose(int a,int b) 
{ 
    if (a>=b) { 
        myprint("the 1st one\n",13); 
    } 

    else { 
        myprint("the 2st one\n",13); 
    } 

    return 0; 
}

以上两段都是32位下的代码

可用以下命令:

nasm -f elf foo.s -o foo.o
gcc -c bar.c -o bar.o
ld -s -o foobar bar.o foo.o(需要把汇编里的_start ->main)

汇编语言用nasm编写并用nasm编译器编译,而C语言用的是gcc编译,这些都没有问题,但是在链接的时候出错了,提示如下:


ld: i386 architecture of input file `foo.o' is incompatible with i386:x86-64 output

google了一下,意思就是nasm 编译产生的是32位的目标代码,gcc 在64位平台上默认产生的是64位的目标代码,这两者在链接的时候出错,gcc在64位平台上默认以64位的方式链接。


这样在解决的时候就会有两种解决方案:

<1> 让gcc 产生32位的代码,并在链接的时候以32位的方式进行链接

在这种情况下只需要修改编译和链接指令即可,具体如下:


nasm -f elf foo.s -o foo.o
gcc -m32 -c bar.c -o bar.o
ld -m elf_i386 -s -o foobar foo.o bar.o


具体的-m32 和 -m elf_i386 请自行查阅gcc (man gcc)

参考地址:http://bbs.chinaunix.net/thread-2018497-1-1.html
如果你是高版本的gcc(可能是由于更新内核造成的),可能简单的使用-m32 的时候会提示以下错误(使用别人的历程,自己未曾遇到):


> In file included from /usr/include/stdio.h:28:0,
> from test.c:1:
> /usr/include/features.h:323:26: fatal error: bits/predefs.h: No such file or directory
> compilation terminated.


这应该是缺少构建32 位可执行程序缺少的包,使用以下指令安装:
sudo apt-get install libc6-dev-i386
此时应该就没有什么问题了。

参考地址:http://aaronbonner.tumblr.com/post/14969163463/cross-compiling-to-32bit-with-gcc

转自:http://www.cnblogs.com/chenchenluo/archive/2012/04/02/2421457.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值