user366312
user366312

Reputation: 16918

How can I compile a hybrid (asm, C++) source code into a 32-bit program?

I am using Cygwin 32-bit under Win7 in a 64-bit machine.

The following program

makefile:

runme:  main.cpp    asm.o
        g++ main.cpp    asm.o   -o  executable

asm.o:  asm.asm
        nasm    -f  elf     asm.asm     -o  asm.o 

asm.asm:

section .data
section .bss
section .text
    global GetValueFromASM

GetValueFromASM:
    mov eax, 9
    ret

main.cpp:

#include <iostream>

using namespace std;

extern "C" int GetValueFromASM();

int main()
{
    cout<<"GetValueFromASM() returned = "<<GetValueFromASM()<<endl;

    return 0;
} 

is giving me the following error:

$ make
nasm    -f      elf             asm.asm         -o      asm.o
g++     main.cpp        asm.o   -o      executable
/tmp/cc3F1pPh.o:main.cpp:(.text+0x26): undefined reference to `GetValueFromASM'
collect2: error: ld returned 1 exit status
make: *** [makefile:2: runme] Error 1

I am not understanding why this error is being generated.

How can I get rid of this issue?

Upvotes: 0

Views: 340

Answers (1)

S.S. Anne
S.S. Anne

Reputation: 15576

You have to prefix your symbols with _, as is customary in Windows/Cygwin:

section .data
section .bss
section .text
    global _GetValueFromASM

_GetValueFromASM:
    mov eax, 9
    ret

The rest of your code should work fine.

An alternative would be to compile with -fno-leading-underscore. However, this may break linking with other (Cygwin system) libraries. I suggest using the first option if portability to other platforms does not matter to you.

Quoting from the GNU Online Docs:

-fleading-underscore

This option and its counterpart, -fno-leading-underscore, forcibly change the way C symbols are represented in the object file. One use is to help link with legacy assembly code.

Warning: the -fleading-underscore switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface. Not all targets provide complete support for this switch.

Upvotes: 2

Related Questions