C++ MASMでx64アセンブリからHelloWorldをprintfする


環境

  • Visual Studio 2019
  • MSVC 14.16.27023
  • C++14
  • x64

はじめに

x86ではインラインアセンブリ(__asm)が使えますがx64はサポートされていないので、別途ひと手間かける必要があります。

予めビルド設定でmasmを有効にする必要があります。


任意のディレクトリに任意の名前で.asmを作成し、Microsoft Macro Assemblerを設定します。

アセンブリを書く

本例ではサンプルとして下記のコードをアセンブリ化しています。

example.cpp
#include <cstdio>

extern "C" void helloworld()
{
    printf("Hello World from %s!", "Assembly");
}

ミニマムなアセンブリ例:

helloworld.asm
.code

; [.data]
message_str db 'Assembly', 0
format_str db 'Hello World from %s!', 0

; [.text]
extrn printf:proc

helloworld proc

lea rdx, message_str
lea rcx, format_str
jmp printf

helloworld endp

end

呼び出し側:
本例の場合printf関数ポインタを上記アセンブリにて使用している為legacy_stdio_definitions.lib(またはlibcmt.lib(マルチスレッド), libc.lib(シングルスレッド) or 適切なリンカ)のリンクが必要なことに注意して下さい。

main.cpp
#pragma comment(lib, "legacy_stdio_definitions.lib")

#ifdef __cplusplus
extern "C" {
#endif

    void helloworld();

#ifdef __cplusplus
};
#endif

int main(const int argc, const char** argv)
{
    helloworld();
    return 0;
}

サンプル結果