Ian
Ian

Reputation: 21

Interfacing Assembly with C

I am trying to call a assembly function assembled with NASM from a simple C driver class compiled with MinGW GCC.

I am using the following commands to compile and assemble the files.

nasm -f win32 asm_main.asm -o asm.o

gcc -c driver.c -o driver.o

and the following command to link them together.

ld.exe asm.o driver.o -L"C:\Windows\SysWOW64" -lkernel32 -luser32 -o app.exe

I get the error message:

driver.o:driver.c:(.text+0x7): undefined reference to `__main'

Here is my sample assembly and C code

; asm.asm
extern _MessageBoxA, _ExitProcess

section .data
    title db "Greeting", 0
    message db "Hello World!", 0
section .bss

section .text
    global _asm_main

_asm_main:
    enter 0, 0

    push dword 0 
    push dword title
    push dword message 
    push dword 0 
    call _MessageBoxA

    push dword 0 
    call _ExitProcess

    mov eax, 0 
    leave
    ret

// driver.c
extern int asm_main();


void main()
{   
    asm_main(); 
}

Any thought why I might get this error? Thanks.

UPDATE: I got my problem solved by changing ExitProcess to _ExitProcess@4 and MessageBox to _MessageBoxA@16 and linking with gcc.

Upvotes: 2

Views: 443

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126458

You're missing the gcc C startup routine __main (called by main when you compile with gcc), which is usually defined in libgcc. The easiest way to get it is to link with gcc (which includes it) rather than ld. Alternately, add -lgcc to the link command line.

Upvotes: 1

Related Questions