Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define in inline assembly in GCC

I'm attempting to write inline assembly in GCC which writes a value in a #define to a register.

#define SOME_VALUE  0xDEADBEEF

void foo(void)
{
    __asm__("lis r5, SOME_VALUE@ha");
    __asm__("ori r5, r5, SOME_VALUE@l");
}

However, I get an error when I compile:

undefined reference to `SOME_VALUE'

Is there a way for the assembler to see the #define in the inline assembly?

I've solved it by doing the following:

#define SOME_VALUE  0xDEADBEEF
__asm__(".equ SOME_VALUE,   0xDEADBEEF");

void foo(void)
{
    __asm__("lis r5, SOME_VALUE@ha");
    __asm__("ori r5, r5, SOME_VALUE@l");
}

However, I really don't want to duplicate the value.


1 Answers

Use some preprocessor magic for stringification of the value and the string continuation in C:

#define SOME_VALUE  0xDEADBEEF
#define STR(x) #x
#define XSTR(s) STR(s)

void foo(void)
{
    __asm__("lis r5, " XSTR(SOME_VALUE) "@ha");
    __asm__("ori r5, r5, " XSTR(SOME_VALUE) "@l");
}

XSTR will expand into the string "0xDEADBEEF", which will get concatenated with the strings around it.

Here is the demo: https://godbolt.org/z/2tBfoD

like image 196
Eugene Sh. Avatar answered Sep 02 '25 15:09

Eugene Sh.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!