Example 2

Example 2 expands upon the previous example and demonstrates how to wrap your library's APIs in a C++ namespace header-only library while still including global variables:

// Contents of library.h

namespace library_name
{
namespace details { inline int answer = 42; }

int my_api() { return details::answer; }
// ...
}

// Contents of main.cpp

#include <iostream>

int main(void)
{
using namespace library_name;

std::cout << "The answer is: " << my_api() << ' ';
return 0;
}

As shown in the preceding example, C++17 was leveraged to create an inline global variable that is wrapped in our library's namespace. inline variables are needed as header-only libraries don't have a source file to define global variables; without the inline keyword, defining a global variable in a header would result in the variable being defined multiple times (that is, the result would be a linking error during compilation). C++17 resolved this issue by adding inline global variables, which allows a header-only library to define global variables without the need for tricky magic (such as returning a pointer to a static variable from a singleton style function).

In addition to the library's namespace , we wrapped the global variable in a details namespace. This is done to create a private place within your library in case the user of the library declares using namespace library_name. If the user does this, all of the APIs and variables that are wrapped by the library_name namespace become globally accessible within the scope of the main() function. For this reason, any private APIs or variables that are not meant to be accessible by the user should be wrapped by a second namespace (typically called details) to prevent their global accessibility. Finally, leveraging C++17's inline keyword allows us to create a global variable for use in our library while still supporting a header-only design. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset