【问题标题】:Why am I getting this error in the assembly code below?为什么我在下面的汇编代码中收到此错误?
【发布时间】:2021-09-29 14:39:20
【问题描述】:

这是我第一次尝试在 MASM 中运行 x64 的汇编代码:

_text SEGMENT
main PROC
    mov ah,0
    ret
main ENDP
_text ENDS
END

我收到链接器错误LNK2001: unresolved external symbol mainCRTStartup。为什么?

我在属性>链接器>高级>入口点中有入口点main

P.S.:代码在 x86 中按预期组装和执行。

【问题讨论】:

    标签: assembly masm64


    【解决方案1】:

    在 C 运行时库 (CRT) libcmt.lib 中有一个入口点 (_mainCRTStartup),它执行一些初始化任务,然后将控制权交给您的应用程序的入口点主要。您可以更改默认入口点,但通常您希望 CRT 入口点自动为您进行初始化的便利。

    有两种方法可以避免LNK2001:无法解析的外部符号mainCRTStartup。

    1. 将 libcmt.lib 添加到链接命令中:
      (C-Runtime 初始化调用 main

      ml64.exe test64.asm /link /DEBUG /subsystem:console /defaultlib:kernel32.lib /defaultlib:user32.lib /defaultlib:libcmt.lib

    2. 在链接命令上指定入口点main:
      (避免 C-Runtime 初始化和调用 main

      ml64.exe test64.asm /link /DEBUG /subsystem:console /defaultlib:kernel32.lib /defaultlib:user32.lib /entry:main

    这是一些用于弹出窗口的示例 MASM64 代码:

    test64.asm

    option casemap:none
    
    externdef MessageBoxA : near
    externdef ExitProcess : near
    
       .data
       
        szDlgTitle    db "MASM 64-bit",0
        szMsg         db "HELLO",0   
    
       .code
    
    main proc
       ; Reserve 28h bytes of shadow space.
       sub  rsp, 28h       
       xor  r9d, r9d       
       lea  r8, szDlgTitle  
       lea  rdx, szMsg    
       xor  rcx, rcx       
       call MessageBoxA
       add  rsp, 28h
    
       ; rax contains the ExitCode from MessageBoxA(...)
    
       ; When the primary thread's entry-point function main returns,
       ; it returns to the C/C++ Runtime startup code,
       ; which properly cleans up all the C Runtime resources used by the process.
       ; 
       ; After the C Runtime resources have been freed,
       ; the C Runtime startup code explicitly calls ExitProcess,
       ; passing it the value returned from the entry-point function. 
       ; This explains why simply returning from the primary thread's entry-point function terminates the entire process.
       ; Note that any other threads running in the process terminate along with the process.
    
       ret
       
    main endp
    
    end
    

    为了构建 test64.exe,我使用了这些批处理命令:

    ma​​keit64.bat

    @echo on
    
    if not defined DevEnvDir (
      call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Auxiliary\Build\vcvars64.bat"
    )
    
    ml64.exe test64.asm /link /subsystem:console /defaultlib:kernel32.lib /defaultlib:user32.lib /defaultlib:libcmt.lib
    

    输出是

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      相关资源
      最近更新 更多