Search code examples
goassemblyconstants

Go Assembler Named Constants


Is there a way to name constant values in Go Assembly? I'd like to name some constants to make my code more readable.

I am looking for something that works like #define in C or .equ in Arm64 assembly. Here's an example of what I'd do in those languages:

C
#define myConstant 2024

Arm64
.equ myConstant, 2024

I've tried using #define in Go Assembly, but I can only get it to work for entire instructions. Here's an example of that:

#define MyInstruction     MOVD R1, R2
#define OtherInstruction  WORD $0xaabbccee

When I try to just make and use #define with a constant this happens:

Code

#define myConstant        WORD $2024
MOVD    R1, myConstant(R0)

Compiler Error

myFile:49: expected '(', found $
asm: assembly of myFile.s failed

Solution

  • The Go assembler runs a variant of the C preprocessor on your code. I.e. what you define with #define will literally be searched and replaced in your code. So if you write

    #define myConstant        WORD $2024
    
    ...
    
    MOVL myConstant, EAX
    

    the result will be something like

    MOVL WORD $2024, EAX
    

    which is clearly nonsensical.

    To fix this, change your macro to read just

    #define myConstant 2024
    

    and use it as if it was a symbol

    MOVL $myConstant, EAX