$\require{cancel}$
cout
to work, so we will use printf.
printf("%s is %d years old\n",name, age)
printf
,
extern printf
_printf
_start
global main section .text main:
extern "C"
to our function declarations.
extern "C" void Newline() { printf("\n"); }
g++ -c -o myLib.o myLib.cpp
cc
does not mangle names, so no problem.
-g
so we can run gdb
nasm -f elf64 -g myCaller.asm -o myCaller.o g++ -c -o myLib.o myLib.cpp cc -c -o myCLib.o myCLib.c g++ -g myCaller.o myLib.o -o myCaller
section .data format0 db `%s\n\n`,0 format1 db `%s %d\n`,0 message db "Hello World!",0 number1 dd 1234 count dd 0 ... mov rdi, format0 mov rsi, message mov eax, 0 call printf mov rdi, format1 mov rsi, message mov rdx, [count] mov eax, 0 call printf
extern "C" type name(params)
in the c++ file
extern name
in the assembly file.
// c++ extern "C" void Newline() { printf("\n"); } extern "C" void PrintHello() { printf("Hello world from C++!\n"); return; } ; assembly extern PrintHello extern Newline ... call Newline call PrintHello
; asm mov rdi, 100 call PrintNumber // c++ extern "C" void PrintNumber(int n) { printf("The number is %d\n", n); return; }
; asm mov rdi, 100 mov rsi, 200 call AddEm mov rdi, rax call PrintNumber // c++ extern "C" int AddEm(int a, int b){ return a+b; }
; asm mov rdi, callCount call PrintAndIncrement // c++ extern "C" void PrintAndIncrement(int & n) { printf("The number is %d\n", n); ++n; return; }
; nasm mov rdi, array mov rsi, 10 call FillArray call Newline mov rdi, array mov rsi, 10 call PrintArray call Newline // C++ extern "C" void FillArray(int data[], int size) { for (int i{0}; i < size; ++i) { data[i] = 100 + i; } return; } extern "C" void PrintArray(const int data[], int size) { for (int i{0}; i < size; ++i) { printf("Array[%d] = %d\n", i, data[i]); } return; }