Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing operands/parameters in GNU assembler macros

I am currently trying to understand the concept of macros in the assembly language, specifically in GNU assembler, AT&T syntax for IA-32 (x86). The slides from my university say the following:

# How to define a macro:
.macro write string
    movl string, %esi
    call printstr
.endm

# How to use a macro:
write aString

However, this doesn't work for me. I am using gcc to compile my code.

.data
    msg:    .string "The result is %d.\n"

.text
.global main

.macro add_3 n
    movl n, %eax
    addl $3, %eax
.endm

main:
    add_3 $39
    pushl %eax
    pushl $msg
    call printf
    popl %eax
    popl %eax
    movl $1, %eax
    int $0x80

When I try to compile this, I get the following error:

undefined reference to `n'

What exactly am I doing wrong?

like image 845
lkbaerenfaenger Avatar asked Nov 04 '13 09:11

lkbaerenfaenger


People also ask

How do you name each operand in assembly language?

Each operand has this format: Specifies a symbolic name for the operand. Reference the name in the assembler template by enclosing it in square brackets (i.e. ‘ % [Value] ’). The scope of the name is the asm statement that contains the definition.

Can two operands have the same symbolic name in ASM?

No two operands within the same asm statement can use the same symbolic name. When not using an asmSymbolicName, use the (zero-based) position of the operand in the list of operands in the assembler template.

How do you reference a variable in assembler?

Reference the name in the assembler template by enclosing it in square brackets (i.e. ‘ % [Value] ’). The scope of the name is the asm statement that contains the definition. Any valid C variable name is acceptable, including names already defined in the surrounding code.

What is the Order of the operands in the assembler?

The Intel assembler uses the opposite order (destination<-source) for operands. Operands can be immediate(that is, constant expressions that evaluate to an inline value), register(a value in the processor number registers), or memory(a value stored in memory). An indirectoperand contains the address of the actual operand value.


1 Answers

To reference arguments inside the macro, prepend the name with a backslash. For example:

.macro  add_3  n
    movl \n + 3, %eax
.endm

GAS manual: https://sourceware.org/binutils/docs/as/Macro.html

like image 79
3 revs, 3 users 67% Avatar answered Oct 01 '22 19:10

3 revs, 3 users 67%