ALT by Bilal Ahmed Shaik - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

img190.png

 

  Assembly Macros

 

  Writing a macro is another way of ensuring modular programming in assembly language.

 

   A macro is a sequence of instructions, assigned by a name and could be used anywhere in the program.

 

   In NASM, macros are defined with %macro and %endmacro directives.

 

   The macro begins with the %macro directive and ends with the %endmacro directive.

 

  The Synta x for macro definition:

 

img191.png 

  Where, number_of_params specifies the number parameters , macro_name specifies the name of the macro.

 

  The macro is invoked by using the macro name along with the necessary parameters. When you need to use some sequence of instructions many times in a program, you can put those instructions in a macro and use it instead of writing the instructions all the time.

 

  For example, a very common need for programs is to write a string of characters in the screen. For displaying a string of characters, you need the following sequence of instructions:

 

img192.png 

  We have observed that, some instructions like IMUL, IDIV, IN T etc., need some of the information to be stored in some particular registers and even returns values in some specific register(s). If the program was already using those registers for keeping important data, then the existing data from these registers should be saved in the stack and restored after the instruction is executed.

 

  In the above example of displaying a character string also, the registers EAX, EBX, EC X and EDX we will used by the INT 80H function call. So for each time you need to display on screen, you need to save these registers on the stack, invoke INT 80H and then restore the original value of the registers from the stack. So it could be useful to write two macros for saving and restoring data.

 

  Example:

 

  Following example shows defining and using macros:

 

img193.png 

  When the above code is compiled and executed, it produces fol owing result:

 

img194.png