Search code examples
c++visual-c++masm

how do I reference an external C++ function from masm?


I'm currently learning masm and I am having a problem calling an external function.

I have a function in c++ which is called writei, it receives a uint64 and outputs it.

int writei(uint64_t a)
{
    cout << a;
    return 1;
}

I tried "extrn"ing and calling it from an .asm file but the compiler throws "unresolved external symbol writei referenced in function mai".

this is the masm code (I'm using visual studio 2019)

extern writei : proto


.code
mai proc
    push rbp
    push rsp
    mov ecx,3
    call writei
    pop rsp
    pop rbp
    ret
mai endp
end

Solution

  • Among other things, you need "extern C" in your C++ method declaration.

    For example:

    extern "C" {
      int writei(uint64_t a);
    }
    
    int writei(uint64_t a)
    {
        cout << a;
        return 1;
    }
    

    Here's a good article that explains this in more detail:

    ISO C++ FAQ: How to mix C and C++