原文:https://zhuanlan.zhihu.com/p/149828002

0. 序

CMake 是一个跨平台的开源构建工具,使用 CMake 能够方便地管理依赖多个库的目录层次结构并生成 makefile 和使用 GNU make 来编译和连接程序。

1. 构建单个文件

1.1 使用 GCC 编译

假设现在我们希望编写一个函数来实现安全的 int 类型加法防止数据溢出,这个源文件没有任何依赖的源码或静态库:

  1. // safe_add.cpp
  2. #include <iostream>
  3. #include <memory>
  4. #define INT_MAX 2147483647
  5. #define ERROR_DATA_OVERFLOW 2
  6. int SafeIntAdd(std::unique_ptr<int> &sum, int a, int b)
  7. {
  8. if (a > INT_MAX - b)
  9. {
  10. *sum = INT_MAX;
  11. return ERROR_DATA_OVERFLOW;
  12. }
  13. *sum = a + b;
  14. return EXIT_SUCCESS;
  15. }
  16. int main()
  17. {
  18. int a, b;
  19. std::cin >> a >> b;
  20. std::unique_ptr<int> sum(new int(1));
  21. int res = SafeIntAdd(sum, a, b);
  22. std::cout << *sum << std::endl;
  23. return res;
  24. }

我们可以直接使用一句简单的 gcc 命令来编译这个文件并执行:

  1. [joelzychen@DevCloud ~/cmake-tutorial]$ g++ main.cc -g -Wall -std=c++11 -o SafeIntAdd
  2. [joelzychen@DevCloud ~/cmake-tutorial]$ ./SafeIntAdd
  3. 2100000000 2100000000
  4. 2147483647

1.2 使用 cmake 构建

