2

I am trying to compile assembly code that calls c++ function. And c++ code that calls assembly code. I am using Dev-C++4.9.9.2 and nasm in Windows 7. Can some show me how to compile the following codes so that they produce working programs. These codes are taken from lecture handouts.

Calling C++ from Assembly Example

//C++ file
#include <iostream>
using std::cout;

void swap(int *p1, int *p2);
{
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

;NASM file    
extern _swap
x: dd 4
y: dd 7

push dword y
push dword x
call _swap
add esp, 8

Calling Assembly from C++ Example

;NASM file
global _swap
_swap:
    mov ecx, [esp+4]
    mov edx, [esp+8]
    mov eax, [ecx]
    xchg [ecx],eax
    ret


//C++ file
#include <iostream>
using std::cout;

void swap(int *p1, int *p2);

int main()
{
    int a = 10, b = 20;
    cout << "a=" << a << "b=" << b;
    swap(&a, &b);
    cout << "a=" << a << "b=" << b;
    system("PAUSE");
    return 0;   
}

Also it will be very helpful if some one can show me how to program the same code using Visual Studio 2010 C++ and NASM.

1
  • In what way is the code not working now?
    – Michael
    Jun 30, 2013 at 21:55

1 Answer 1

3

Symbols in C++ undergo name mangling. To make simple functions directly linkable with foreign code, you need to declare them (at least) as extern "C":

extern "C" void swap(int *, int *)

You also need to make sure that the calling conventions match. (For example, I believe that fastcall on x86_64 passes integral arguments in registers, not on the stack.)

A "foreign function interface" (ffi) library can help make this sort of cross-language interoperation easier.

1
  • Minor clarification: fastcall (or a variant thereof) is the default calling convention for x86-64, and fastcall on IA-32 also passes the first few integral arguments in registers.
    – Michael
    Jul 1, 2013 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.