I need to write some constants in different files with some integer id. For instance:
#define MESSAGE_FIRST 0
In another file:
#define MESSAGE_ANOTHER 1
Any ways to automatically get this id at compile time? Sort of:
#define MESSAGE_AUTO GetNextId()
I can not use the enumerations here, because these directives will be in different files.
Thank.
ps GCC, Linux
You can make a compile-time counter with an overload of inheritance and functions:
template<unsigned int n> struct Count { bool data[n]; }; template<int n> struct Counter : public Counter<n-1> {}; template<> struct Counter<0> {}; Count<1> GetCount(Counter<1>); #define MAX_COUNTER_NUM 64 #define COUNTER_VALUE (sizeof(GetCount(Counter<MAX_COUNTER_NUM + 1>())) / sizeof(bool)) #define INC_COUNTER Count<COUNTER_VALUE + 1> GetCount(Counter<COUNTER_VALUE + 1>);
You can see it in action here . Also works with msvc.
, GCC. GCC (AFAIK per-file) __COUNTER__, .
__COUNTER__
, ++.
:
enum { FIRST = 0, SECOND, THIRD };
, , :
#define FIRST 0 #define SECOND (1 + FIRST) #define THIRD (1 + SECOND)