且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

cmake:在静态库中包含库依赖项

更新时间:2022-06-12 22:20:34

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