
上QQ阅读APP看书,第一时间看更新
How to do it
Let us start with the same source code as for the previous recipe. We want to be able to toggle between two behaviors:
- Build Message.hpp and Message.cpp into a library, static or shared, and then link the resulting library into the hello-world executable.
- Build Message.hpp, Message.cpp, and hello-world.cpp into a single executable, without producing the library.
Let us construct CMakeLists.txt to achieve this:
- We start out by defining the minimum CMake version, project name, and supported language:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(recipe-04 LANGUAGES CXX)
- We introduce a new variable, USE_LIBRARY. This is a logical variable and its value will be set to OFF. We also print its value for the user:
set(USE_LIBRARY OFF)
message(STATUS "Compile sources into a library? ${USE_LIBRARY}")
- Set the BUILD_SHARED_LIBS global variable, defined in CMake, to OFF. Calling add_library and omitting the second argument will build a static library:
set(BUILD_SHARED_LIBS OFF)
- We then introduce a variable, _sources, listing Message.hpp and Message.cpp:
list(APPEND _sources Message.hpp Message.cpp)
- We then introduce an if-else statement based on the value of USE_LIBRARY. If the logical toggle is true, Message.hpp and Message.cpp will be packaged into a library:
if(USE_LIBRARY)
# add_library will create a static library
# since BUILD_SHARED_LIBS is OFF
add_library(message ${_sources})
add_executable(hello-world hello-world.cpp)
target_link_libraries(hello-world message)
else()
add_executable(hello-world hello-world.cpp ${_sources})
endif()
- We can again build with the same set of commands. Since USE_LIBRARY is set to OFF, the hello-world executable will be compiled from all sources. This can be verified by running the objdump -x command on GNU/Linux.