Tuesday Coding Tip 23 — CMake configure_file

●5 ●29 ●93
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

Want more #cpp & #tuesday-coding-tips deep dives?

Join 6,001+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 23 of 31 in Tuesday Coding Tips

1 Comment

0 votes

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 31 — Deducing this

Jakub Neruda - Nov 17

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

Jakub Neruda - Oct 20

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30
chevron_left
2.1k Points • 127 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
43Posts
37Comments
22Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Commenters (This Week)

2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!