如何在cmake中添加lib库

如何在cmake中添加lib库:

复制代码
 生成lib文件 libhello.a
add_library(hello hello.cxx)

# 在top level添加子目录
add_subdirectory(hello)

# 在顶层添加link依赖
target_link_libraries(Test PUBLIC hello)

# 添加targert依赖的头文件路径
target_include_directories(Test PUBLIC
                    "{PROJECT_BINARY_DIR}"
                    "{PROJECT_SOURCE_DIR}/hello")

# test.cxx添加头文件
#include "hello.hpp"
复制代码

接前篇,新增一个hello.hpp和hello.cpp的文件,期望将其打包为libhello.a被Test调用,具体操作:

  • 在test.cxx所在目录下创建hello,并在hello下分别创建hello.hpp、hello.cpp
  • void hello();

     

  • #include <iostream>
    #include "hello.hpp"
    void hello() {
        std::cout << "hello world" << std::endl;
    }

    在hello目录下新建CMakeLists.txt

  • add_library(hello hello.cxx)

    在顶层的CMakeLists.txt写入

  • target_link_libraries(Test PUBLIC hello)
    target_include_directories(Test PUBLIC
                    "{PROJECT_BINARY_DIR}"
                    "{PROJECT_SOURCE_DIR}/hello")

    test.cxx里添加头文件

  • 复制代码
    #include <iostream>
    #include <memory>
    #include "version.hpp"
    #include "hello.hpp"
    class A {
    public:
        A() { std::cout << "create A" << std::endl; }
        ~A() { std::cout << "destroy A" << std::endl; }
        void show() { std::cout << "call A function" << std::endl; }
    };
    int main() {
        std::cout << "VERSION:" << TEST_VERSION_MAJOR << "." << TEST_VERSION_MINOR << std::endl;
        std::unique_ptr<A> a = std::make_unique<A>();
        a->show();
        hello();
        return 0;
    }
    复制代码

    目录结构如下:

  • ├── build
    ├── CMakeLists.txt
    ├── hello
    │   ├── CMakeLists.txt
    │   ├── hello.cpp
    │   └── hello.hpp
    ├── test.cxx
    └── version.hpp.in

    在build下执行cmake .. && cmake --build .

    Test执行结果如下:

  • VERSION:1.0
    create A
    call A function
    hello world
    destroy A

    原文链接:cmake添加lib库

posted @   rainbow70626  阅读(1142)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2018-03-05 CUDA 纹理的使用
点击右上角即可分享
微信分享提示