在linux nasm汇编中调用C IO函数

标签 c linux gcc assembly nasm

有没有办法从 nasm 汇编文件调用 C 输入/输出函数?

最佳答案

以下代码是从 Sample nasm programs 逐字复制的:

printf1.asm基本调用printf:

  The nasm source code is printf1.asm
  The result of the assembly is printf1.lst
  The equivalent "C" program is printf1.c
  Running the program produces output printf1.out

  This program demonstrates basic use of "C" library function  printf.
  The equivalent "C" code is shown as comments in the assembly language.

; printf1.asm   print an integer from storage and from a register
; Assemble:     nasm -f elf -l printf.lst  printf1.asm
; Link:         gcc -o printf1  printf1.o
; Run:          printf1
; Output:       a=5, eax=7

; Equivalent C code
; /* printf1.c  print an int and an expression */
; #include <stdio.h>
; int main()
; {
;   int a=5;
;   printf("a=%d, eax=%d\n", a, a+2);
;   return 0;
; }

; Declare some external functions
;
        extern  printf          ; the C function, to be called

        SECTION .data           ; Data section, initialized variables

        a:      dd      5               ; int a=5;
fmt:    db "a=%d, eax=%d", 10, 0 ; The printf format, "\n",'0'


        SECTION .text                   ; Code section.

        global main             ; the standard gcc entry point
main:                           ; the program label for the entry point
        push    ebp             ; set up stack frame
        mov     ebp,esp

        mov     eax, [a]        ; put a from store into register
        add     eax, 2          ; a+2
        push    eax             ; value of a+2
        push    dword [a]       ; value of variable a
        push    dword fmt       ; address of ctrl string
        call    printf          ; Call C function
        add     esp, 12         ; pop stack 3 push times 4 bytes

        mov     esp, ebp        ; takedown stack frame
        pop     ebp             ; same as "leave" op

        mov     eax,0           ;  normal, no error, return value
        ret                     ; return

关于在linux nasm汇编中调用C IO函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8523905/

相关文章:

c - C 中 getopt_long() 的强制选项

c - c 中 '(' token 之前的预期标识符错误

c - 将 mex 文件链接到静态 mpfr 库时出现问题

linux - curl:来自 CLI 的每个文件附加 header (用于多部分 POST、SOAP 等)

c - 寻求有关安装和使用mips-gcc交叉编译器以生成自定义ASM的帮助

c - 如何在没有参数的情况下将值传递给函数

linux - 使用netlink API从linux界面删除属于同一子网的ipv4地址

python - 为什么即使没有执行/'x' 权限也可以运行 python 脚本?

c++ - 禁用关于 "underscore-prefixed user-defined literals"的 GCC 警告

c - 有什么办法可以拆分 gcc 宏参数吗?