Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested macro calls

Trying to have nested macro calls as below:

#include <stdint.h>

#define INT
#define LONG

#define AS(t) AS_##t
#define AS_INT as_int
#define AS_LONG as_long

#define LET(v, t) v. AS(t)

typedef union
{
    int32_t as_int;
    int64_t as_long;
} mytype_t;

int main()
{
    mytype_t s;

    s.AS(INT) = 10;    /* This is OK */

    LET(s, INT) = 10;  /* This makes error */

    return 0;
}

It makes error:

main.c:xx:yy: error: ‘mytype_t {aka union <anonymous>}’ has no member named ‘AS_’
 #define LET(v, t) v. AS(t)
                    ^
main.c:zz:ww: note: in expansion of macro ‘LET’
     LET(s, INT) = 10;
     ^~~

Is there any workaround to have LET(s, INT) = 10; ?

like image 327
masoud Avatar asked Mar 03 '23 17:03

masoud


1 Answers

It's these two empty macros

#define INT
#define LONG

INT when passed into AS(t) via LET undergoes intermediate expansion, and is expanded to an empty token sequence before AS() itself is expanded. As such you concatenate AS_ with an empty token sequence. Just drop these two macros, having AS_INT and AS_LONG defined is enough for your example.

like image 166
StoryTeller - Unslander Monica Avatar answered Mar 12 '23 05:03

StoryTeller - Unslander Monica