The inline
keyword in C++ allows functions to be defined in headers so that the compiler can either actually inline them or leave only one copy of the function. This allows reducing the number of compilation units by defining the functions directly in headers, with the advantage of often several times faster compilation time and possibly faster execution.
Why can't this same pattern be applied to namespace-scope variables, while functions in C++ actually are namespace-scope variables when viewing them as a special pointer?
What I can think of is using a static local variable of an inline function.
inline std::string& Hello__() { //Edit: Added the &
static std::string hello("Hello");
return hello;
}
#define Hello (Hello__())
Edit: I'd like to clarify my question as below.
I'm using the term 'inline' as what the compiler understands. It lets the same definition with the same name be in multiple compilations units, allowing the definition in the header. The main advantage of 'inline' is not the performance benefit as a macro function would have but the shorter compilation time from the reduced number of compilation units. It can possibly be several times shorter.
I did come out with a solution to let a variable work like an inline function. But I am still finding for a better way to do this.
To state again clearly, what I want to achieve is defining a namespace-scope variable in the header like an inline function, in order to make the build process as simple and fast as possible.
Edit2: Thank you for the link in the comment by dyp. I've just read the proposal, and that is exactly what I am thinking of. What is the current status of that proposal?
Quoted from the proposal:
However, it is not uncommon to desire the existence of a globally unique object without having to pick a single translation unit in which to define it. As a practical matter, making this choice generally requires either the use of nontrivial preprocessor macros, separately compiled libraries, or both. However, one strength of C++ is its ability to support the development of headeronly libraries. In this vein, the lack of the ability to define an inline variable poses a significant constraint on library design.
Variables actually can be
inline
d, but they would not be globally the same then.zzz.h:
xxx.cpp:
zzz.cpp:
Let's see if it compiles altogether: