bilsch01 wrote:
Ah... fools rush in... I just can't resist.
> I got a simple example of calling printf() from assembly program (see
> below). It doesn't tell me how to include a library with printf() in
> it. So it gives the error:
>
> undefined reference to `printf'
>
> What is NASM equivalent of #include <stdio.h>. How do I do it? I used
> command line:
> nasm -felf64 asmprintf.asm && ld -m elf_x86_64 asmprintf.o -o asmprintf
Easy way: ... && gcc -o asmprintf asmprintf.o (this will link in some
"startup" code which "call"s main, as well as libc)
Or... tell ld "-lc". ("-l" being library and "c" being libc.so). Your
default entrypoint would still be "_start", so you'd need to tell ld
"-emain" too. And you can't "ret" from "_start" (it isn't "call"ed!) so
end with sys_exit or exit(). The 32-bit ld tries to use a nonexistanf
"interpreter" or "dynamic linker" so you have to correct that, too, but
I don't think you'll run into that in 64-bit. Really - easier to use gcc
(but you don't "have" to).
You may need to align the stack before calling printf, and clean it up
after, too. I'm not sure about 64-bit code.
Best,
Frank
> ; Equivalent C code
> ; /* printf1.c print a long int, 64-bit, and an expression */
> ; #include <stdio.h>
> ; int main()
> ; {
> ; long int a=5;
> ; printf("a=%ld, rax=%ld\n", a, a+2);
> ; return 0;
> ; }
>
> ; Declare external function
> extern printf ; the C function, to be called
>
> SECTION .data ; Data section, initialized variables
>
> a: dq 5 ; long int a=5;
> fmt: db "a=%ld, rax=%ld", 10, 0 ; The printf format, "\n",'0'
If you use "back quotes", Nasm understands `\n`, etc.