LoginSignup
0
0

More than 3 years have passed since last update.

アセンブリ(NASM)で関数作ってC++で呼ぶ

Last updated at Posted at 2019-12-23

はじめに

C++からでもNASMで作った関数呼べちゃいました。

環境

  • OS : Ubuntu 18.04 LTS
  • アセンブラ : NASM 2.13.02
  • リンカ : ld 2.30
  • コンパイラ : g++ 7.4.0

ソース

main.cpp
extern "C" void _nasm_hello(void);
extern "C" [[noreturn]] void _nasm_exit(void);

int main(void){

    _nasm_hello();
    _nasm_exit();

    return 0;
}
function.asm
global _nasm_hello
global _nasm_exit

[section .data]
    string: db "Hello", 0x0a
    length: equ $ - string

[section .text]

_nasm_hello:
    mov rax, 1
    mov rdi, 1
    mov rsi, string
    mov rdx, length
    syscall
    ret

_nasm_exit:
    mov rax, 60
    mov rdi, 0
    syscall
Makefile
build:
    nasm -felf64 function.asm -o function.obj
    g++ -c -o main.obj main.cpp
    ld -e main -o exe main.obj function.obj

run:
    ./exe

実行結果

Hello

結果

C++からNASMで作った簡単な関数を呼べました。
過去記事のようにvoid main(void)を使わないのは、こう書くと
error: ‘::main’ must return ‘int’と出るからです。
かと言って_nasm_exit();を書かないと、
Segmentation fault (コアダンプしました)と出ます。

最後に

C++は最高。

0
0
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0