如果要使用 cmake 来生成 makefile 的话我们需要首先新建一个 CMakeLists.txt 文件,cmake 的所有配置都在这个文件中完成,CMakeLists.txt 中的内容大致如下:

  1. cmake_minimum_required(VERSION 3.10)
  2. project(SafeIntAdd)
  3. set(CMAKE_CXX_COMPILER "c++")
  4. set(CMAKE_CXX_STANDARD 11)
  5. set(CMAKE_CXX_STANDARD_REQUIRED True)
  6. set(CMAKE_CXX_FLAGS -g -Wall)
  7. message(STATUS "CMAKE_CXX_FLAGS: " "${CMAKE_CXX_FLAGS}")
  8. string(REPLACE ";" " " CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
  9. message(STATUS "CMAKE_CXX_FLAGS: " "${CMAKE_CXX_FLAGS}")
  10. add_executable(SafeIntAdd main.cc)

其中有一些基础的 cmake 指令,它们的含义如下:

  1. cmake_minimum_required:cmake 的最低版本要求
  2. project:指定项目的名称
  3. set:设置普通变量,缓存变量或环境变量
  4. message:显示信息
  5. string:字符串查找和替换
  6. add_executable:使用列出的源文件构建可执行文件

有几个需要注意的点:

  1. cmake 的指令是不区分大小写的,写作 CMAKE_MINIMUM_REQUIRED 或 cmake_minimum_required,甚至是 cmAkE_mInImUm_rEquIrEd(不建议)都是可以的
  2. 在使用 set 指令指定 CMAKE_CXX_FLAGS 的时候通过空格来分隔多个编译选项,生成的 CMAKE_CXX_FLAGS 字符串是 “-g;-Wall”,需要用字符串替换string将分号替换为空格
  3. message 可以在构建的过程中向 stdout 输出一些信息,上面例子中的输出信息为:

bash -- CMAKE_CXX_FLAGS: -g;-Wall -- CMAKE_CXX_FLAGS: -g -Wall

  • 类似于 bash 脚本,在 CMakeLists.txt 中输出变量时要使用 “${CMAKE_CXX_FLAGS}” 的形式,而不能直接使用 CMAKE_CXX_FLAGS

编辑好 CMakeLists.txt 之后,我们可以新建一个 build 目录,并在 build 目录下使用 cmake 来进行构建,构建成功的话再使用 make 来进行编译和链接,最终得到 SafeAdd 这个可执行文件:

  1. [joelzychen@DevCloud ~/cmake-tutorial]$ mkdir build/
  2. [joelzychen@DevCloud ~/cmake-tutorial]$ cd build/
  3. [joelzychen@DevCloud ~/cmake-tutorial/build]$ cmake ..
  4. -- The C compiler identification is GNU 4.8.5
  5. -- The CXX compiler identification is GNU 4.8.5
  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. -- CMAKE_CXX_FLAGS: -g;-Wall
  19. -- CMAKE_CXX_FLAGS: -g -Wall
  20. -- Configuring done
  21. -- Generating done
  22. -- Build files have been written to: /home/joelzychen/cmake-tutorial/build
  23. [joelzychen@DevCloud ~/cmake-tutorial/build]$ make
  24. Scanning dependencies of target SafeIntAdd
  25. [ 50%] Building CXX object CMakeFiles/SafeIntAdd.dir/main.cc.o
  26. [100%] Linking CXX executable SafeIntAdd
  27. [100%] Built target SafeIntAdd
  28. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ./SafeIntAdd
  29. 2100000000 2100000000
  30. 2147483647

2. 构建多个文件

2.1 使用 GCC 编译

假设现在我们希望将加法函数放到单独的文件中去,并在 main 函数所在的源文件中包含这个文件:

  1. // main.cc
  2. #include "math.h"
  3. #include "error_code.h"
  4. #include <iostream>
  5. int main()
  6. {
  7. int a{ 0 }, b{ 0 }, c{ 0 };
  8. std::cin >> a >> b >> c;
  9. int sum{ 0 };
  10. int ret_val = SafeAdd(sum, a, b, c);
  11. std::cout << sum << std::endl;
  12. return ret_val;
  13. }
  14. // util/math.h
  15. #ifndef UTIL_MATH_H
  16. #define UTIL_MATH_H
  17. #include "error_code.h"
  18. #include <limits>
  19. template<typename ValueType>
  20. ValueType ValueTypeMax(ValueType)
  21. {
  22. return std::numeric_limits<ValueType>::max();
  23. }
  24. template<typename ValueType>
  25. int SafeAdd(ValueType &sum)
  26. {
  27. return exit_success;
  28. }
  29. template<typename ValueType, typename ...ValueTypes>
  30. int SafeAdd(ValueType &sum, const ValueType &value, const ValueTypes &...other_values)
  31. {
  32. int ret_val = SafeAdd<ValueType>(sum, other_values...);
  33. if (ret_val != exit_success)
  34. {
  35. return ret_val;
  36. }
  37. if (sum > ValueTypeMax(value) - value)
  38. {
  39. sum = ValueTypeMax(value);
  40. return error_data_overflow;
  41. }
  42. sum += value;
  43. return exit_success;
  44. }
  45. #endif
  46. // definition/error_code.h
  47. #ifndef DEFINITION_ERROR_CODE_H
  48. #define DEFINITION_ERROR_CODE_H
  49. constexpr int exit_success = 0;
  50. constexpr int exit_failure = 1;
  51. constexpr int error_data_overflow = 2;
  52. #endif

我们可以在使用 GCC 编译的时候使用 -I 参数指定头文件所在的目录:

  1. [joelzychen@DevCloud ~/safe_add]$ g++ -g -Wall -std=c++11 -Ilib -Idefinition -o SafeAdd main.cc
  2. [joelzychen@DevCloud ~/safe_add]$ ./SafeAdd
  3. 20000 50000 80000
  4. 150000

2.2 使用 cmake 构建

  1. cmake_minimum_required(VERSION 3.10)
  2. project(SafeIntAdd)
  3. set(CMAKE_CXX_COMPILER "c++")
  4. set(CMAKE_CXX_STANDARD 11)
  5. set(CMAKE_CXX_STANDARD_REQUIRED True)
  6. set(CMAKE_CXX_FLAGS -g -Wall)
  7. string(REPLACE ";" " " CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
  8. include_directories(util/ definition/)
  9. aux_source_directory(./ SOURCE_DIR)
  10. add_executable(SafeIntAdd ${SOURCE_DIR})

相比于构建单个文件,我们额外使用了两个指令:

  1. include_directories:添加多个头文件搜索路径,路径之间用空格分隔;如果将 util 和 definition 目录都添加到到搜索路径的话,在 include 的时候就不需要使用相对路径了
  2. aux_source_directory:在目录中查找所有源文件,并将这些源文件存储在变量 SOURCE_DIR 中;需要注意这个指令不会递归包含子目录

接下来进入 build 目录进行构建:

  1. [joelzychen@DevCloud ~/cmake-tutorial/build]$ rm -rf *
  2. [joelzychen@DevCloud ~/cmake-tutorial/build]$ cmake ..
  3. -- The C compiler identification is GNU 4.8.5
  4. -- The CXX compiler identification is GNU 4.8.5
  5. -- Check for working C compiler: /usr/bin/cc
  6. -- Check for working C compiler: /usr/bin/cc - works
  7. -- Detecting C compiler ABI info
  8. -- Detecting C compiler ABI info - done
  9. -- Detecting C compile features
  10. -- Detecting C compile features - done
  11. -- Check for working CXX compiler: /usr/bin/c++
  12. -- Check for working CXX compiler: /usr/bin/c++ - works
  13. -- Detecting CXX compiler ABI info
  14. -- Detecting CXX compiler ABI info - done
  15. -- Detecting CXX compile features
  16. -- Detecting CXX compile features - done
  17. -- Configuring done
  18. -- Generating done
  19. -- Build files have been written to: /home/joelzychen/cmake-tutorial/build
  20. [joelzychen@DevCloud ~/cmake-tutorial/build]$ make
  21. Scanning dependencies of target SafeIntAdd
  22. [ 50%] Building CXX object CMakeFiles/SafeIntAdd.dir/main.cc.o
  23. [100%] Linking CXX executable SafeIntAdd
  24. [100%] Built target SafeIntAdd
  25. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ./SafeIntAdd
  26. 2000000000 1900000000
  27. 2147483647

3. 构建依赖于静态库的项目

关于静态库和动态库相关内容可以参考浅谈静态库和动态库

3.1 使用 GCC 编译静态库文件

假设现在我们希望将 exp2 函数封装到一个计算器单例类中,并计算 2 的 n 次方,并为此编写了以下这些文件:

  1. // main.cc
  2. #include "util/calculator.h"
  3. #include "definition/error_code.h"
  4. #include <iostream>
  5. int main()
  6. {
  7. double a{ 0 };
  8. std::cin >> a;
  9. double exp2{ 0 };
  10. int ret_val = Calculator::GetInstance().Exp2(exp2, a);
  11. if (ret_val != exit_success)
  12. {
  13. return ret_val;
  14. }
  15. std::cout << exp2 << std::endl;
  16. return exit_success;
  17. }
  18. // util/singleton.h
  19. #ifndef UTIL_SINGLETON_H
  20. #define UTIL_SINGLETON_H
  21. template <typename T>
  22. class Singleton
  23. {
  24. public:
  25. static T& GetInstance()
  26. {
  27. static T instance;
  28. return instance;
  29. }
  30. Singleton(Singleton const &) = delete;
  31. Singleton& operator=(Singleton const &) = delete;
  32. protected:
  33. Singleton() = default;
  34. ~Singleton() = default;
  35. };
  36. #endif
  37. // definition/error_code.h
  38. #ifndef DEFINITION_ERROR_CODE_H
  39. #define DEFINITION_ERROR_CODE_H
  40. constexpr int exit_success = 0;
  41. constexpr int exit_failure = 1;
  42. constexpr int error_data_overflow = 2;
  43. #endif
  44. // util/calculator.h
  45. #ifndef UTIL_CALCULATOR_H
  46. #define UTIL_CALCULATOR_H
  47. #include "singleton.h"
  48. #include "../definition/error_code.h"
  49. #include <limits>
  50. #include <cmath>
  51. class Calculator : public Singleton<Calculator>
  52. {
  53. public:
  54. template<typename ValueType>
  55. ValueType ValueTypeMax(ValueType)
  56. {
  57. return std::numeric_limits<ValueType>::max();
  58. }
  59. int Exp2(double &exp2, const double &val);
  60. };
  61. #endif

为了方便生成静态库文件,我们先将 http://calculator.cc 这个文件放到 archive 目录下:

  1. // archive/calculator.cc
  2. #include "../util/calculator.h"
  3. int Calculator::Exp2(double &exp2, const double &val)
  4. {
  5. if (std::sqrt(ValueTypeMax(val)) < val)
  6. {
  7. exp2 = ValueTypeMax(val);
  8. return error_data_overflow;
  9. }
  10. exp2 = std::exp2(val);
  11. return exit_success;
  12. }

对于 http://calculator.cc 这个源文件,我们可以使用 -c 参数将其编译为 obj 文件,再使用 ar 归档就能将其编译为一个 .a 库文件了::

  1. [joelzychen@DevCloud ~/cmake-tutorial/archive]$ g++ calculator.cc -g -Wall -std=c++11 -c
  2. [joelzychen@DevCloud ~/cmake-tutorial/archive]$ ar -crv libcalculator.a calculator.o
  3. a - calculator.o

3.2 使用 GCC 编译项目和链接静态库

现在的目录结构如下:

  1. [joelzychen@DevCloud ~/cmake-tutorial]$ tree
  2. .
  3. |-- archive
  4. | |-- calculator.cc
  5. | |-- calculator.o
  6. | `-- libcalculator.a
  7. |-- CMakeLists.txt
  8. |-- definition
  9. | `-- error_code.h
  10. |-- main.cc
  11. `-- util
  12. |-- calculator.h
  13. `-- singleton.h
  14. 3 directories, 8 files

使用 GCC 编译和链接到对应的静态库文件即可得到可执行文件:

  1. [joelzychen@DevCloud ~/cmake-tutorial]$ g++ main.cc -g -Wall -std=c++11 -o Exp2 -Larchive -lcalculator
  2. [joelzychen@DevCloud ~/cmake-tutorial]$ ll Exp2
  3. 32K -rwxrwxr-x 1 joelzychen joelzychen 31K Jun 21 14:38 Exp2
  4. [joelzychen@DevCloud ~/cmake-tutorial]$ ./Exp2
  5. 8
  6. 256

需要注意的点有:

  1. -Larchive 用于指定库文件目录archive
  2. -lcalculator 用于指定库文件libcalculator.a, 省略前缀lib和后缀名.a
  3. -L 和 -l 参数一定要在 -o 参数之后

3.3 使用 cmake 构建项目和链接静态库

我们刚才已经用 GCC 编译好了静态库文件,所以可以直接在 CMakeLists.txt 里添加链接静态库的指令:

  1. cmake_minimum_required(VERSION 3.10)
  2. project(Exp2)
  3. set(CMAKE_CXX_COMPILER "c++")
  4. set(CMAKE_CXX_STANDARD 11)
  5. set(CMAKE_CXX_STANDARD_REQUIRED True)
  6. set(CMAKE_CXX_FLAGS -g -Wall)
  7. string(REPLACE ";" " " CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
  8. set(CMAKE_RUNTIME_OUTPUT_DIRECTORY bin/)
  9. message(STATUS "source dir: " ${PROJECT_SOURCE_DIR})
  10. message(STATUS "binary dir: " ${PROJECT_BINARY_DIR})
  11. message(STATUS "output dir: " ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
  12. include_directories(./)
  13. aux_source_directory(./ SOURCE_DIR)
  14. link_directories(archive/)
  15. add_executable(Exp2 ${SOURCE_DIR})
  16. target_link_libraries(Exp2 libcalculator.a)
  17. # target_link_libraries(Exp2 calculator)

和之前相比,新使用的指令有:

  1. link_directories:指定静态库或动态库的搜索路径。注意:link_directories在add_executable之前。
  2. target_link_libraries:将指定的静态库连接到可执行文件上,calculator和 libcalculator.a 两种形式等价。注意:target_link_libraries在add_executable之后。
  3. set(CMAKE_RUNTIME_OUTPUT_DIRECTORY bin/) 命令将生成的二进制文件放到了 bin 目录下

然后进入 build 目录进行构建:

  1. [joelzychen@DevCloud ~/cmake-tutorial/build]$ rm -rf *
  2. [joelzychen@DevCloud ~/cmake-tutorial/build]$ cmake ../
  3. -- The C compiler identification is GNU 4.8.5
  4. -- The CXX compiler identification is GNU 4.8.5
  5. -- Check for working C compiler: /usr/bin/cc
  6. -- Check for working C compiler: /usr/bin/cc - works
  7. -- Detecting C compiler ABI info
  8. -- Detecting C compiler ABI info - done
  9. -- Detecting C compile features
  10. -- Detecting C compile features - done
  11. -- Check for working CXX compiler: /usr/bin/c++
  12. -- Check for working CXX compiler: /usr/bin/c++ - works
  13. -- Detecting CXX compiler ABI info
  14. -- Detecting CXX compiler ABI info - done
  15. -- Detecting CXX compile features
  16. -- Detecting CXX compile features - done
  17. -- source dir: /home/joelzychen/cmake-tutorial
  18. -- binary dir: /home/joelzychen/cmake-tutorial/build
  19. -- output dir: /home/joelzychen/cmake-tutorial/build/bin/
  20. -- Configuring done
  21. -- Generating done
  22. -- Build files have been written to: /home/joelzychen/cmake-tutorial/build
  23. [joelzychen@DevCloud ~/cmake-tutorial/build]$ make
  24. Scanning dependencies of target Exp2
  25. [ 50%] Building CXX object CMakeFiles/Exp2.dir/main.cc.o
  26. [100%] Linking CXX executable bin/Exp2
  27. [100%] Built target Exp2
  28. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ll bin/Exp2
  29. 32K -rwxrwxr-x 1 joelzychen joelzychen 31K Jun 21 14:58 bin/Exp2
  30. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ./bin/Exp2
  31. 6
  32. 64

可以看到通过 cmake 构建得到二进制文件大小和直接通过 GCC 编译和链接得到的二进制文件大小是相同的。这次用 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY bin/) 命令将生成的二进制文件放到了 bin 目录下,注意这里的 bin 目录是使用 cmake 进行构建的目录(PROJECT_BINARY_DIR),不是 CMakeLists.txt 所在的目录(PROJECT_SOURCE_DIR)。

3.4 使用 cmake 构建静态库文件和项目

除了直接引用外部的静态库,cmake 还可以先将源文件编译成静态库之后在进行构建:

  1. cmake_minimum_required(VERSION 3.10)
  2. set(project_name Exp2)
  3. project(${project_name})
  4. set(CMAKE_CXX_COMPILER "c++")
  5. set(CMAKE_CXX_STANDARD 11)
  6. set(CMAKE_CXX_STANDARD_REQUIRED True)
  7. set(CMAKE_CXX_FLAGS -g -Wall)
  8. string(REPLACE ";" " " CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
  9. set(CMAKE_RUNTIME_OUTPUT_DIRECTORY bin/)
  10. message(STATUS "source dir: " ${PROJECT_SOURCE_DIR})
  11. message(STATUS "binary dir: " ${PROJECT_BINARY_DIR})
  12. message(STATUS "output dir: " "${PROJECT_BINARY_DIR}/${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
  13. include_directories(./)
  14. aux_source_directory(./ SOURCE_DIR)
  15. set(static_lib_source_file archive/calculator.cc)
  16. add_library(calculator_static STATIC ${static_lib_source_file})
  17. add_executable(${project_name} ${SOURCE_DIR})
  18. target_link_libraries(${project_name} calculator_static)

这里用到了一个新的指令 add_library 来使用指定的源文件生成库文件,再使用 target_link_libraries 将生成的库文件添加到项目中;接下来进行构建:

  1. [joelzychen@DevCloud ~/cmake-tutorial/build]$ rm -rf *
  2. [joelzychen@DevCloud ~/cmake-tutorial/build]$ cmake ../
  3. -- The C compiler identification is GNU 4.8.5
  4. -- The CXX compiler identification is GNU 4.8.5
  5. -- Check for working C compiler: /usr/bin/cc
  6. -- Check for working C compiler: /usr/bin/cc - works
  7. -- Detecting C compiler ABI info
  8. -- Detecting C compiler ABI info - done
  9. -- Detecting C compile features
  10. -- Detecting C compile features - done
  11. -- Check for working CXX compiler: /usr/bin/c++
  12. -- Check for working CXX compiler: /usr/bin/c++ - works
  13. -- Detecting CXX compiler ABI info
  14. -- Detecting CXX compiler ABI info - done
  15. -- Detecting CXX compile features
  16. -- Detecting CXX compile features - done
  17. -- source dir: /home/joelzychen/cmake-tutorial
  18. -- binary dir: /home/joelzychen/cmake-tutorial/build
  19. -- output dir: /home/joelzychen/cmake-tutorial/build/bin/
  20. -- Configuring done
  21. -- Generating done
  22. -- Build files have been written to: /home/joelzychen/cmake-tutorial/build
  23. [joelzychen@DevCloud ~/cmake-tutorial/build]$ make
  24. Scanning dependencies of target calculator_static
  25. [ 25%] Building CXX object CMakeFiles/calculator_static.dir/archive/calculator.cc.o
  26. [ 50%] Linking CXX static library libcalculator_static.a
  27. [ 50%] Built target calculator_static
  28. Scanning dependencies of target Exp2
  29. [ 75%] Building CXX object CMakeFiles/Exp2.dir/main.cc.o
  30. [100%] Linking CXX executable bin/Exp2
  31. [100%] Built target Exp2
  32. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ll | grep calculator
  33. 12K -rw-rw-r-- 1 joelzychen joelzychen 11K Jun 21 15:30 libcalculator_static.a
  34. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ./bin/Exp2
  35. 5
  36. 32

可以看到在 build 目录下生成了一个名为 libcalculator_static.a 的静态库文件,这个名字是由使用 add_library 指令时的第一个参数指定的。

4. 构建依赖于动态库的项目

4.1 使用 GCC 编译动态库文件

仍然使用之前已有的文件,在 archive 目录下生成动态库文件:

  1. [joelzychen@DevCloud ~/cmake-tutorial/archive]$ rm calculator.o libcalculator.a
  2. [joelzychen@DevCloud ~/cmake-tutorial/archive]$ g++ calculator.cc -g -Wall -std=c++11 -c -fPIC
  3. [joelzychen@DevCloud ~/cmake-tutorial/archive]$ g++ calculator.o -g -Wall -std=c++11 -shared -o libcalculator.so

分为两个步骤:

  1. 使用 -c 和 -fPIC 参数生成位置无关的(position independent code)机器码 .o 文件
  2. 使用 -shared 参数生成 .so 动态库文件

也可以合并为一个步骤:

  1. [joelzychen@DevCloud ~/cmake-tutorial/archive]$ g++ calculator.cc -g -Wall -std=c++11 -shared -fPIC -o libcalculator.so

这样可以直接生成动态库文件,省去生成机器码文件的中间步骤。

4.2 使用 GCC 编译项目和链接动态库

和链接到静态库类似,在编译后链接动态库即可生成二进制文件:

  1. [joelzychen@DevCloud ~/cmake-tutorial]$ g++ main.cc -g -Wall -std=c++11 -o Exp2 -Larchive -lcalculator
  2. [joelzychen@DevCloud ~/cmake-tutorial]$ ./Exp2
  3. ./Exp2: error while loading shared libraries: libcalculator.so: cannot open shared object file: No such file or directory

我们发现在运行二级制文件时会出现找不到动态库的报错,这是因为动态链接库环境变量的目录下没有找到编译时所用到的动态库,我们可以将对应的目录添加到环境变量下,或是将动态库拷贝到环境变量的目录下:

  1. [joelzychen@DevCloud ~/cmake-tutorial]$ echo $LD_LIBRARY_PATH
  2. [joelzychen@DevCloud ~/cmake-tutorial]$ export LD_LIBRARY_PATH="/usr/lib/"
  3. [joelzychen@DevCloud ~/cmake-tutorial]$ sudo cp archive/libcalculator.so /usr/lib/

接下来就可以运行可执行文件了,可以看到使用链接动态库方式生成的可执行文件的大小要小于使用链接静态库方式生成的可执行文件,使用 ldd 命令也能看到可执行文件是正确地调用了对应的动态库文件:

  1. [joelzychen@DevCloud ~/cmake-tutorial]$ ./Exp2
  2. 9
  3. 512
  4. [joelzychen@DevCloud ~/cmake-tutorial]$ ll Exp2
  5. 28K -rwxrwxr-x 1 joelzychen joelzychen 28K Jun 21 14:25 Exp2
  6. [joelzychen@DevCloud ~/cmake-tutorial]$ ldd Exp2 | grep calculator
  7. libcalculator.so => /usr/lib/libcalculator.so (0x00007fd2391f0000)

4.3 使用 cmake 构建项目和链接动态库

和构建静态库类似,只需要将 CMakeLists.txt 中链接静态库的指令修改为链接动态库即可进行构建:

  1. cmake_minimum_required(VERSION 3.10)
  2. project(Exp2)
  3. set(CMAKE_CXX_COMPILER "c++")
  4. set(CMAKE_CXX_STANDARD 11)
  5. set(CMAKE_CXX_STANDARD_REQUIRED True)
  6. set(CMAKE_CXX_FLAGS -g -Wall)
  7. string(REPLACE ";" " " CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
  8. set(CMAKE_RUNTIME_OUTPUT_DIRECTORY bin/)
  9. message(STATUS "source dir: " ${PROJECT_SOURCE_DIR})
  10. message(STATUS "binary dir: " ${PROJECT_BINARY_DIR})
  11. message(STATUS "output dir: " "${PROJECT_BINARY_DIR}/${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
  12. include_directories(./)
  13. aux_source_directory(./ SOURCE_DIR)
  14. link_directories(archive/)
  15. add_executable(Exp2 ${SOURCE_DIR})
  16. target_link_libraries(Exp2 libcalculator.so)

重新构建和运行

  1. [joelzychen@DevCloud ~/cmake-tutorial/build]$ rm -rf *
  2. [joelzychen@DevCloud ~/cmake-tutorial/build]$ cmake ../
  3. -- The C compiler identification is GNU 4.8.5
  4. -- The CXX compiler identification is GNU 4.8.5
  5. -- Check for working C compiler: /usr/bin/cc
  6. -- Check for working C compiler: /usr/bin/cc - works
  7. -- Detecting C compiler ABI info
  8. -- Detecting C compiler ABI info - done
  9. -- Detecting C compile features
  10. -- Detecting C compile features - done
  11. -- Check for working CXX compiler: /usr/bin/c++
  12. -- Check for working CXX compiler: /usr/bin/c++ - works
  13. -- Detecting CXX compiler ABI info
  14. -- Detecting CXX compiler ABI info - done
  15. -- Detecting CXX compile features
  16. -- Detecting CXX compile features - done
  17. -- source dir: /home/joelzychen/cmake-tutorial
  18. -- binary dir: /home/joelzychen/cmake-tutorial/build
  19. -- output dir: /home/joelzychen/cmake-tutorial/build/bin/
  20. -- Configuring done
  21. -- Generating done
  22. -- Build files have been written to: /home/joelzychen/cmake-tutorial/build
  23. [joelzychen@DevCloud ~/cmake-tutorial/build]$ make
  24. Scanning dependencies of target Exp2
  25. [ 50%] Building CXX object CMakeFiles/Exp2.dir/main.cc.o
  26. [100%] Linking CXX executable bin/Exp2
  27. [100%] Built target Exp2
  28. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ll bin/Exp2
  29. 28K -rwxrwxr-x 1 joelzychen joelzychen 28K Jun 21 15:04 bin/Exp2
  30. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ldd bin/Exp2 | grep calculator
  31. libcalculator.so => /home/joelzychen/cmake-tutorial/archive/libcalculator.so (0x00007f4c87e35000)
  32. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ./bin/Exp2
  33. 6
  34. 64

可以看到通过 cmake 构建得到二进制文件大小和直接通过 GCC 编译和链接动态库得到的二进制文件大小也是相同的。

4.4 使用 cmake 构建动态库文件和项目

使用 cmake 构建动态库的步骤和构建静态库的步骤几乎一模一样,只需要将 add_library 的 STATIC 参数改为 SHARED 即可:

  1. cmake_minimum_required(VERSION 3.10)
  2. set(project_name Exp2)
  3. project(${project_name})
  4. set(CMAKE_CXX_COMPILER "c++")
  5. set(CMAKE_CXX_STANDARD 11)
  6. set(CMAKE_CXX_STANDARD_REQUIRED True)
  7. set(CMAKE_CXX_FLAGS -g -Wall)
  8. string(REPLACE ";" " " CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
  9. set(CMAKE_RUNTIME_OUTPUT_DIRECTORY bin/)
  10. message(STATUS "source dir: " ${PROJECT_SOURCE_DIR})
  11. message(STATUS "binary dir: " ${PROJECT_BINARY_DIR})
  12. message(STATUS "output dir: " "${PROJECT_BINARY_DIR}/${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
  13. include_directories(./)
  14. aux_source_directory(./ SOURCE_DIR)
  15. set(shared_lib_source_file archive/calculator.cc)
  16. add_library(calculator_shared SHARED ${shared_lib_source_file})
  17. add_executable(${project_name} ${SOURCE_DIR})
  18. target_link_libraries(${project_name} calculator_shared)

构建和运行:

  1. [joelzychen@DevCloud ~/cmake-tutorial/build]$ rm -rf *
  2. [joelzychen@DevCloud ~/cmake-tutorial/build]$ cmake ..
  3. -- The C compiler identification is GNU 4.8.5
  4. -- The CXX compiler identification is GNU 4.8.5
  5. -- Check for working C compiler: /usr/bin/cc
  6. -- Check for working C compiler: /usr/bin/cc - works
  7. -- Detecting C compiler ABI info
  8. -- Detecting C compiler ABI info - done
  9. -- Detecting C compile features
  10. -- Detecting C compile features - done
  11. -- Check for working CXX compiler: /usr/bin/c++
  12. -- Check for working CXX compiler: /usr/bin/c++ - works
  13. -- Detecting CXX compiler ABI info
  14. -- Detecting CXX compiler ABI info - done
  15. -- Detecting CXX compile features
  16. -- Detecting CXX compile features - done
  17. -- source dir: /home/joelzychen/cmake-tutorial
  18. -- binary dir: /home/joelzychen/cmake-tutorial/build
  19. -- output dir: /home/joelzychen/cmake-tutorial/build/bin/
  20. -- Configuring done
  21. -- Generating done
  22. -- Build files have been written to: /home/joelzychen/cmake-tutorial/build
  23. [joelzychen@DevCloud ~/cmake-tutorial/build]$ make
  24. Scanning dependencies of target calculator_shared
  25. [ 25%] Building CXX object CMakeFiles/calculator_shared.dir/archive/calculator.cc.o
  26. [ 50%] Linking CXX shared library libcalculator_shared.so
  27. [ 50%] Built target calculator_shared
  28. Scanning dependencies of target Exp2
  29. [ 75%] Building CXX object CMakeFiles/Exp2.dir/main.cc.o
  30. [100%] Linking CXX executable bin/Exp2
  31. [100%] Built target Exp2
  32. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ll | grep calculator
  33. 16K -rwxrwxr-x 1 joelzychen joelzychen 13K Jun 21 15:34 libcalculator_shared.so
  34. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ll bin/Exp2
  35. 28K -rwxrwxr-x 1 joelzychen joelzychen 28K Jun 21 15:34 bin/Exp2
  36. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ldd bin/Exp2 | grep calculator
  37. libcalculator_shared.so => /home/joelzychen/cmake-tutorial/build/libcalculator_shared.so (0x00007f1fa5aa5000)
  38. [joelzychen@DevCloud ~/cmake-tutorial/build]$ ./bin/Exp2
  39. 7
  40. 128

可以看到得到的二进制文件的相关信息和使用前几种方法得到的都是相同的。

5. 总结

本文通过几个示例程序对比了在 Linux 下使用 GCC 和 cmake 来编译和构建程序的基本步骤,了解了一些 cmake 的基础指令。实际开发中的项目往往会非常大,以致于不能够直接使用 GCC 来编译整个项目,在这种场景下使用 cmake 进行构建往往能够节省时间和提高效率,让我们能够专注在项目的开发上。在实际应用中编写 CMakeLists.txt 的时候还会遇到非常多的问题、不熟悉的指令和其他的使用技巧,这些都需要结合教程和实践来进一步学习。