CMake Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it

Let us have a look at our static/shared library example from the previous recipe. Instead of hardcoding USE_LIBRARY to ON or OFF, we will now prefer to expose it as an option with a default value that can be changed from the outside:

  1. Replace the set(USE_LIBRARY OFF) command of the previous recipe with an option. The option will have the same name and its default value will be OFF:
option(USE_LIBRARY "Compile sources into a library" OFF)
  1. Now, we can switch the generation of the library by passing the information to CMake via its -D CLI option: 
$ mkdir -p build
$ cd build
$ cmake -D USE_LIBRARY=ON ..

-- ...
-- Compile sources into a library? ON
-- ...

$ cmake --build .

Scanning dependencies of target message
[ 25%] Building CXX object CMakeFiles/message.dir/Message.cpp.o
[ 50%] Linking CXX static library libmessage.a
[ 50%] Built target message
Scanning dependencies of target hello-world
[ 75%] Building CXX object CMakeFiles/hello-world.dir/hello-world.cpp.o
[100%] Linking CXX executable hello-world
[100%] Built target hello-world

The -D switch is used to set any type of variable for CMake: logicals, paths, and so forth.