1

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

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

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

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

PS:代码在 x86 中按预期组装和执行。

4

1 回答 1

2

C-Runtime 库 (CRT) libcmt.lib中有一个入口点 (_mainCRTStartup) ,它执行一些初始化任务,然后将控制权交给应用程序main的入口点。您可以更改默认入口点,但通常您希望 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,我使用了这些批处理命令:

makeit64.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

输出是

你好_masm

于 2021-10-06T03:04:41.453 回答