如何在 cmake 中添加库路径?

How do I add a library path in cmake?(如何在 cmake 中添加库路径?)

本文介绍了如何在 cmake 中添加库路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 folders "inc" and "lib" in my project which have headers and static libs respectively. How do I tell cmake to use those 2 directories for include and linking respectively?

推荐答案

最简单的方法是添加

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 和 -L 标志的现代 CMake 版本将使用导入的库:

The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

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).但是,此不再适用于 CMake 3.6 或更高版本.

If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

这篇关于如何在 cmake 中添加库路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 cmake 中添加库路径?

基础教程推荐