将C与NASM链接 [英] Linking C with NASM
本文介绍了将C与NASM链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个NASM文件和一个C文件.如何在NASM文件的C文件中调用函数?如何从C文件调用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?
非常感谢 DD
推荐答案
从C调用汇编函数:
C文件:
#include <stdio.h>
int add(int a, int b);
int main(int argc, char **argv)
{
printf("%d\n", add(2, 6));
return 0;
}
汇编文件:
global add
section .data
section .text
add:
mov eax, [esp+4] ; argument 1
add eax, [esp+8] ; argument 2
ret
编译:
$ nasm -f elf add.asm
$ gcc -Wall main.c add.o
$ ./a.out
8
$
从汇编中调用C函数:
C文件:
int add(int a, int b)
{
return a + b;
}
汇编文件:
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)
编译:
$ 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
$
这篇关于将C与NASM链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文