具有 MASM 代码的 Visual Studio C/C++ 项目会产生错误“错误 A2008:语法错误:”。

Koo*_*uel 2 x86 assembly masm visual-studio

main.asm我有一个 Visual Studio C/C++ 项目,其中包含一个程序集文件。在构建项目的过程中,我收到错误:

1>main.asm(5): error A2008: syntax error : .
1>main.asm(6): error A2008: syntax error : .
1>main.asm(7): error A2008: syntax error : .
1>main.asm(8): error A2008: syntax error : ,
1>main.asm(20): error A2008: syntax error : INVOKE
Run Code Online (Sandbox Code Playgroud)

我的main.asm代码是:

; program 3.1
; sample Assembly program - MASM (32-bit)


.386                                ; Line 5
.MODEL FLAT, stdcall                ; Line 6
.STACK 4096                         ; Line 7
ExitProcess PROTO, dwExitCode:DWORD ; Line 8

.data
sum DWORD 0

.code
_main PROC
mov eax, 25
mov ebx, 50
add ebx, ebx
mov sum, eax

INVOKE ExitProcess, 0               ; Line 20
_main ENDP
END
Run Code Online (Sandbox Code Playgroud)

Visual Studio 的屏幕截图,其中包含我的代码和错误:

https://i.stack.imgur.com/VCtKg.jpg

为什么我会收到这些错误以及如何修复它们?

Mic*_*tch 5

.MODEL根据您在以、 、开头的行上显示的错误.STACK.386我只能推测您正在为 64 位目标而不是 32 位目标构建。您可能还收到与该指令相关的错误INVOKE。64 位 MASM 不支持这些指令,因此会生成错误。在 64 位代码中,模型始终被假定为平坦的,并且 CDECL、STDCALL、THISCALL、FASTCALL 等的调用约定都是相同的,并且遵循 Windows 64 位调用约定

你有两个选择:

  • 构建 32 位应用程序。在 Visual Studio 中,作为菜单栏的一部分,有一个平台的下拉框。x64可以在工具栏中通过更改为来调整平台x86

    在此输入图像描述

  • 修改代码以使用 64 位代码。要构建 64 位,您必须替换INVOKECALL,并且必须使用Windows 64 位调用约定。您可以删除.STACK.MODEL.386指令。EXTERN通过使用类型声明外部过程来修改它们的定义PROC。代码可能类似于:

    ; program 3.1
    ; sample Assembly program - MASM (64-bit)
    
    extern ExitProcess:PROC
    public mainCRTStartup
    
    .data
    sum DWORD 0
    
    .code
    mainCRTStartup PROC       ; Use mainCRTStartup if making a CONSOLE app without
                              ;   any C/C++ files AND if you haven't overridden the
                              ;   ENTRY point in the Visual Studio Project.
      sub rsp, 8+32           ; Align stack on 16 byte boundary and allocate 32 bytes
                              ;   of shadow space for call to ExitProcess. Shadow space
                              ;   is required for 64-bit Windows Calling Convention as
                              ;   is ensuring the stack is aligned on a 16 byte boundary
                              ;   at the point of making a call to a C library function
                              ;   or doing a WinAPI call.
      mov eax, 25
      mov ebx, 50
      add ebx, ebx
      mov sum, eax
    
      xor ecx, ecx            ; Set Error Code to 0 (RCX is 1st parameter)
      call ExitProcess
    mainCRTStartup ENDP
    END
    
    Run Code Online (Sandbox Code Playgroud)

    对于您的环境,入口点可能会有所不同,具体取决于您是创建 GUI 还是 CONSOLE 应用程序以及您的项目是否存在 C/C++ 文件。

    与 32 位 Windows 代码不同,64 位调用约定中的函数名称不需要以下划线开头。