如何在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库
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
2018-03-05 CUDA 纹理的使用