CMake and variables

on , , , 2 minutes reading

Yeah, it is me again with more CMake!

You remember my last blog post? When I told you it was the simplest CMake file possible? Well, I lied. In fact, if we just want to print Hello world in CMake we just need to do something like this:

# we just print hello world
message("Hello world!")

It does absolutely nothing except say “Hello world!” when generating the Makefile, and of course, your Makefile will do absolutely nothing.


So I have been talking only about CMake Commands. add_executable, link_target_library and message are commands in CMake; they tell CMake what to do and CMake will know how to do it. CMake has a lot of commands and all of them are documented in the CMake documentation.

As in every modern scripting “language”, CMake has variables too. Some of those variables are special and provide special information to CMake, like the directory path where the sources are, the place where we put the compiled executables and libraries, etc. The same as commands, there are a lot of useful variables listed in the CMake wiki and documentation.

Setting variables

Setting a variable in CMake is really easy; you just need the command set:

cmake_minimum_required (VERSION 3.5)
project (CMakeVariables)
set (SOURCES hello.c greeter.c)
add_executable (hello ${SOURCES})

We just created a list of files in our variable called SOURCES and then used that variable in a target. Easy!

Where are the header files?

Header files are important in C/C++ development and usually they live in a separate directory. Let’s change that in our current project:

mkdir includes
mv greeter.h includes

Of course we will need to change our CMakeLists.txt file to reflect this change:

cmake_minimum_required (VERSION 3.5)
project (CMakeVariables)
set (SOURCES hello.c greeter.c)
include_directories (${PROJECT_SOURCE_DIR}/includes)
add_executable (hello ${SOURCES})

As you can see, we need to use the include_directories command to tell CMake where to find our header files.

File globbing

Instead of creating a variable with a explicit list of source files we can “glob” them together using an expression and assign the created list to a variable. This is done with the file command:

cmake_minimum_required (VERSION 3.5)
project (CMakeVariables)
include_directories (${PROJECT_SOURCE_DIR})
file (GLOB SOURCES *.c)
add_executable (hello ${SOURCES})

Note about globbing! : Even the CMake documentation warns us about globbing and asks us to explicitly list the source files instead of using globbing. This question from StackOverflow explains a little more about the issue and the options.

In conclusion, use globbing with caution!

Well, now we know about variables in CMake and file globbing, but we still have a few other things to explore in CMake, so I will see you soon with another short blog post!