如何在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库