0

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:

  1. 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)
  1. 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

  1. 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.

2
  • 1
    I’m voting to close this question because this seems opinion based and more suitable for codereview.stackexchange.com Commented 38 mins ago
  • This is C++, so "It depends". What is the use case? With the macros, you can use the values with #if conditions. With constexpr values, you can use if 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...
    – BoP
    Commented 37 mins ago

0

Browse other questions tagged or ask your own question.