You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在MinGW中用GCC链接NASM汇编代码时,ExitProcess@4引用未定义

解决MinGW链接ExitProcess@4未定义引用问题

问题描述

在Windows下编写NASM汇编程序,调用Windows API的ExitProcess函数,汇编成功但使用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

使用的汇编和链接命令

nasm -f win32 file.asm -o file.obj
gcc file.obj -o file.exe -m32 -nostartfiles -lkernel32 -luser32

错误信息

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

解决方法

问题核心是MinGW导入库的函数命名规则:MinGW对Windows API函数的装饰名会额外添加前缀下划线,正确的函数名应为_ExitProcess@4,而非ExitProcess@4。修改步骤如下:

  1. 修正汇编代码中的函数引用
    将extern ExitProcess@4改为extern _ExitProcess@4,同时把调用语句call ExitProcess@4改为call _ExitProcess@4。修改后的关键代码片段:

    section .text
        global _start
    
        extern _ExitProcess@4   ; 添加前缀下划线,匹配MinGW命名规则
    
    ; ... 中间代码省略 ...
    
        push 0                  ; exit code 0
        call _ExitProcess@4      ; 修正调用的函数名
    
  2. 重新执行汇编和链接命令
    再次运行原命令即可完成链接:

    nasm -f win32 file.asm -o file.obj
    gcc file.obj -o file.exe -m32 -nostartfiles -lkernel32 -luser32
    

额外说明

  • MinGW 32位导入库遵循_函数名@参数字节数的命名规则,这是和原生Windows COFF导入库的核心区别(原生库函数名无前缀下划线)。
  • 若不想手动处理装饰名,也可使用extern _ExitProcess(不带@4),调用时写call _ExitProcess,链接器会自动匹配到正确的装饰名,但显式写出@4更符合汇编的严谨性。

内容的提问来源于stack exchange,提问作者user23130088

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 21:12:51