Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

assembly - Linking C with NASM

I have a NASM file and a C file. How do I call a function in the C file from the NASM file? How do I call a NASM function from the C file?

Many Thanks DD

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calling assembly function from C:

C file:

#include <stdio.h>

int add(int a, int b);

int main(int argc, char **argv)
{
  printf("%d
", add(2, 6));
  return 0;
}

assembly file:

global add

section .data

section .text

add:
    mov   eax, [esp+4]   ; argument 1
    add   eax, [esp+8]   ; argument 2
    ret

compiling:

$ nasm -f elf add.asm 
$ gcc -Wall main.c add.o 
$ ./a.out 
8
$ 

Calling C function from assembly:

C file:

int add(int a, int b)
{
  return a + b;
}

assembly file:

extern add
extern printf
extern exit

global _start

section .data
  format db "%d", 10, 0
section .text

_start:
    push  6
    push  2
    call  add     ; add(2, 6)

    push  eax
    push  format
    call  printf  ; printf(format, eax)

    push  0
    call exit     ; exit(0)

compiling:

$ gcc -Wall -c add.c
$ nasm -f elf main.asm 
$ ld main.o add.o -lc -I /lib/ld-linux.so.2
$ ./a.out 
8
$ 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...