cmake using find_package() cross compiling

2020-02-12 21:44发布

问题:

I am using CMake with a custom toolchain that I built using yocto. I have a problem though, the toolchain has sysroot for the target machine and one for the build machine.

CMake keeps finding the libraries in the build system sysroot only.

For example I am using:

find_package(libxml2)

But it always keeps finding libxml2 in the build system sysroot instead of the target sysroot. How can I tell it to only look in the target sysroot?

回答1:

How can I tell it to look in the target sysroot only?

There is a family of CMake variables CMAKE_FIND_ROOT_PATH_MODE_*, which adjusts search strategy for different CMake commands:

  • BOTH value means that both target and host (build) paths are searched. This is also a default behavior, when a variable is not set.

  • ONLY value means that only target is searched.

  • NEVER value means, that only host is searched.

List of variables:

  • CMAKE_FIND_ROOT_PATH_MODE_LIBRARY affects on find_library() calls

  • CMAKE_FIND_ROOT_PATH_MODE_INCLUDE affects on find_path() and find_file() calls

  • CMAKE_FIND_ROOT_PATH_MODE_PACKAGE affects on find_package() in CONFIG mode (when *Config.cmake file is searched).

  • CMAKE_FIND_ROOT_PATH_MODE_PROGRAM affects on find_program() call.

Generally, concrete find_package() call may be affected by all of these variables. In case of searching libraries, it is usually suffificient to set only 3 of them:

# Search libraries only under *target* paths.
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)

Variables CMAKE_FIND_ROOT_PATH_MODE_* are normally set in toolchain files.