13.1. CMake Style Guide#

13.1.1. General#

To put in in one sentence: be as careful when writing the CMake files as when you are writing C++ code.

13.1.2. Indentation#

Indent all code correctly, i.e. the body of

  • if/else/endif

  • foreach/endforeach

  • while/endwhile

  • macro/endmacro

  • function/endfunction

Use spaces for indenting, 4 spaces preferably. Use the same amount of spaces for indenting as is used in the rest of the file. Do not use tabs.

13.1.3. Naming#

Functions: lower_case name. Ex:

do_something(...)

Local variables: lower_case name. Local variables are used exclusively inside the file that contained them, and their values were simply passed as parameters to CMake functions. Ex:

set(some_variable "...")

Global variables: UPPER_CASE name. Global variables (can also be called “export variables”) are intended for exporting up/down-stream via the environment variable mechanism. Ex:

set(SOME_VARIABLE "..." CACHE ...)

Control statements: lower_case name without repeat the condition in the closing brackets. Ex:

if(condition)
  ...
else() # not repeat condition
  ...
endif() # not repeat condition

Operators: UPPER_CASE name. Ex:

if(condition STREQUAL "")

Directives and/or extra options: UPPER_CASE name. Ex:

do_something(... USE_THIS)
file(COPY ...)

13.1.4. End commands#

To make the code easier to read, use empty commands for endforeach(), endif(), endfunction(), endmacro() and endwhile(). Also, use empty else() commands.

For example, do this:

if(FOOVAR)
   some_command(...)
else()
   another_command(...)
endif()

and not this:

if(BARVAR)
   some_other_command(...)
endif(BARVAR)

13.1.5. Examples#

An real-world example:

function(set_platform system_name)
  if(${system_name} MATCHES "Darwin")
    set(PLATFORM "darwin")
  elseif(${system_name} MATCHES "Linux")
    set(PLATFORM "linux")
  else()
    set(PLATFORM "")
  endif()
endfunction()

cmake_minimum_required(VERSION 3.0)
set_platform(${CMAKE_SYSTEM_NAME})

13.1.6. References#

This style guide is mainly taken from