Search code examples
assemblygccgnu-assembler

.S assembly code Macro to apply another macro to multiple registers in .S


In .S assembly code, I want to write a macro that takes as "argument" another macro, that is then applied to multiple registers. A minimal example would be:

.macro add_macro reg1 reg2
    add reg1 reg2
.endm

.macro apply_macro func reg1 reg2
    func reg1
.endm

test_rax:
    apply_macro add_macro %rax, %rdi

However, when I want to compile this macro, it does not work:

gcc test.S -c -o test.o
test.S: Assembler messages:
test.S:10: Error: no such instruction: `func reg1'

Is there any way to define a macro that applies another macro to certain registers? Note that for the use case at hand, I have to use a macro and cannot use a function.


Solution

  • when I want to compile this macro, it does not work: test.S:10: Error: no such instruction: `func reg1'

    That's because the apply_macro body doesn't do any parameter substitutions. The following edited variant of your macros work for me:

    .macro add_macro reg1 reg2
        add \reg1, \reg2
    .endm
    
    .macro apply_macro func reg1 reg2
        \func \reg1 \reg2
    .endm
    
    test_rax:
        apply_macro add_macro %rax %rdi