On Mon, Aug 1, 2016 at 4:13 PM, VinÃcius dos Santos Oliveira
...I want my library header only and Boost.System requires the category to be a single static object and it'll even use address comparison to test if the categories are the same: ... Is it guaranteed the above code will return the same object even if this code was included in different libraries used by the same program?
Sorry for the late reply. This header-only idiom works:
inline
boost::system::error_category const&
my_category()
{
struct my_error_category : boost::system::error_category { ... };
static my_error_category cat;
return cat;
}
This idiom also works:
template
From the C++ standard (see https://isocpp.org/std/the-standard)
7.1.6 describes inline functions. It says they must exist in every TU that they are used in, and must be the same in all TUs (no diagnostic required). 7.1.6 p6 also states that the address of an (extern) inline function shall be the same in all TUs. Elsewhere, the standard specifies that inline functions are extern by default. Empirical evidence also supports these claims, both of the aforementioned idioms have been used extensively in my projects under gcc, clang, and msvc. This likely upcoming feature (maybe its already in?) further cements support for global variables in header-only libraries: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4424.pdf However, even in the absence of additional language features, the ability to have global variables in header-only libraries exists today, with nothing more than C++11 support. Hope this helps!