Author Topic: Simple Macro Question  (Read 8321 times)

nobody

  • Guest
Simple Macro Question
« on: August 24, 2009, 06:25:00 PM »
What is a macro?

Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: Simple Macro Question
« Reply #1 on: August 28, 2009, 08:35:25 AM »
Well... it's a text substitution. At its simplest:

%define BUFSIZ 128

... and then you use "BUFSIZ" instead of "128" throughout your program - makes it easy to change, and "128" doesn't have much meaning without some "context". Typically, there are a flock of these stuffed into a "win32.inc" or "linux.inc" which you "%include". Then you can use "WM_MESSAGEBOX_OK" or "O_RDONLY" without having to remember the numbers (both 0 :). I sometimes call this "long names for small integers". Nasm knows a bunch of "built in" macros - Nasm version, bits, output format, date and time...

More complex macros emit more than one instruction - perhaps different instructions under different conditions - sometimes nothing. For example:

%macro dbgdump 0 ; no parameters
%ifdef DEBUG
call dumpregs
call dumpstack
%endif
; else do nothing
%endmacro

; code sprinkled with "dbgdump"

%ifdef DEBUG
; code for "dumpregs" and "dumpstack"
%endif

Now if we assemble this with "nasm -f ??? -dDEBUG myprog.asm", we'll "tell everything we know", and if we assemble without "-dDEBUG", that code completely disappears. Macros that don't emit anything are my favorite kind! :)

Macros can be used to emit code to emulate "high-level constructs", IF/ELSE, WHILE/ENDWHILE, REPEAT/UNTIL, SWITCH/CASE... things like that. The famous "PROC" macro mostly defines convenient names for parameters which you can use instead of "ebp + ???" (Nasm remembers what the "???" is, so we don't have to). "INVOKE" replaces "push/push/push/call" and perhaps cleans up the stack afterwards... I really feel that a person should learn to code these things "by hand" before resorting to macros, but they simplify the code... once you understand what they're "hiding".

There's a considerable section in the Friendly Manual on the subject:

http://www.nasm.us/doc/nasmdoc4.html

I suspect you'll need to read it more than once, interspersed with some observation of example macros and plenty of trial and error, to get anywhere with it. I find it "difficult", anyway. But it's just text substitution...

Did you have some particular macro in mind?

Best,
Frank