且构网

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

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

更新时间:2022-06-12 22:21:10

好的,所以我有解决办法。首先,必须认识到静态库不会将其他静态库链接到代码中。必须创建一个组合库,在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 的CMake中>命令。

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.