I wrote a C++ static library, and I want to add version information for it in a designated header. I'm working with C++14. I'm contemplating on multiple approaches:
- Adding it as macros:
#pragma once
#define LIBRARY_NAME_VERSION_MAJOR 1
#define LIBRARY_NAME_VERSION_MINOR 0
#define LIBRARY_NAME_VERSION_PATCH 0
// Prefixed stringify macros to avoid collisions
#define LIBRARY_NAME_STRINGIFY(x) #x
#define LIBRARY_NAME_TOSTRING(x) LIBRARY_NAME_STRINGIFY(x)
// Construct version string using prefixed macros
#define LIBRARY_NAME_VERSION_STRING \
LIBRARY_NAME_TOSTRING(LIBRARY_NAME_VERSION_MAJOR) "." \
LIBRARY_NAME_TOSTRING(LIBRARY_NAME_VERSION_MINOR) "." \
LIBRARY_NAME_TOSTRING(LIBRARY_NAME_VERSION_PATCH)
- Adding it as constexpr
#pragma once
#include <string>
constexpr int LIBRARY_NAME_VERSION_MAJOR = 1;
constexpr int LIBRARY_NAME_VERSION_MINOR = 0;
constexpr int LIBRARY_NAME_VERSION_PATCH = 0;
constexpr auto LIBRARY_NAME_VERSION_STRING =
std::to_string(LIBRARY_NAME_VERSION_MAJOR) + "." +
std::to_string(LIBRARY_NAME_VERSION_MINOR) + "." +
std::to_string(LIBRARY_NAME_VERSION_PATCH);
I understand there is inline constexpr to avoid multiple definitions of the same symbol, but I have to use C++14 and not C++17
- Adding it with extern
#pragma once
#include <string>
constexpr int LIBRARY_NAME_VERSION_MAJOR = 1;
constexpr int LIBRARY_NAME_VERSION_MINOR = 0;
constexpr int LIBRARY_NAME_VERSION_PATCH = 0;
std::string getLibraryVersionString();
I was wondering what is the best practice in this case.
Thanks!
I experimented with all of these approaches, and I have pros and cons for each. I want to use modern C++ as much as I can under my constraints and follow the best practice way.
#if
conditions. With constexpr values, you can useif constexpr
(but perhaps not in C++14...). The C++ standard library instead uses defines for each feature, so you don't have to remember the patch level where your specific feature was finally fixed...