Matthew Sainsbury
Matthew Sainsbury

Reputation: 1488

Nasm: Macros not expanded as operands to instructions

I wrote a small bit of assembly for nasm like this:

%macro register 1
    %if %1 = 0
        rax
    %elif %1 = 1
        rbx
    %elif %1 = 2
        rcx
    %endif
%endmacro

add register(1), register(2)

I expect that to evaluate to add rbx, rcx

However, nasm -E test.asm returns this, showing that the macro is not evaluated:

%line 10+1 test.asm

add register(1), register(2)

Compare that to this code:

%macro register 1
    %if %1 = 0
        rax
    %elif %1 = 1
        rbx
    %elif %1 = 2
        rcx
    %endif
%endmacro

register(1)

which is transformed into

%line 10+1 test.asm

rbx

Why the difference? How can I achieve what I expect in the first snippet?

Upvotes: 2

Views: 657

Answers (1)

Jester
Jester

Reputation: 58762

You need to use single-line macros for this, as they are expanded differently:

%define register_1 rax
%define register_2 rbx
%define register_3 rcx
%define register(x) register_ %+ x

add register(1), register(2)
$ nasm -E t4.asm
%line 1+1 t4.asm

%line 6+1 t4.asm

add rax, rbx

Upvotes: 2

Related Questions