Maty
Maty

Reputation: 30

C Macro Whitespace

I am unable to accomplish the following because whitespaces are ignored(?) in the preprocessor. I understand that this is part of the standard, but I'm wondering if there's a work around using variadic or some indirect macro trick.

Variable:

#define DECL_INT(name) int #name

DECLR_INT(myValue);
// Expected: int myValue;
// Actual: intmyValue;

Structure:

#define ADD_CUSTOM_MEMBERS() \
   C_MEM(IntMember, int) \
   C_MEM(CharMember, char)

#define C_MEM(name, type) type #name;

typedef struct {
   int Stuff;

   ADD_CUSTOM_MEMBERS()
   // Expected: int IntMember;
   //           char CharMember;
} my_struct_t;

The goal is to have a generic structure that then each application can add its own members to it, natively.

There is a lot of information out there on white-spaces and macros, but I haven't seen anyone directly address this issue. I've seen plenty of examples where a prefix is added.

#define DECL_INT(name) int myPrefix_#name

DECLR_INT(myValue);
// Actual: int myPrefix_myValue;

Doing it this way keeps the whitespace between int and myValue, but I don't want a prefix.

And assuming adding a prefix is the only way of achieving this, I can't use this trick to declare a variable with the type as one of the arguments of the macro.

Upvotes: 1

Views: 331

Answers (1)

KamilCuk
KamilCuk

Reputation: 140990

You have an erroneus #. Without it:

#define ADD_CUSTOM_MEMBERS() \
   C_MEM(IntMember, int) \
   C_MEM(CharMember, char)

#define C_MEM(name, type) type name;

typedef struct {
   int Stuff;

   ADD_CUSTOM_MEMBERS()
   // Expected: int IntMember;
   //           char CharMember;
} my_struct_t;

outputs with gcc -E:

typedef struct {
   int Stuff;

   int IntMember; char CharMember;

} my_struct_t;

Upvotes: 2

Related Questions