I'd like to have a C pre-processor macro to call which increments a constant each time it is called. Obviously the following does not work: #define ID 0 // initially ...then #define ID ID+1 // each time I need a new constant Is there any trick to solve this seemingly simple problem, even with more than one macro. thx. PS: I cannot use a variable, because the ID has to be incremented across functions.
Are you trying to implement some kind of unique ID feature? I would typically use something like this int makeUniqueID ( void ) { static int id = 0; return ++id; } Each time you want another ID, call the function. > Is there any trick to solve this seemingly simple problem, even with more than one macro. It's doubtful. The pre-processor is after all just a 'stream editor' which inserts files through #include, and performs simple text substitutions through #define. It doesn't have an internal state you can access.
They have to be unique IDs, but furthermore they have to be statically assigned at compile time, not runtime. Therefore I cannot call a function which would only generate the ID when it is hit, and which would increment multiple times each time the encompassing function runs. That's why I was looking at macros, but like you said, they are very limited in that respect. You can have: #define X 5 #define Y ((X)+1) but not: #define ID 0 #define ID (ID+1) we need an eval() ;-) thx anyway.
The way I've solved this kind of problem in the past is to use some kind of Perl script (or another scripting language of your choice) to 'edit' the code in certain predefined ways. For example, create a magic comment, say #define ID 0 /*--Next Unique ID--*/ When your script sees the magic comment, it can edit the line and write out the line with the actual unique ID in place of the 0.
hey! you have invented the pre-pre-processor !! I will think it over. Actually what I'd like to do is more general, like: ________________ sender file: f() { ... #ID #LABEL "text" send(ID); ... } _________________ receiver file: g() { ... id=receive(); str=lookup(id) printf(str); // magic is that str is the LABEL we defined on the sender for this id. ... } _________________ I want the lookup table in the receiver end to be automatically generated from the sender file so that the ID are always in sync. You understand that I was alreaday blocked at the very beginning of my endeavour ;-) Now that you open up with perl, everything seems possible!
Hi, I think you can follow the following logic to redefine a macro.Whenever u want to increment the value of macro u might use this way: #ifdef ID #undef ID #define ID ID + 1 #endif Thanks,