您现在的位置是:首页 > 服务器相关

C和汇编混编

batsom2021-08-22服务器相关

简介C和汇编混编

C语言调用汇编函数有一下几个要点:

1.C语言中用extern将用到的函数声明为外部函数

2.汇编中用.globl或.global将函数的标号声明为全局类型

3.汇编函数的写法遵循ATPCS约定
由调用者清理堆栈

C语言代码:
void  myprint(char* msg,int len );


     int choose( int a,int b ){
     if( a>b ){
          myprint( "the 1st one",13 );
          
     }else{
          myprint( "the 2st two",13 );
          
     }
     return 0;
     
}

汇编语言代码:
        ;;
        extern choose
        
        [section .data]
        num1st dd 4
        num2st dd 4

        [section .text]

global _start   ;导出程序入口函数
global myprint  ;导出打印函数

_start:
        push dword[num1st]   ;压入堆栈
        push dword[num2st]

        call choose    ;int choose(a int,b int)
        add esp,8

        mov ebx,0      ;
        mov eax,1      ;sys_exit 正常退出
        int 0x80       ;系统调用

myprint:
        mov edx,[esp+8]  ;字符串
        mov ecx,[esp+4]  ;长度
        mov ebx,1
        mov eax,4       ;sys_write
        int 0x80        ;系统调用
        ret             ;返回

编译方式:
gcc -m32 -c bar.c -o bar.o
nasm -f elf test.asm -o test.o
ld -m elf_i386 -s test.o bar.o -o test
./test

 

郑重声明:

本站所有活动均为互联网所得,如有侵权请联系本站删除处理

随便看看

文章排行

本栏推荐

栏目更新