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

How it works

The previous example introduced two new commands:

  • add_library(message STATIC Message.hpp Message.cpp): This will generate the necessary build tool instructions for compiling the specified sources into a library. The first argument to add_library is the name of the target. The same name can be used throughout CMakeLists.txt to refer to the library. The actual name of the generated library will be formed by CMake by adding the prefix lib in front and the appropriate extension as a suffix. The library extension is determined based on the second argument, STATIC or SHARED, and the operating system.
  • target_link_libraries(hello-world message): Links the library into the executable. This command will also guarantee that the hello-world executable properly depends on the message library. We thus ensure that the message library is always built before we attempt to link it to the hello-world executable.

After successful compilation, the build directory will contain the libmessage.a static library (on GNU/Linux) and the hello-world executable. 

CMake accepts other values as valid for the second argument to add_library and we will encounter all of them in the rest of the book:

  • STATIC, which we have already encountered, will be used to create static libraries, that is, archives of object files for use when linking other targets, such as executables.
  • SHARED will be used to create shared libraries, that is, libraries that can be linked dynamically and loaded at runtime. Switching from a static library to a dynamic shared object (DSO) is as easy as using add_library(message SHARED Message.hpp Message.cpp) in CMakeLists.txt
  • OBJECT can be used to compile the sources in the list given to add_library to object files, but then neither archiving them into a static library nor linking them into a shared object. The use of object libraries is particularly useful if one needs to create both static and shared libraries in one go. We will demonstrate this in this recipe.
  • MODULE libraries are once again DSOs. In contrast to SHARED libraries, they are not linked to any other target within the project, but may be loaded dynamically later on. This is the argument to use when building a runtime plugin.

CMake is also able to generate special types of libraries. These produce no output in the build system but are extremely helpful in organizing dependencies and build requirements between targets:

In this example, we have collected the sources directly using add_library. In later chapters, we demonstrate the use of the target_sources CMake command to collect sources, in particular in Chapter 7Structuring Projects. See also this wonderful blog post by Craig Scott: https://crascit.com/2016/01/31/enhanced-source-file-handling-with-target_sources/ which further motivates the use of the target_sources command.