Best practices on finding third party libraries for a project?

I’m new to CMake. Trying to read up on best practices and common concepts.

One thing which eludes me is how to be able to provide CMake with paths for external libraries such that find_library finds them. The documentation refer to a number of variables used by CMake, but I’m struggling to work out which ones to use when.

Example, I have a project where I need external libraries. These libs cannot be bundled with my project so it must be supplied by the system/user somehow. (I’m targeting Windows and Mac)

To avoid hard coding paths that relate to my own machine I’m trying to figure out how to pass the appropriate directories to the project and using find_library and find_path.

One thing I tried, (using VSCode along with the CMake Tools extension) was to set the user config to:

    "cmake.configureSettings": {
        "CMAKE_INCLUDE_PATH": "<path>",
        "CMAKE_LIBRARY_PATH": "<path>"
    }
}

And this works, but for both variables CMake documentation says:

By default it is empty, it is intended to be set by the project.

So it sounds like I’m not using the variables appropriately by setting them in a user setting.

What’s common practice? Add all these paths to the system environment PATH variable? (Is there a CMAKE environment variable that I can avoid using the PATH variable?)

Take a look at CMAKE_FIND_ROOT_PATH.

I don’t see that listed under CMake env variables. So presumably this is only a configuration variable? cmake -DCMAKE_FIND_ROOT_PATH=<paths>?

Any canonical way to set this as a machine config for CMake? Or do people usually always pass in these types of paths when configuring CMake?

Yes.

Yes, these variables are meant to be passed on the command line. They explain to the project what your system looks like.

I’m not sure what you mean by this.

Never mind, the below quote gave me insight into what you’re asking:

Indeed, using find_*() is the best approach to make your project cross-platform. And as I said above, machine-specific settings should be passed on the command line rather than hard-coded in your project.

That said, you can use the -C argument to pass a script file that automatically sets your system-specific variables, or write a shell script that passes them to CMake automatically, to avoid having to repeat them every time you configure your project.

Gotcha - thank you for the insight.

I prefer CMAKE_PREFIX_PATH . It can be set via the command line or as an environment variable ( 3.6+ ).

1 Like