一、介绍

如先前在第三方库中所述,较新版本的 CMake 允许您使用导入的 ALIAS imported 目标链接第三方库。

本教程中的文件树如下:

  1. $ tree
  2. .
  3. ├── CMakeLists.txt
  4. ├── main.cpp

二、环境版本

  • CMake v3.5+
  • 安装在默认位置的 boost 库

解析

§ 10.导入第三方库到目标 - 图1 导入目标

Imported targets 是 FindXXX 模块导出的只读目标。

在 CMake 命令中包含 boost 这个库:

  1. target_link_libraries( imported_targets
  2. PRIVATE
  3. Boost::filesystem
  4. )

作用是自动链接 Boost::filesystemBoost :: system 库,同时还包括 Boost 头文件目录。

三、编译例子

  1. $ mkdir build
  2. $ cd build/
  3. $ cmake ..
  4. -- The C compiler identification is GNU 5.4.0
  5. -- The CXX compiler identification is GNU 5.4.0
  6. -- Check for working C compiler: /usr/bin/cc
  7. -- Check for working C compiler: /usr/bin/cc -- works
  8. -- Detecting C compiler ABI info
  9. -- Detecting C compiler ABI info - done
  10. -- Detecting C compile features
  11. -- Detecting C compile features - done
  12. -- Check for working CXX compiler: /usr/bin/c++
  13. -- Check for working CXX compiler: /usr/bin/c++ -- works
  14. -- Detecting CXX compiler ABI info
  15. -- Detecting CXX compiler ABI info - done
  16. -- Detecting CXX compile features
  17. -- Detecting CXX compile features - done
  18. -- Boost version: 1.58.0
  19. -- Found the following Boost libraries:
  20. -- filesystem
  21. -- system
  22. boost found
  23. -- Configuring done
  24. -- Generating done
  25. -- Build files have been written to: /data/code/01-basic/K-imported-targets/build
  26. $ make
  27. Scanning dependencies of target imported_targets
  28. [ 50%] Building CXX object CMakeFiles/imported_targets.dir/main.cpp.o
  29. [100%] Linking CXX executable imported_targets
  30. [100%] Built target imported_targets
  31. $ ./imported_targets
  32. Hello Third Party Include!
  33. Path is not relative