微軟的組合語言

安裝:Visual Studio

如果您想學習微軟組合語言程式的開發,最簡單的方法是安裝 Visual Studio 開發環境,然後利用其中的組譯連結器 ML.exe 進行組譯的動作。或者利用 CL.exe 這個編譯器,將 C 語言轉換為組合語言以利觀察。

範例一:簡單加減法 (必須使用除錯環境觀察)

程式碼

.386
.model flat
.code
main PROC
    mov eax, 1
    add eax, 4
    sub eax, 2
main ENDP
END main

組譯與執行

C:\ccc\SP\code\ch03>ml add.asm
Microsoft (R) Macro Assembler Version 9.00.21022.08
Copyright (C) Microsoft Corporation.  All rights reserved.

 Assembling: add.asm
add.asm(9) : warning A4023:with /coff switch, leading underscore required for st
art address : main
Microsoft (R) Incremental Linker Version 9.00.21022.08
Copyright (C) Microsoft Corporation.  All rights reserved.

/OUT:add.exe
add.obj

C:\ccc\SP\code\ch03>devenv add.exe /debugexe

範例二:簡單加減法 (可印出結果)

程式碼

.386
.model    flat
INCLUDELIB LIBCMT
printf PROTO C, format:PTR BYTE, args:VARARG
.data
num DWORD 0
formatStr BYTE "num=%d", 0dh, 0ah, 0
PUBLIC    _main
.code
_main    PROC
    MOV eax, 1
    ADD eax, 4
    SUB eax, 2
    MOV num, eax
    INVOKE printf, ADDR formatStr, num
    ret    0
_main    ENDP
END

組譯與執行

C:\ccc\SP\code\ch03>ml add_print.asm
Microsoft (R) Macro Assembler Version 9.00.21022.08
Copyright (C) Microsoft Corporation.  All rights reserved.

 Assembling: add_print.asm
Microsoft (R) Incremental Linker Version 9.00.21022.08
Copyright (C) Microsoft Corporation.  All rights reserved.

/OUT:add_print.exe
add_print.obj

C:\ccc\SP\code\ch03>add_print
num=3

範例三:從 1 加到 10

程式碼

.386
.model    flat
INCLUDELIB LIBCMT
printf PROTO C, format:PTR BYTE, args:VARARG
.data
sum DWORD 0
formatStr BYTE "sum=%d", 0dh, 0ah, 0
PUBLIC    _main
.code
_main    PROC
    MOV eax, 1
FOR1:
    ADD sum, eax
    ADD eax, 1
    CMP eax, 10
    JLE FOR1
    INVOKE printf, ADDR formatStr, sum
    ret    0
_main    ENDP
END

組譯與執行

結果會印出 sum=55 這樣的訊息,這代表該程式正確的計算出 1+2+…+10 的結果為 55。

使用 Visual Studio 撰寫組合語言

如果您想使用 Visual Studio 這樣的工具撰寫組合語言,必須對專案進行相當複雜的設定。您可以直接使用組合語言書籍 "Assembly Language for Intel-Based Computers, 5th Edition" 的作者 Kip Irvine 教授的設定,只要下載 http://kipirvine.com/asm/examples/index.htm 網頁中的範例程式,然後將專案檔中的主程式換成所想要執行的組合語言程式即可,建議各位試試看。

結語

以上組合語言是在微軟 Windows XP 系統上,搭配 Visual Studio 2008 執行的,如果版本不同,可能執行方法會略有差異。這些組合語言是真正可以在 Win32 模式下執行的程式,並非在 DOS 環境下的版本。筆者發現在網路上這樣的範例相當稀少,希望本文對讀者能有所幫助。

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License