我先回去了。
main.asm
[section] .text
global _main
_main:
mov eax, 6
ret ; returns eax (exits)
这个程序所做的只是返回 6。
像这样组装和链接:
c:\Users\James\Desktop>nasm -fwin32 main.asm
c:\Users\James\Desktop>ld -e _main main.obj -o main.exe
c:\Users\James\Desktop>main.exe
c:\Users\James\Desktop>echo %errorlevel%
6
使用堆栈帧。
main.asm
[section] .text
global _main
_main:
push ebp ; set up stack frame
mov ebp,esp
push 6
pop eax; ; mov 6 into eax using the stack
leave ; destroy stack frame
ret ; return eax
编译:
c:\Users\James\Desktop>nasm -fwin32 main.asm
c:\Users\James\Desktop>ld -e _main main.obj -o main.exe
c:\Users\James\Desktop>main
c:\Users\James\Desktop>echo %errorlevel%
6
要使用您自己的外部函数,您可以:
func.asm
[section] .text
global _func
_func:
push ebp ; set up stack frame
mov ebp,esp
mov eax, [ebp+8] ; move argument into eax
add eax, 3 ; eax = eax + 3
leave ; destroy stack frame
ret ; return to caller with (eax + 3)
main.asm
[section] .text
global _main
extern _func
_main:
push ebp ; set up stack frame
mov ebp,esp
push 3 ; push argument onto stack for function
call _func ; calling the function
add esp, 4 ; clean 1 argument
leave ; destroy stack frame
ret ; return what func returned in eax
编译:
c:\Users\James\Desktop>nasm -fwin32 func.asm
c:\Users\James\Desktop>nasm -fwin32 main.asm
c:\Users\James\Desktop>ld -e _main main.obj func.obj -o main.exe
c:\Users\James\Desktop>main
c:\Users\James\Desktop>echo %errorlevel%
6
我很确定在你的代码中而不是 ret 16,你的意思是 int 80h。
如果是这样,您就不能像在linux 中那样在windows 中进行系统调用,
但是您可以使用gcc 链接c's 库函数,例如; stdio's puts.
要使用 c 库函数,如 printf 或 puts,您可以这样做:
[section] .text
global _main
extern _puts
_main:
push ebp ; set up stack frame
mov ebp,esp
push helloStr ; push argument onto stack for function
call _puts ; calling the function
add esp, 4 ; clean 1 argument
mov eax, 0
leave ; destroy stack frame
ret ; return 0 (exit)
[section] .data
helloStr db "Hello World!",0
而不是使用ld(因为参数很难正确设置),
你可以像使用普通的c 源文件一样在obj 文件上使用gcc。
c:\Users\James\Desktop>nasm -fwin32 main.asm
c:\Users\James\Desktop>gcc main.obj -o main.exe
c:\Users\James\Desktop>main
Hello World!
(puts 自动添加新行)