0

I have this assembly file

bits 32
global _start
extern kmain

section .text
_start:
    cli
    call kmain
    hlt

And this .cpp file

void kmain(void)
{    
}

And when running these commands:

nasm -f elf32 asmfoo.asm -o asmfoo.o
gcc -m32 -c cppfoo.cpp -o cppfoo.o
ld -m elf_i386 -T ./linker.ld -o foo-output asmfoo.o cppfoo.o 

I get this error:

ld: asmfoo.o: in function `_start':
asmfoo.asm:(.text+0xe): undefined reference to `kmain'

But when I change the name of the cpp file from cppfoo.cpp to cppfoo.c and run the same compile commands it works without any errors. So how would I call a c++ function from assembly as this doesent work with c++ for some reason.

Robiot
  • 98
  • 10
  • 3
    You’ll need to either use `extern “C”` to disable mangling, or you’ll have to call the actual mangled function name. C++ includes parameter info etc in the function name, C doesn’t. You can use `nm` command to list the functions in the object file you compiled from C++ code to see the naming – Sami Kuhmonen Jun 19 '21 at 11:04
  • As for the mangling, the specifics depend on the OS in use. For ELF targets, I believe the mangling is documented in the SysV ABI document. – fuz Jun 19 '21 at 11:10
  • Thank I got it working now! I didn't know about the name mangling before but now I know so thanks once again! – Robiot Jun 19 '21 at 11:15

0 Answers0