Help us understand the problem. What is going on with this article?

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

はじめに

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++は最高。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした