如何从 masm 引用外部 C++ 函数?

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

我目前正在学习 masm,但在调用外部函数时遇到问题。

我在 c++ 中有一个名为 writei 的函数,它接收一个 uint64 并输出它。

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

我尝试 "extrn"ing 并从 .asm 文件调用它,但编译器抛出 "unresolved external symbol writei referenced in function mai"。

这是masm代码(我用的是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

除其他事项外,您需要在 C++ 方法声明中 "extern C"

例如:

extern "C" {
  int writei(uint64_t a);
}

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

这里有一篇很好的文章对此进行了更详细的解释:

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