如何使用CMake将静态库链接到可执行文件 [英] How to link a static library to an executable using CMake

查看:1002
本文介绍了如何使用CMake将静态库链接到可执行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CMake中,我们使用TARGET_LINK_LIBRARIES()将共享库链接到库/可执行文件。

In CMake, we use TARGET_LINK_LIBRARIES() to link a shared library to an library/executable.

For example:
TARGET_LINK_LIBRARIES(ExecutableName xxx)
   where ExecutableName - is the name of executable
         xxx - is the library name.

据我了解,CMake在LINK_DIRECTORIES()宏中提到的路径中搜索 libxxx.so 。
但是,如果我有一个名为 libxxx.a的第三方库,那么我该如何使用CMake将库链接到可执行文件。

As of my understanding CMake searches for "libxxx.so" at the paths mentioned in LINK_DIRECTORIES() macro. But if I have a third party library with name "libxxx.a" then how do I link the library to the executable using CMake.

谢谢

推荐答案

您应始终尝试为target_link_libraries提供完整路径或CMake目标。

You should always try to give either full paths or CMake targets to target_link_libraries.

由于您似乎并未在CMake项目中建立依赖关系,因此获取要链接的CMake目标的唯一方法是创建导入目标。手动进行操作通常很繁琐,因此除非依赖项已经提供了带有导入目标的配置文件,否则您可能不想走这条路。导入的目标是最方便使用的,但前提是您可以让CMake为您编写。

Since you do not seem to build the dependency as part of the CMake project, the only way to obtain a CMake target to link against, is to create an imported target. This is usually quite tedious to do manuall, so unless the dependency already provides a config file with an imported target, you probably do not want to go down that road. Imported targets are the most convenient to use, but only if you can get CMake to write the for you.

因此,绝对路径就是这样。您显然不想在CMakeLists中对绝对库路径进行硬编码。正如您的问题中指出的那样,所需的行为是仅指定库的名称,并且CMake应该能够自动找出其位置。这正是 find_library 为您服务。

So, absolute paths it is then. You obviously would not want to hardcode absolute library paths in your CMakeLists. As pointed out in your question, the desired behavior is that you specify just the name of a library and CMake should be able to figure out its location automatically. This is exactly what find_library does for you.

要链接到库 xxx ,您可以像这样的东西:

To link against a library xxx, you would do something like this:

find_library(LIB_LOCATION xxx)
target_link_libraries(ExecutableName ${LIB_LOCATION})

请注意, find_library 提供了很多选项,可以进一步指定在何处查找所需的库。摆脱现有的 link_directories 调用,并将相应的路径作为提示添加到 find_library 中。

Note that find_library provides a plethora of options to further specify where to look for the requested library. Get rid of your existing link_directories call and add the respective paths as hints to find_library instead.

将CMake代码移植到其他平台时,这种方法既灵活,而且比最初的方法更容易调试出问题。

This approach is both more flexible when porting your CMake code to other platforms and more easy to debug if something goes wrong than your initial approach.

这篇关于如何使用CMake将静态库链接到可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