CMake 链接静态库 示例

2022-08-31 14:24:03 浏览数 (3)

现有

lib-a, lib-b

可执行文件

final

链接情况

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

lib-a

CMakeLists.txt

代码语言:javascript复制
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

代码语言:javascript复制
#ifndef LIB_A_LIBRARY_A_H
#define LIB_A_LIBRARY_A_H

void helloA();

#endif //LIB_A_LIBRARY_A_H

library_a.cpp

代码语言:javascript复制
#include "library_a.h"

#include <iostream>

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

CMakeLists.txt

代码语言:javascript复制
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

代码语言:javascript复制
#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

代码语言:javascript复制
#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

代码语言:javascript复制
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

代码语言:javascript复制
#include <iostream>

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

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

输出

代码语言:javascript复制
Hello, World!
静态库A
静态库B
静态库B中调用静态库A
静态库A

命令行输入ldd final

代码语言:javascript复制
test@ubuntu:~/CLionProjects/lib_test/final/build$ ldd final 
        不是动态可执行文件

工程源码

链接

提取码:6666

0 人点赞