I show how to build C++ Hello World program by CMake in the last post. Today, I want to build C++ program by CMake with C++ math library. The last CMake build example was too simple, so I add library to my C++ program. Here is my code with C++ math library. The program calculate square root of 4. You expect to get 2.
#include <iostream>
#include <cmath>
int main(int argc, const char * argv[])
{
std::cout << "Square Root of 4: "
<< sqrt(4.0) << std::endl;
return EXIT_SUCCESS;
}
When you compile C++ by g++ compiler with C++ math library in command line, you add library option -lm. Here is g++ compilation in command line.
g++ -o out main.cpp -lm

Now you have execution file out.

Run program

Next, we build main.cpp by CMake with C++ math library. Here is how to add library to CMake by target_link_libraries. Add target_link_libraries to your CMake with C++ math library option ‘m.’ C++ compiler g++ requires -l before ‘m’ due to its argument option ‘-l.’ CMake need C++ math library name ‘m.’
target_link_libraries(main m)
Now, let’s configure the program by CMake.
cmake -H. -Bbuild

Next, build the program by CMake.
cmake --build build/

Run an execution file.
./build/main

Here is a complete version of CMakeLists.txt
# set minimum requirements
cmake_minimum_required(VERSION 3.10)
# set the project name and version
project(main VERSION 1.0)
# add compile options
add_compile_options(-Wall -g)
# specify the C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# set source files
set(SOURCES main.cpp)
# add the executable
add_executable(main ${SOURCES})
# set library option
target_link_libraries(main m)
This is how to build and compile C++ program by CMake with library.