Tuesday, November 11, 2014

Assembly Tutorial 2: Include Files and Macros

The code for this tutorial can be found at https://github.com/musicman89/Assembly-Tutorial
Tutorial 1: Intro to x86 Assembly

The last segment of this series covered an introduction into the world of assembly programming.  It also was a bit winded.  Today I am going to keep it a little shorter and we will cover a relatively simple topic that often is overlooked when starting in assembly.  That topic would be macros, since what I am going to cover is quite short I will also talk briefly about include files.

Lets get started with Macros

A macro is simply a statement that is processed by the compiler.  This can be from a simple variable, a string of statements, or even mathematical functions.

First there is the single line macro.  A single line macro is exactly what it sounds a macro defined in a single line, we define them using the %define directive. 

For example, we could write %define LightGrayOnBlack 0x07, this would allow us to put LightGrayOnBlack in our code rather than writing 0x07 when printing a character to the screen.  Though the compiled code is identical, this is much easier to read and debug.

We could also write %define Poly(a,b) ((a*a) + b + 2) so if we later in our code put Poly(2,3) it would output 9 into our assembled code.  

Now for the multiple line macro.  This operates on the same rules as the single line macro, but has multiple lines.  This is useful when you have a task you do often like calling a function.  We could write the following macro to prep a string to be printed using the function we wrote in the last tutorial.

%macro Print 1
     mov bx, %1
     call print_string
%endmacro

Now when we type Print HelloWorldString it outputs the assembly instructions for us using the macro.  Also note from this example the format of parameters.

In a multiple line macro they are numbered.  You simply put the number of parameters you expect after the name and then you reference them by number of the parameter preceded by %.

There are lots of additional features to macros that can be found in the NASM manual in Chapter 4.

Now for Include Files

Include files are quite similar to macros as they tell the compiler to rather than include a line or two, that it needs to insert an entire file at that point.  An include is given using the %include directive.  Using this we can extract our print functions from the Hello World example and put them in their own file.

When compiling though you must keep in mind that for relative paths to include files to work the compiler must be run from the location they are relative to.  Either that or you need to use the -i parameter on the compiler to define the path.

No comments:

Post a Comment