C++ 将编译的库和包含文件添加到 CMake 项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2601798/
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
Adding compiled libraries and include files to a CMake Project?
提问by Mike
What is the best method to include a prebuilt library to a cmake project? I want to include FreeType into the project I am working on and the file structure is like this:
将预构建库包含到 cmake 项目的最佳方法是什么?我想将 FreeType 包含到我正在处理的项目中,文件结构是这样的:
- Build
- MacOS
- Make/
- XCode/
- Windows
- VisualStudio/
- Source
- libs
- MacOS
- libfreetype
- Windows
- freetype.dll
- includes
- freetype/ (Various header files that are included automatically by ftbuild.h)
- ftbuild.h (this is what is included in code from my understanding.)
- MyProject
- main.cpp
- foo.cpp
- foo.h
- 建造
- 苹果系统
- 制作/
- 代码/
- 视窗
- 视觉工作室/
- 来源
- 库
- 苹果系统
- 自由类型
- 视窗
- freetype.dll
- 包括
- freetype/(ftbuild.h 自动包含的各种头文件)
- ftbuild.h(这是我理解的代码中包含的内容。)
- 我的项目
- 主程序
- 文件
- foo.h
The library is already compiled. MyProject is the name of the current project.
库已经编译好了。MyProject 是当前项目的名称。
Thanks! Mike
谢谢!麦克风
采纳答案by Boojum
Recent versions already have a module for finding FreeType. Here's the kind of thing I've done in the past:
最近的版本已经有一个用于查找 FreeType 的模块。这是我过去做过的事情:
INCLUDE(FindFreetype)
IF(NOT FREETYPE_FOUND)
FIND_LIBRARY(FREETYPE_LIBRARIES NAMES libfreetype freetype.dll PATHS "./libs/MacOS" "./libs/Windows" DOC "Freetype library")
FIND_PATH(FREETYPE_INCLUDE_DIRS ftbuild.h "./includes" DOC "Freetype includes")
ENDIF(NOT FREETYPE_FOUND)
INCLUDE_DIRECTORIES(${FREETYPE_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(MyProject ${FREETYPE_LIBRARIES})
You'll need to change the paths to be relative to your CMakeLists.txt.
您需要将路径更改为相对于您的 CMakeLists.txt。
This snippet first invokes the FindFreetype module to check in the standard system locations. If it fails to find the library there, then this falls back to checking directories relative to the your CMakeLists.txt script. If thatstill fails, you can still set or override the locations via the usual CMake UI. In any event, it tries to add something to the list of includes and libraries to link.
此代码段首先调用 FindFreetype 模块以检查标准系统位置。如果在那里找不到库,那么这将退回到检查与 CMakeLists.txt 脚本相关的目录。如果这仍然失败,你仍然可以设置或覆盖通过通常CMake的UI的位置。在任何情况下,它都会尝试向要链接的包含和库列表中添加一些内容。
回答by DLRdave
Just use target_link_libraries with the full path to the prebuilt lib.
只需将 target_link_libraries 与预构建库的完整路径一起使用。
So, something like:
所以,像这样:
# In the file Source/MyProject/CMakeLists.txt
add_executable(my_exe main.cpp foo.cpp foo.h)
if(WIN32)
target_link_libraries(my_exe ${CMAKE_CURRENT_SOURCE_DIR}/../libs/Windows/freetype.lib)
endif()
if(APPLE)
target_link_libraries(my_exe ${CMAKE_CURRENT_SOURCE_DIR}/../libs/MacOS/libfreetype.a)
endif()