Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC macro expansion arguments inside string

Tags:

c

gcc

macros

I have a situation like this

#define PRE 0xF1

#define SR0 0B0000
#define SR1 0B0001
#define SR2 0B0010
#define SR3 0B0011

#define VIOTA(A0)  asm(".byte PRE, A0")

int main()
{
  VIOTA(SR1);
  return 0;
}

I have a top-level macro that expands out however the expansion contains more macros. These aren't being expanded and causing some problems.

The behaviour that I desire is that the end expansion is

asm(".byte 0xF1, 0B0000")

Here the inner macros have been expanded. I'm really not sure what I'm doing wrong at all. Any advice?

like image 530
Jimmy Cracked Corn Avatar asked Jul 13 '11 22:07

Jimmy Cracked Corn


2 Answers

#define S(x) #x
#define SX(x) S(x)

#define VIOTA(A0) asm(".byte " SX(PRE) ", " SX(A0))

See details here: C Preprocessor, Stringify the result of a macro

like image 195
Karoly Horvath Avatar answered Oct 10 '22 04:10

Karoly Horvath


Use the stringizing operator # to convert tokens into strings. However, since the stringizing operator can only be applied to macro parameters, you need to add some extra layers of macros:

#define PRE 0xF1

#define SR0 0B0000
#define SR1 0B0001
#define SR2 0B0010
#define SR3 0B0011

#define VIOTA(A0) VIOTA_HELPER1(PRE, A0)
#define VIOTA_HELPER1(PRE, A0) VIOTA_HELPER2(PRE, A0)
#define VIOTA_HELPER2(PRE, A0) asm(".byte" #PRE ", " #A0)

int main(void)
{
  VIOTA(SR1);
  return 0;
}

After preprocessing, this expands to this:

int main(void)
{
  asm(".byte " "0xF1" ", " "0B0001");
  return 0;
}

String constants get concatenated at compile time, so this is equivalent to asm(".byte 0xF1, 0B0001");.

like image 26
Adam Rosenfield Avatar answered Oct 10 '22 04:10

Adam Rosenfield