Export Application Version Information to Code using CMake

Export Application Version Information to Code using CMake

Versioning is a critical part of software development - it helps to track releases, manage compatibility, and communicate changes to users and developers alike. However, keeping version information consistent across the source code and build system can be annoying. Developers often hardcode version strings directly into the codebase, which leads to duplication, version mismatches, or forgotten updates when releasing new builds. Fortunately, CMake offers a built-in solution that allows you to define the application's version once and automatically export it to the code at build time, keeping everything in sync and reducing maintenance overhead. This tutorial explains how to export application version information to code using CMake.

Here's the CMakeLists.txt file:

cmake_minimum_required(VERSION 3.27)
project(myapp VERSION 1.2.3)

set(CMAKE_CXX_STANDARD 17)

configure_file(version.h.in version.h)

add_executable(${PROJECT_NAME} main.cpp)

target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_BINARY_DIR})

This does the following:

  • Declares the project version using project(myapp VERSION 1.2.3).
  • Uses configure_file to generate a header (version.h) from a template (version.h.in).
  • Includes the build directory, so the generated file can be included by the source.

Create the version header template version.h.in:

#ifndef MYAPP_VERSION_H
#define MYAPP_VERSION_H

#define MYAPP_VERSION_MAJOR @myapp_VERSION_MAJOR@
#define MYAPP_VERSION_MINOR @myapp_VERSION_MINOR@
#define MYAPP_VERSION_PATCH @myapp_VERSION_PATCH@

#define MYAPP_VERSION "@myapp_VERSION@"

#endif //MYAPP_VERSION_H

CMake replaces the @...@ variables with values from the project command.

Here's a simple main.cpp that prints the application version:

#include <iostream>
#include "version.h"

int main() {
    std::cout << MYAPP_VERSION << std::endl;
    std::cout << MYAPP_VERSION_MAJOR << "."
              << MYAPP_VERSION_MINOR << "."
              << MYAPP_VERSION_PATCH << std::endl;

    return 0;
}

Run the following command to generate the necessary build files:

cmake -S . -B build

Build the project:

cmake --build build

Run the application:

./build/myapp

You should see the output:

1.2.3
1.2.3

Leave a Comment

Cancel reply

Your email address will not be published.