Which one is the best in const int, extern const int, inline constexpr?

Viewed 72

I have a header file where some #define constants(all integers) are there. I wanted to replace #define constants with extern const int and then define them in separate file. But it so happened that some of the #define constants are being used as size of array. So for these constants I cannot replace by extern const int. So I had to find something else to make this work and I found two solutions but cannot decide which is better.

  1. Replace each #define const by const int. Only problem is that const int has internal linkage so ultimately I will be having multiple copies across different translation units resulting in multiple storage which I want to avoid. But then again the compiler may optimise this by replacing each const int usage with its value and ultimately no storage will be used for the cost ints.
  2. The other option is inline constexpr(came across this while trying to find solutions). In this case it is guaranteed that only one copy will be retained by the linker.

So inline constexpr looks better but then again when I start to think of optimisation in the first case then both look good.

Please provide suggestions and also reasons for it.

1 Answers

constexpr is the usual way to do it, unless you do not have C++11 support in which case you can do this:

enum { MYCONST = 120 };
Related