将 NASM 汇编代码中的 Windows API 函数 (ExitProcess) 与 MinGW 上的 GCC 链接时出现问题

6 assembly gcc nasm

我正在尝试在 Windows 上的 NASM 中编写一个简单的汇编程序,其中包含一个循环并从 Windows API 调用 ExitProcess 函数。我已经使用 NASM 成功组装了代码,但是当我尝试将其与 MinGW 上的 GCC 链接时,我遇到了 ExitProcess@4 的“未定义引用”错误。

这是我的汇编代码(file.asm):

section .data
    i dd 0

section .text
    global _start

    extern ExitProcess@4   ; Import ExitProcess function from kernel32.dll

_start:
    mov ecx, 1000000       ; set loop counter

    ; loop start
loop_start:
    mov eax, [i]           ; load i into eax
    ; your code inside the loop (e.g., b = i) goes here

    add eax, 1             ; increment eax
    mov [i], eax           ; store the result back to i

    cmp eax, ecx           ; compare i with loop counter
    jl loop_start          ; jump to loop_start if i < ecx

    ; your code after the loop (e.g., input(time() - a)) goes here

    ; exit the program
    push 0                  ; exit code 0
    call ExitProcess@4      ; call ExitProcess function

    ; It's good practice to have a ret instruction, even though it will not be reached
    ret

Run Code Online (Sandbox Code Playgroud)

我使用以下命令来组装和链接:

nasm -f win32 file.asm -o file.obj
gcc file.obj -o file.exe -m32 -nostartfiles -lkernel32 -luser32
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

file.obj:(.text+0x19): undefined reference to `ExitProcess@4'
collect2.exe: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我尝试了各种库组合(-lkernel32、-luser32 等),但问题仍然存在。如何在 MinGW 上将 ExitProcess 函数与 GCC 正确链接?我在链接过程中遗漏了什么吗?

任何帮助或指导将不胜感激。谢谢你!