Tuesday Coding Tip 23 — CMake configure_file

●5 ●18 ●83
calendar_today • schedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


In unit tests, I often don’t want to bother with the working folder of the test binary. But if those tests need physical files from the disc, I need to know their absolute paths (which are different on each machine). Luckily, CMake has a function configure_file that can write CMake variables to a file template.

cmake_minimum_required ( VERSION 3.10 )

set ( USE_MSVC_FEATURES ("${CMAKE_GENERATOR}" MATCHES "Visual Studio 17 2022") )

project ( DEMO CXX )

# CMakeLists.txt
configure_file(
    "${CMAKE_SOURCE_DIR}/TemplateHeader.hpp.in" # input
    "${CMAKE_SOURCE_DIR}/FinalHeader.hpp" # output
)

For example, I can prepare a template for a header that will hold an absolute path to a folder with helper files, and during configuration, I can produce a valid C++ header with the path filled out. CMake will replace variables escaped as @VAR@, ${VAR}, $CACHE{VAR} or $ENV{VAR} and furthermore it can do things like generating #define directives.

// TemplateHeader.hpp.in
#pragma once

#include <filesystem>

#cmakedefine01 USE_MSVC_FEATURES

const std::filesystem::path TESTDATA_FOLDER = "@CMAKE_CURRENT_SOURCE_DIR@/TestFiles";

// Generated FinalHeader.hpp
#pragma once

#include <filesystem>

#define USE_MSVC_FEATURES 1

const std::filesystem::path TESTDATA_FOLDER = "C:/Work/Project/TestFiles";

Full documentation: https://cmake.org/cmake/help/latest/command/configure_file.html

Part 23 of 28 in Tuesday Coding Tips

1 Comment

0 votes
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 27 — Aliasing and ‘using’ in C++

Jakub Neruda - Oct 20

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21
chevron_left
2k Points • 106 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
40Posts
35Comments
21Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

5 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!