How to do it

We will construct the CMakeLists.txt step by step and show how to require a certain standard (in this case C++14):

  1. We state the minimum required CMake version, project name, and language:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

project(recipe-09 LANGUAGES CXX)
  1. We request all library symbols to be exported on Windows:
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
  1. We need to add a target for the library. This will compile the sources into a shared library:
add_library(animals
SHARED
Animal.cpp
Animal.hpp
Cat.cpp
Cat.hpp
Dog.cpp
Dog.hpp
Factory.hpp
)
  1.  We now set the CXX_STANDARD, CXX_EXTENSIONS, and CXX_STANDARD_REQUIRED properties for the target. We also set the POSITION_INDEPENDENT_CODE property, to avoid issues when building the DSO with some compilers:
set_target_properties(animals
PROPERTIES
CXX_STANDARD 14
CXX_EXTENSIONS OFF
CXX_STANDARD_REQUIRED ON
POSITION_INDEPENDENT_CODE 1
)
  1. Then, we add a new target for the animal-farm executable and set its properties:
add_executable(animal-farm animal-farm.cpp)

set_target_properties(animal-farm
PROPERTIES
CXX_STANDARD 14
CXX_EXTENSIONS OFF
CXX_STANDARD_REQUIRED ON
)
  1.  Finally, we link the executable to the library:
target_link_libraries(animal-farm animals)
  1. Let us also check what our example cat and dog have to say:
$ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
$ ./animal-farm

I'm Simon the cat!
I'm Marlowe the dog!