Personally I love macros and what spurred me to write this was my adventure today while I was remapping the PICs for my hobby O/S.
So what is a macro in assembly?
When the assembler encounters a macro label in your source code, it replaces the label with the text lines that the macro label represents. Also called 'expanding the macro'.
A macro definition is stored between a %macro and %endmacro directive.
%macro ... %endmacro
Now after the %macro will be our label then followed by the number of parameters.
%macro mymult 2 ... %endmacro
So we named our macro 'mymult' and said it will take two parameters but how do we use these parameters?
%macro mymult 2 mov ecx, %2 mov eax, %1 ... %endmacro
Basically this says to copy the first parameter or %1 into eax and copy the second parameter or %2 into ecx.
Pretty simple huh? Ok now for the rest of the code.
%macro mymult 2 mov ecx, %2 mov eax, %1 dec ecx .loop: add eax, %1 dec ecx jnz .loop %endmacro
Cool now how do we call it? It's easy just use the label 'mymult', no need for a call.
mymult 2, 4
Another reason to use macro is when you have a bunch of similar pieces of code to write many times.
Such as writing IRQs when remapping a PIC. If you don't understand the code itself don't worry just watch how I use macros to my advantage.
global _irq0 _irq0: cli push byte 0 push byte 32 jmp irq_common_stub ;All the way to... global _irq15 _irq15: cli push byte 0 push byte 47 jmp irq_common_stub
You'll notice there's only a few numbers that are changing.
So instead I just make a macro and let it do the work.
%macro Irq 2 global _irq%1 _irq%1: cli push byte 0 push byte %2 jmp irq_common_stub %endmacro Irq 0, 32 Irq 1, 33 Irq 2, 34 ... Irq 15, 47
So when the assembler hits this for instance
Irq 0, 32It will turn it into
global _irq0 _irq0: cli push byte 0 push byte 32 jmp irq_common_stub
And it'll continue to do that for the rest of them.
So why do this? Why not just write a procedure? Well both ways have there pros and cons.
Macros are fast, there's no call or ret instruction the only instructions used are the one's actually doing work. However if there is a speed increase in code what does that usually tell us about memory?
Well let's say we have a macro that does 4 instructions and that macro is called 3 times. That's 12 instructions generated into memory.


Sign In
Create Account


Back to top









