如何在 cmake 中添加库路径?

How do I add a library path in cmake?

我的项目中有 2 个文件夹 "inc" 和 "lib",它们分别有头文件和静态库。我如何告诉 cmake 分别使用这两个目录进行包含和链接?

最简单的方法是添加

include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)

add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib

不向每个编译器调用添加 -I and -L 标志的现代 CMake 版本将使用导入的库:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
  IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
  INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)

set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path

如果设置 INTERFACE_INCLUDE_DIRECTORIES 不添加路径,旧版本的 CMake 也允许您使用 target_include_directories(bar PUBLIC /path/to/include)。但是,此 no longer works 使用 CMake 3.6 或更新版本。

可能无法使用 link_directories,然后添加每个静态库,如下所示:

target_link_libraries(foo /path_to_static_library/libbar.a)

你最好使用find_library命令而不是link_directories。具体来说有两种方式:

  1. 在命令中指定路径

    find_library(命名 gtest 路径 path1 path2 ... pathN)

  2. 设置变量CMAKE_LIBRARY_PATH

    设置(CMAKE_LIBRARY_PATH路径1路径2)
    find_library(名称 gtest)

原因如flowings:

Note This command is rarely necessary and should be avoided where there are other choices. Prefer to pass full absolute paths to libraries where possible, since this ensures the correct library will always be linked. The find_library() command provides the full path, which can generally be used directly in calls to target_link_libraries(). Situations where a library search path may be needed include: Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).

Libraries may themselves have other private library dependencies that expect to be found via RPATH mechanisms, but some linkers are not able to fully decode those paths (e.g. due to the presence of things like $ORIGIN).

If a library search path must be provided, prefer to localize the effect where possible by using the target_link_directories() command rather than link_directories(). The target-specific command can also control how the search directories propagate to other dependent targets.