CMake 链接静态库 示例

December 09, 2023
测试
测试
测试
测试
6 分钟阅读
现有

lib-a, lib-b

可执行文件

final

链接情况

lib-b 静态链接 lib-a, final静态链接lib-blib-a, 且final同样静态编译

lib-a

CMakeLists.txt

cmake_minimum_required(VERSION 3.19)
project(lib_a)

set(CMAKE_CXX_STANDARD 11)

add_library(lib_a STATIC library_a.cpp)

library_a.h

#ifndef LIB_A_LIBRARY_A_H
#define LIB_A_LIBRARY_A_H

void helloA();

#endif //LIB_A_LIBRARY_A_H

library_a.cpp

#include "library_a.h"

#include <iostream>

void helloA() {
    std::cout << "静态库A" << std::endl;
}
lib-b

CMakeLists.txt

cmake_minimum_required(VERSION 3.19)
project(lib_b)

set(CMAKE_CXX_STANDARD 11)

include_directories(${CMAKE_SOURCE_DIR}/third_party/include/)

add_library(lib_b STATIC library_b.cpp)

target_link_libraries(lib_b ${CMAKE_SOURCE_DIR}/third_party/lib/a/liblib_a.a)

library_b.h

#ifndef LIB_B_LIBRARY_B_H
#define LIB_B_LIBRARY_B_H

#include "a/library_a.h"

void helloB();

#endif //LIB_B_LIBRARY_B_H

library_b.cpp

#include "library_b.h"
#include "a/library_a.h"

#include <iostream>

void helloB() {
    std::cout << "静态库B" << std::endl;
    std::cout << "静态库B中调用静态库A" << std::endl;
    helloA();
}
final

CMakeLists.txt

cmake_minimum_required(VERSION 3.19)
project(final)

set(CMAKE_CXX_STANDARD 11)

include_directories(${CMAKE_SOURCE_DIR}/third_party/include/)

set(CMAKE_EXE_LINKER_FLAGS "-static")

add_executable(final main.cpp)


target_link_libraries(final
        ${CMAKE_SOURCE_DIR}/third_party/lib/b/liblib_b.a
        ${CMAKE_SOURCE_DIR}/third_party/lib/a/liblib_a.a
        )

main.cc

#include <iostream>

#include "b/library_b.h"
#include "a/library_a.h"

int main() {
    std::cout << "Hello, World!" << std::endl;
    helloA();
    helloB();
    return 0;
}

输出

Hello, World!
静态库A
静态库B
静态库B中调用静态库A
静态库A

命令行输入ldd final

test@ubuntu:~/CLionProjects/lib_test/final/build$ ldd final 
        不是动态可执行文件

工程源码

链接

提取码:6666

继续阅读

更多来自我们博客的帖子

如何安装 BuddyPress
由 测试 December 17, 2023
经过差不多一年的开发,BuddyPress 这个基于 WordPress Mu 的 SNS 插件正式版终于发布了。BuddyPress...
阅读更多
Filter如何工作
由 测试 December 17, 2023
在 web.xml...
阅读更多
如何理解CGAffineTransform
由 测试 December 17, 2023
CGAffineTransform A structure for holding an affine transformation matrix. ...
阅读更多