Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ld MinGW link to standard C library

I have a problem with following code.

extern printf
global _main
main:
push msg
call printf
ret
msg db "Hello world",0

I assemble this with NASM using nasm -fwin32 test.asm Then i link it using ld test.obj. And it tells me "test.obj:test.asm:(text+0x6): undefined reference to 'printf'"

How to link my file to standard C libraries? I have ld from latest MinGW.

like image 441
Smax Smaxović Avatar asked Aug 31 '25 03:08

Smax Smaxović


1 Answers

To assemble code :

nasm -fwin32 test.asm

Microsoft will prefix functions using the cdecl calling convention with a underscore.
To be match to the C calling convention printf should be _printf.
The same applies for _main instead of main.

And link with:

ld test.obj -lmsvcrt -entry=_main -subsystem=console -o test.exe

Here -entry command line option is used to invoking ld to specify the entry point for program .
Then use -l options to pass msvcrt library to the ld linker, otherwise you will get an error message, (undefined reference to `printf') which means that the linker did not found the symbol printf in the specified object file produced by NASM.

Here is completed source:

global  _main
extern  _printf
section .text
_main:
push msg
call _printf
add esp, 4 ;adjust the stack
ret
msg db "Hello world",0
like image 140
boleto Avatar answered Sep 02 '25 17:09

boleto