Professional CMake:

A Practical Guide

Learn to use CMake effectively with practical advice from a CMake co-maintainer. You can also have the author work directly with your team!

Let your compiler do your housekeeping

A common sequence of steps we mortal software developers frequently find ourselves implementing goes something like this:

  1. Perform some sort of setup or acquire some sort of resource.
  2. Carry out some arbitrary sequence of actions.
  3. Tear down things we setup or release resources we acquired in step 1.

There are well-known patterns for implementing this scenario robustly, but when there are multiple sub-steps to be performed in the setup phase and where any of those sub-steps can each fail individually, things get more complicated. This article presents a concise, self-documenting and robust way to handle these more complicated cases. A follow-up article will extend this further to improve some performance characteristics and ends up having a lot in common with the ScopeGuard11 pattern described in various places online.

The multi-step setup problem

Conceptually, the problem we want to solve can be described as follows:

  1. For each setup sub-step:
    • Perform sub-step.
    • If sub-step fails, stop and release/clean up after all previous setup sub-steps.
  2. Carry out some arbitrary sequence of actions.
  3. Tear down things we setup or release resources we acquired in all sub-steps of step 1.

    Read more