masoud
masoud

Reputation: 56479

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; ?

Upvotes: 4

Views: 641

Answers (2)

Jona
Jona

Reputation: 1288

It has been answered that the error was due to empty macros.

Another solution can be:

#define INT INT
#define LONG LONG

Hope this helps.

Upvotes: 1

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.

Upvotes: 6

Related Questions