Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 477
CorkiMain Avatar asked Aug 29 '26 21:08

CorkiMain


1 Answers

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
like image 143
fuz Avatar answered Aug 31 '26 23:08

fuz