Blog Series Tags

CMake find_package

In the last scroll on CMake we discussed adding libraries that you write to your own code. This time, we look at using third party libraries out of the box. This turns out to be fairly easy with CMake - though there are exceptions (alternatively spelled “bugs”). Adding a third party package such as the precious Boost libraries for C++ is fairly easy with CMake. In your CMakeLists.txt file add a call to FIND_PACKAGE like so:

FIND_PACKAGE(Boost 1.53.0 REQUIRED COMPONENTS filesystem system thread)

The first line says find Boost (which in turn calls a module FindBoost.cmake). You probably should give it a explicit version because you want to know what your linking against. You then list the different REQUIRED COMPONENTS from boost that you want (filesystem etc). Next you want to make sure you add the Boost header folders to your include path like so:

include_directories (${Boost_INCLUDE_DIRS})

Then add the library folders to your link path like so:

link_directories ( ${Boost_LIBRARY_DIRS} )

The variables ${Boost_INCLUDE_DIRS} and ${Boost_LIBRARY_DIRS} are defined by the FIND_PACKAGE call.

Finally when your building your binary you give the ${Boost_LIBRARIES} variable (again defined by the FIND_PACKAGE call) to it like so:

target_link_libraries(SomeBinary ${Boost_LIBRARIES} SomeOtherLirary)

And your done!

This is a post in the CMake series.