Is there anything like a preprocessor variable in C? It could simplify my definitions.
Currently I have something like this:
typedef struct mystruct {
int val1;
int val2;
int val3;
int val4;
} MYSTRUCT;
typedef struct mysuperstruct {
MYSTRUCT *base;
int val;
} MYSUPERSTRUCT;
#define MY_OBJECT_BEGIN(name, val1, val2, val3, val4) \
MYSTRUCT name##Base = { val1, val2, val3, val4 }; \
MYSUPERSTRUCT * name##Objs = {
#define MY_OBJECT_VALUE(name, val) \
{ &(name##Base), val },
#define MY_OBJECT_END() \
NULL \
};
It is used this way:
MY_OBJECT_BEGIN(obj1, 1, 2, 3, 4)
MY_OBJECT_VALUE(obj1, 5)
MY_OBJECT_VALUE(obj1, 6)
MY_OBJECT_VALUE(obj1, 7)
MY_OBJECT_END()
Which generates something like this:
MYSTRUCT obj1Base = { 1, 2, 3, 4 };
MYSUPERSTRUCT * obj1Objs = {
{ &(obj1Base), 5 },
{ &(obj1Base), 6 },
{ &(obj1Base), 7 },
NULL
}
It's obvious that repetitive use of the object name is redundant. I would like to store the name in the MY_OBJECT_BEGIN definition to some preprocessor variable so that I can use it the following way:
MY_OBJECT_BEGIN(obj1, 1, 2, 3, 4)
MY_OBJECT_VALUE(5)
MY_OBJECT_VALUE(6)
MY_OBJECT_VALUE(7)
MY_OBJECT_END()
Does standard C preprocessor provide a way to achieve this?
There are 4 Main Types of Preprocessor Directives: Macros. File Inclusion. Conditional Compilation. Other directives.
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation (Proprocessor direcives are executed before compilation.).
The C preprocessor is the macro preprocessor for the C, Objective-C and C++ computer programming languages. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control.
## is Token Pasting Operator. The double-number-sign or "token-pasting" operator (##), which is sometimes called the "merging" operator, is used in both object-like and function-like macros.
There are no standard C preprocessor variables. As Oli Charlesworth suggested, using X-Macros is probably your best bet if you want to keep it just with standard C. If there really is a lot of associated data that would touch several files, you'll want to use a code generator like GNU autogen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With