Home >Backend Development >C++ >How Do C 17 Inline Variables Solve External Linkage Issues?
Understanding Inline Variables in C 17
In 2016, the C Standards Committee introduced inline variables as part of the C 17 standard. This feature enables the creation of external linkage variables that can be defined in a header file and referenced across multiple translation units without incurring linker errors.
How Inline Variables Work
The inline specifier applied to a variable allows it to have external linkage, meaning that multiple definitions of the variable in different translation units are permitted. When multiple definitions exist, the linker will select one of them and ignore the others.
Declaring, Defining, and Using Inline Variables
Inline variables should be declared as static and may be defined in the class definition or namespace scope. They can be initialized using a brace-or-equal initializer or via a separate redeclaration without an initializer if they are declared with the constexpr specifier. For example:
struct Kath { static inline std::string const hi = "Zzzzz..."; };
This code declares a static inline variable named hi in the Kath struct. The variable is initialized with the value "Zzzzz..." and can be accessed using Kath::hi from any translation unit that includes the header where it is defined.
Benefits of Inline Variables
Inline variables provide several advantages:
The above is the detailed content of How Do C 17 Inline Variables Solve External Linkage Issues?. For more information, please follow other related articles on the PHP Chinese website!