CMake link to external library

I assume you want to link to a library called foo, its filename is usually something link foo.dll or

1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB use

    find_library(FOO_LIB foo)

CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib, /usr/lib64 and the paths in PATH.

You already know the location of your library. Add it to the CMAKE_PREFIX_PATH when you call CMake, then CMake will look for your library in the passed paths, too.

Sometimes you need to add hints or path suffixes, see the documentation for details:

2. Link the library
From 1. you have the full library name in FOO_LIB. You use this to link the library to your target GLBall as in

  target_link_libraries(GLBall PRIVATE "${FOO_LIB}")

You should add PRIVATE, PUBLIC, or INTERFACE after the target, cf. the documentation:

If you don’t add one of these visibility specifiers, it will either behave like PRIVATE or PUBLIC, depending on the CMake version and the policies set.

3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path similar to find_library and search for a header file. Then add the include directory with target_include_directories similar to target_link_libraries.


If available for the external software, you can replace find_library and find_path by find_package.

Leave a Comment