gpt4 book ai didi

c - 如何从汇编例程调用 C 函数并使用 nasm 和 gcc 链接 C 和汇编文件

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:32 27 4
gpt4 key购买 nike

我想从汇编中调用至少 1 个 C 函数。这是因为我正在从头开始(无中生有)做我自己的微型操作系统。我想从我的引导加载程序调用 c 函数的原因。我能理解汇编,但不擅长编写自己的程序。因此,如果我可以将控制权从汇编程序转移到 c 程序,我的工作就会变得更容易。

那么如何将汇编 pgm 和 C 程序文件链接成一个。 即使文件大小超过 512 字节,对我来说也可以。我在 mingw 的帮助下在 Windows 7 上 执行此操作。我的 C 编译器是 gcc,汇编器是 nasm

最佳答案

举个例子比较简单,我前段时间在网上找到了这个,并把它作为源保存在我的电脑上,不过不知道从哪里来的

; 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 - 如何从汇编例程调用 C 函数并使用 nasm 和 gcc 链接 C 和汇编文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8863042/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com