CMake:在静态库中包含库依赖项 [英] CMake: include library dependencies in a static library

查看:443
本文介绍了CMake:在静态库中包含库依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在CMake中构建一个静态库,该库依赖于许多其他静态库。我希望它们全部包含在输出.lib / .a文件中,所以我可以将一个很大的lib文件运送给客户。在Visual Studio 2010中,有一个选项链接库依赖项 正是这样做的。

I am building a static library in CMake, which is dependent on many other static libraries. I would like them all to be included in the output .lib/.a file, so I can just ship a big lib file to customers. In Visual Studio 2010 there is an option, "Link Library Dependencies", which does exactly this.

但是我找不到如何在CMake中做到这一点。您可以通过CMake设置此标志,还是通过其他方式获得相同的结果?我尝试了target_link_libraries(...)和add_dependencies(...),但是CMake似乎只是忽略了静态库的这一行。

But I can't find how to do it in CMake. Can you set this flag via CMake, or get the same result some other way? I have tried target_link_libraries(...) and also add_dependencies(...), but CMake seems to simply ignore this line for static libraries.

推荐答案

好的,所以我有解决办法。首先,必须认识到静态库不会将其他静态库链接到代码中。必须创建一个组合库,在Linux上可以使用 ar 完成。请参见 将静态库链接到其他静态库 有关更多信息。

Okay, so I have a solution. First it's important to recognize that static libraries do not link other static libraries into the code. A combined library must be created, which on Linux can be done with ar. See Linking static libraries to other static libraries for more info there.

请考虑两个源文件:

 int hi()
 {
   return 0;
 }



test2.c:



test2.c:

int bye()
{
  return 1;
}

CMakeLists.txt

The CMakeLists.txt file is to create two libraries and then create a combined library looks like:

project(test)

    add_library(lib1 STATIC test1.c)
    add_library(lib2 STATIC test2.c)

    add_custom_target(combined ALL
      COMMAND ${CMAKE_AR} rc libcombined.a $<TARGET_FILE:lib1> $<TARGET_FILE:lib2>)

ar 命令与平台有关,尽管 CMAKE_AR 变量与平台无关。我会四处看看是否有更通用的方法来执行此操作,但是这种方法将在使用 ar 的系统上工作。

The options to the ar command are platform-dependent in this case, although the CMAKE_AR variable is platform-independent. I will poke around to see if there is a more general way to do this, but this approach will work on systems that use ar.

基于 如何设置CMAKE_AR的选项? ,看来更好的方法是:

Based on How do I set the options for CMAKE_AR?, it looks like the better way to do this would be:

add_custom_target(combined ALL
   COMMAND ${CMAKE_CXX_ARCHIVE_CREATE} libcombined.a $<TARGET_FILE:lib1> $<TARGET_FILE:lib2>)

这应该与平台无关,因为这是CMake内部用于创建档案的命令结构。当然,要传递给归档命令的唯一选项是 rc ,因为这些硬连接到 ar 命令。

This should be platform-independent, because this is the command structure used to create archives internally by CMake. Provided of course the only options you want to pass to your archive command are rc as these are hardwired into CMake for the ar command.

这篇关于CMake:在静态库中包含库依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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