Max Frai
Max Frai

Reputation: 64366

Integer values in compile time

I have to write some constants in different files with some integer id. For example:

#define MESSAGE_FIRST 0

In other file:

#define MESSAGE_ANOTHER 1

Any ways to get that id automatically in compile time? Something like:

#define MESSAGE_AUTO GetNextId()

I can't use enums here because this directives will be in different files.

Thanks.

p.s. GCC, Linux

Upvotes: 5

Views: 830

Answers (2)

orlp
orlp

Reputation: 117846

You say you are using GCC. GCC has the (AFAIK per-file) macro called __COUNTER__ that increments by one after every use.

Note that this is an extension and not included in standard C++.

Another option is using an enum:

enum {
    FIRST = 0,
    SECOND,
    THIRD
};

Or you can do this manually using preprocessor directives like this:

#define FIRST 0
#define SECOND (1 + FIRST)
#define THIRD (1 + SECOND)

Upvotes: 1

Synxis
Synxis

Reputation: 9388

You can do a compile-time counter, with inheritance and function overloading:

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.

Upvotes: 5

Related Questions