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

使用NASM汇编生成.exe文件失败,求助解决编译链接错误

解决NASM+MinGW编译汇编生成.exe的错误

你遇到的错误包含三个核心问题,逐个解决如下:

1. 架构不兼容错误

错误片段:i386 architecture of input file 'hello.obj' is incompatible with i386:x86-64 output

  • 原因:NASM默认生成32位目标文件,但你使用的是64位版本MinGW,链接器尝试生成64位程序,导致架构不匹配。
  • 解决方案:
    • 方法一:指定NASM生成64位目标文件,修改编译命令:
      nasm -f win64 hello.asm -o hello.obj
      
    • 方法二:若需编译32位程序,改用32位MinGW的gcc,添加-m32参数:
      gcc -m32 hello.obj -o hello.exe
      

2. _printf未定义错误

错误片段:undefined reference to '_printf'

  • 原因:64位Windows平台C函数无下划线前缀,且汇编代码需匹配对应位数的函数命名规则;32位环境下才使用_printf。
  • 解决方案:
    • 64位环境:汇编代码中声明extern printf;32位环境则保留extern _printf。
    • 链接时gcc默认会关联C标准库,无需额外参数,保持gcc hello.obj -o hello.exe即可。

3. WinMain未定义错误

错误片段:undefined reference to 'WinMain'

  • 原因:MinGW的gcc默认按GUI程序链接,会寻找WinMain作为入口,但你的程序是控制台类型,入口应为main(64位)或_main(32位)。
  • 解决方案:
    • 方法一:在汇编代码中定义正确入口:64位写global main并实现main函数;32位写global _main并实现_main函数。
    • 方法二:编译时强制按控制台程序链接,添加-mconsole参数:
      gcc hello.obj -o hello.exe -mconsole
      

64位环境完整编译示例

  1. 汇编代码示例:
    extern printf
    global main
    
    section .data
        msg db 'Hello, World!', 0
    
    section .text
    main:
        sub rsp, 8  ; 64位Windows调用约定要求栈16字节对齐
        mov rcx, msg
        call printf
        add rsp, 8
        mov rax, 0
        ret
    
  2. 执行命令:
    nasm -f win64 hello.asm -o hello.obj
    gcc hello.obj -o hello.exe -mconsole
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:16:13