#define in inline assembly in GCC

1

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.

c
assembly
embedded
inline
asked on Stack Overflow Sep 26, 2018 by zsnafu

1 Answer

5

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

answered on Stack Overflow Sep 26, 2018 by Eugene Sh.

User contributions licensed under CC BY-SA 3.0