Search code examples
c++assemblymasm

call masm function with arguments from c++ code


here is assembler code:

.386
.model flat, stdcall

_asmFunc proto arg1: dword, arg2: dword

.data
.code

_asmFunc proc, arg1: dword, arg2:dword
    mov eax, arg1
    add eax, arg2
    ret
_asmFunc endp

end

and here is c++ code:

#include <iostream>

extern "C" int asmFunc(int, int);

int main()
{
    std::cout << asmFunc(5, 6);

    char a;
    std::cin >> a;
    return 0;
}

the thing is: in case i remove all arguments from function, remove stdcall from model in asm and remove proto line - i can call this from c++, but if i want to pass some arguments, i need to add them after procedure header, which means i need to add stdcall, in this case c++ tells me that program can't find my function (unresolved external symbol _asmFunc), i really can't find any normal combination (cause i don't wanna pass arguments by hand via registers or manually put them in stack and take them out in my function, too many extra code) that allows me to call asm function with arguments from c++, either it can't have arguments or c++ code can't find it


Solution

    1. The calling convention in the .model directive must match the calling convention in the C function declaration. For the default cdecl calling convention, just use .model flat, c

    2. As a result of specifying the language type in the .model directive, name decoration is performed automatically. This means you should not add any name decoration like _ to the names, those will be decorated according to the name mangling rules for the specified calling convention.