简体   繁体   中英

Calling C++ functions in MASM

I'm working on a program that will use MASM to call some C++ functions. I defined, in a separate file, to sum 2 integers and display the output.

Currently, I can't get 'main.cpp' to run asmMain() to call functions from 'main.cpp'.

code.asm

; ---------------------------------------

promptFirst PROTO C
promptSecond PROTO C
printInt PROTO C

.586
.model flat, stdcall

.stack 4096

; ---------------------------------------

.DATA

first DWORD 0
second DWORD 0

; --------------------------------

.CODE

asmMain PROC C  
    mov first, promptFirst              
    ret 
asmMain ENDP

PUBLIC asmMain  
END

main.cpp

#include <iostream>

using namespace std;

void asmMain();

int promptFirst();
int promptSecond();
void printInt(int myint);

int main() {
    asmMain();
}

int promptFirst() {
    cout << " The first number = ";
    int newint;
    cin >> newint;

    return newint;
}

int promptSecond() {
    cout << "\nThe second number = ";
    int newint;
    cin >> newint;

    return newint;
}

void printInt(int myint) {
    cout << myint;
}

The error I get for the current code is such:

Build started: Project: Project_Name, Configuration: Debug Win32
main.cpp
code.obj: error LNK2019: unresolved external symbol _promptFirst referenced in function _asmMain

Any hints on how to resolve this?

The problem is that C++ compilers mangles the symbols , which is one of the reasons behind the extern "C" construct, so that symbols are not mangled.

If you declare the function to be extern "C" then the compiler will not mangle the name, just like you do with the assembler function you call.

Use dumpbin.exe on your object-file to get the mangled name of your C++ functions.

Or ask for a symbol with C-linkage using extern "C" on the function-declarations in your C++ code.

Then you will know what to call in your assembly-code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM