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

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

问题描述

我在cmake中构建了一个静态库,它依赖于许多其他静态库。我希望他们都包含在输出.lib / .a文件中,所以我可以只是发送一个大的lib文件给客户。在VS2010中有一个选项链接库依赖,这正是这样。

I am building a static lib in cmake, which is dependent on many other static libs. 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 VS2010 there is an option "Link Library Dependencies" which does exactly this.

但我无法找到如何在cmake中做。你可以通过cmake设置此标志,或者获得相同的结果一些其他方式?我试过target_link_libraries(...)和add_dependencies(...),但cmake似乎只是忽略这一行静态库

But I cant 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 libs

推荐答案

好吧,所以我有一个解决方案。首先,重要的是要认识到静态库不会将其他静态库链接到代码中。必须创建一个组合库,在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.

考虑两个源文件:

test1.c:

 int hi()
 {
   return 0;
 }

test2.c:

int bye()
{
  return 1;
}

CMakeLists.txt 创建两个库,然后创建一个组合库如下:

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

project(test)

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 to 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 ,因为这些是硬件连接到CMake的 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天全站免登陆