如何从汇编例程调用C函数,并使用nasm和gcc链接C和汇编文件 [英] how to call C functions from assembly routines and link the C and assembly files using nasm and gcc
问题描述
我想从程序集调用至少1个C函数。这是因为我从零开始做我自己的小操作系统(无中生有)。我想从我的启动加载器调用c函数的原因。我可以理解程序集,但在编写自己的程序时很差。所以如果我能将控制从汇编程序转移到c程序,我的工作变得更容易。
因此,如何将汇编pgm和C程序文件链接成一个。即使文件大小超过512字节,我也可以。我在 mingw 的帮助下,在Windows 7上 。我的c编译器是 gcc ,汇编器是 nasm 。 更容易解析方案
只是为你展示一个例子,前一段时间我在互联网上发现了它,并将它作为源保存在我的计算机上,不知道从哪里来的
; printf1.asm从存储区和寄存器中打印一个整数
;汇编:nasm -f elf -l printf.lst printf1.asm
;链接:gcc -o printf1 printf1.o
;运行:printf1
;输出:a = 5,eax = 7
;等价C代码
; / * printf1.c打印一个int和一个表达式* /
; #include
; int main()
; {
; int a = 5;
; printf(a =%d,eax =%d \ n,a,a + 2);
;返回0;
; }
;声明一些外部函数
;
extern printf; C函数,称为
SECTION .data;数据部分,初始化变量
a:dd 5; int a = 5;
fmt:dba =%d,eax =%d,10,0; printf格式\\\
,0
SECTION .text;代码部分。全球主要
;标准的gcc入口点
main:;入口点
的程序标签push ebp;设置栈帧
mov ebp,esp
mov eax,[a];将商店放入注册
add eax,2; a + 2
推eax; a + 2
push dword [a];变量的值
push dword fmt; ctrl字符串的地址
call printf;调用C函数
add esp,12; pop stack 3推送次数4字节
mov esp,ebp;删除堆栈框架
pop ebp;与离开相同op
mov eax,0;正常,没有错误,返回值
ret;返回
I want to call at least 1 C function from assembly. It is because I'm doing my own tiny OS from scratch(out of nothing). The reason i want to call c function from my boot loader. I can understand assembly but poor in writing my own program. So if i could transfer control from assembly procedure to c procedure my job is made easier.
So how to link assembly pgm and C program files into one. It is ok for me even if the file size exceeds 512 bytes. I am doing this on Windows 7 with help of mingw. my c compiler is gcc and assembler is nasm.
easier to just show you an example, I found this on the internet a while ago and saved it as a source on my computer, not sure where from though
; 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
; 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
这篇关于如何从汇编例程调用C函数,并使用nasm和gcc链接C和汇编文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!