Cmake:链接到静态内部库而不导出它 [英] Cmake: linking to static internal library without exporting it
问题描述
我有一个结构如下的项目:
I have a project with this structure:
/path/to/my/project
├── CMakeLists.txt
├── internal-libs
│ ├── internal-lib1
├── libs
│ ├── lib1
│ ├── lib2
lib1
是静态库.
lib2
是一个静态库.
internal-lib1
是一个静态库.
lib2静态链接到lib2和internal-lib1. lib1
和 lib2
将要导出,但将保留 internal-lib1
.对于链接,我有:
lib2 links statically to lib2 and internal-lib1. lib1
and lib2
are going to be exported but internal-lib1
will be left behind. For the linkage, I have:
target_link_libraries(lib2 PRIVATE internal-lib1)
target_link_libraries(lib2 PRIVATE lib1)
我的理解是,因为我要进行静态和私有链接,所以有关internal-lib1的所有信息都将包含在lib2中,而不必将internal-lib1导出到外界.
My understanding is that because I am linking statically and privately, All the information about internal-lib1 would be contained in lib2 and that I won't have to export internal-lib1 to the outside world.
但是,当我尝试在客户端程序中使用它时,出现错误:
However, when I try to use it in a client program, I get the error:
/usr/bin/ld cannot find -llib-internal1
collect2: error: ld returned 1 exit status
在我生成的导出配置文件中,我有:
in my generated Export config file, I have:
# Create imported target lib2
add_library(lib2 STATIC IMPORTED)
set_target_properties(lib2 PROPERTIES
INTERFACE_LINK_LIBRARIES "$<LINK_ONLY:lib1>;**$<LINK_ONLY:internal-lib1>**"
)
# Create imported target lib1
add_library(lib1 STATIC IMPORTED)
我是否误解了静态链接,或者我的设置有问题吗?我正在使用cmake 3.2.2.我所有的目标包括PRIVATE.我不明白为什么 INTERFACE_LINK_LIBRARIES
会填充条目以及LINK_ONLY的含义.
Am I misunderstanding the static linking or is there something wrong with my setup? I am using cmake 3.2.2. All my target includes are PRIVATE. I don't understand why INTERFACE_LINK_LIBRARIES
is populated with entries and what LINK_ONLY means.
p.s.实际上,lib1和lib2应该是共享库,但是我什至无法使用静态版本,因此为简单起见,我在此描述可导出库的静态情况.
p.s. Actually lib1 and lib2 are supposed to be shared libraries but I can't even get the static version working so for simplicity here I am describing the static case for the exportable libraries.
推荐答案
CMake命令
target_link_libraries(lib2 PRIVATE lib1)
并不表示链接时将库 lib1
复制到库 lib2
中. PRIVATE
关键字仅影响 lib2 时,库 lib1
的nofollow noreferrer>传递用法要求.
does not imply that the library lib1
is copied to the library lib2
upon linking. The PRIVATE
keyword only affects transitive usage requirements of the library lib1
when another library links to lib2
.
要使CMake在链接时将 lib1
合并到 lib2
中,请使用 libtool
和 POST_BUILD
操作:>
To have CMake merge lib1
into lib2
upon linking, use libtool
and a POST_BUILD
action:
add_custom_command(TARGET lib2 POST_BUILD
COMMAND /usr/bin/libtool -static -o $<TARGET_FILE:lib2>
$<TARGET_FILE:lib2> $<TARGET_FILE:lib1>
在这种情况下,无需使用 target_link_libraries
将 lib1
链接到 lib2
.
In that case, there is no need to link lib1
to lib2
with target_link_libraries
.
这篇关于Cmake:链接到静态内部库而不导出它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!