C++ 如何在 cmake 中添加库路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28597351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I add a library path in cmake?
提问by grasevski
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?
我的项目中有 2 个文件夹“inc”和“lib”,它们分别具有标头和静态库。我如何告诉 cmake 分别使用这 2 个目录进行包含和链接?
回答by ar31
The simplest way of doing this would be to add
最简单的方法是添加
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
The modern CMake version that doesn't add the -I and -L
flags to every compiler invocation would be to use imported libraries:
不-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
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 workswith CMake 3.6 or newer.
如果设置INTERFACE_INCLUDE_DIRECTORIES
不添加路径,旧版本的 CMake 也允许您使用target_include_directories(bar PUBLIC /path/to/include)
. 但是,这不再适用于 CMake 3.6 或更高版本。