Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to use extern for constants anymore?

Tags:

c++

c++20

In my earlier days I often had constructs like:

// .h
extern const int MY_CONST;

// .cpp
const int MY_CONST = 5;

Is it true that this is completely superseded by:

// .h
inline const int MY_CONST = 5;

Is there any reason to use the first variant nowadays?

Note that the latter has higher readability because the value is visible in the header file (self-documenting).

like image 504
D.R. Avatar asked Dec 22 '22 16:12

D.R.


1 Answers

Certainly. For the same reasons as one might want to define anything in separate translation unit. Same reasoning applies to function definitions for example.

For example, a reason may be to remove the need to recompile everything depending on the variable in case you want to change the initialiser.

Another reason may be that initialisation is complex and involves call to a function that you wish to hide because you may not want the dependency to be public.

like image 146
eerorika Avatar answered Jan 12 '23 08:01

eerorika