NASM - The Netwide Assembler

Please login or register.

Login with username, password and session length
Advanced search  


Author Topic: printf and scanf in nasm  (Read 5752 times)


  • Guest
printf and scanf in nasm
« on: October 21, 2005, 09:04:25 AM »

i know the basic ideas of using print and scanf in nasm, but can anyone point me to a good resource on how to use these in nasm or maybe give an in depth explanation.

Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Offline Offline
  • Posts: 2102
Re: printf and scanf in nasm
« Reply #1 on: October 21, 2005, 02:17:23 PM »

... probably the best info you'll find on interfacing Nasm with C. Some C reference, for the intricacies of "printf" and "scanf", and other libc functions, I suppose...

You know that you've gotta push the parameters, "last" one first, format-string last. Then call the function. Then clean up the stack.

One tricky bit about printf - it expects all floats to be doubles, even if you say "%f" in the format string. So something like "fld dword [my_single_float]"/"sub esp, 8"/"fstp qword [esp]" to get it on the stack...

The "\n" in the format string is apparently converted to LF or CR/LF by the C preprocessor, which may not be involved here, so...

format db 'answer: %f', 10, 0

instead of...

format db 'answer: %f\n', 0

With scanf, "%f" expects the *address* of where to store a float (IIRC, K&R refer to this as "the most common error"). I found scanf to be a horrid function to use, even from C - if the user doesn't provide exactly the expected input, any "extra" gets left on the input queue and is picked up by later parameters to scanf, or subsequent calls. I usually went with "fgets" followed by "atof" or whatever to evaluate it. I've never used scanf from asm, and would jump through hoops to avoid it. Maybe it's okay if you know what you're doing...

Unless it's for ELF, C expects external functions to start with an underscore. As I recall, Dr. Carter's examples use "_printf" throughout, and define "_printf" as just "printf" if ELF is in use. I'd have done it the other way around - use just "printf" in my source and "%define printf _printf" if you want it. Or you could do "--PREFIX _" on Nasm's command line to add an underscore to anything declared "extern" or "global". (But then, I use ELF by default...) You didn't believe that this stuff was *really* portable, did you? :)

That's about all I know about it.