-
cmake_minimum_required:指定运行此配置文件所需的 CMake 的最低版本;
project:参数值是 Demo1,该命令表示项目的名称是 Demo1 。
add_executable: 将名为 main.cc 的源文件编译成一个名称为 Demo 的可执行文件。
编译项目
之后,在当前目录执行 cmake . ,得到 Makefile 后再使用 make 命令编译得到 Demo1 可执行文件。
[ehome@xman Demo1]$ cmake . -- The C compiler identification is GNU 4.8.2 -- The CXX compiler identification is GNU 4.8.2 -- Check for working C compiler: /usr/sbin/cc -- Check for working C compiler: /usr/sbin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working CXX compiler: /usr/sbin/c++ -- Check for working CXX compiler: /usr/sbin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Configuring done -- Generating done -- Build files have been written to: /home/ehome/Documents/programming/C/power/Demo1 [ehome@xman Demo1]$ make Scanning dependencies of target Demo [100%] Building C object CMakeFiles/Demo.dir/main.cc.o Linking C executable Demo [100%] Built target Demo [ehome@xman Demo1]$ ./Demo 5 4 5 ^ 4 is 625 [ehome@xman Demo1]$ ./Demo 7 3 7 ^ 3 is 343 [ehome@xman Demo1]$ ./Demo 2 10 2 ^ 10 is 1024
多个源文件
同一目录,多个源文件
本小节对应的源代码所在目录:Demo2。
上面的例子只有单个源文件。现在假如把 power 函数单独写进一个名为MathFunctions.c 的源文件里,使得这个工程变成如下的形式:
./Demo2
|
+--- main.cc
|
+--- MathFunctions.cc
|
+--- MathFunctions.h
这个时候,CMakeLists.txt 可以改成如下的形式:
# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
# 项目信息
project (Demo2)
# 指定生成目标
add_executable(Demo main.cc MathFunctions.cc)
唯一的改动只是在 add_executable 命令中增加了一个 MathFunctions.cc 源文件。这样写当然没什么问题,但是如果源文件很多,把所有源文件的名字都加进去将是一件烦人的工作。更省事的方法是使用 aux_source_directory 命令,该命令会查找指定目录下的所有源文件,然后将结果存进指定变量名。其语法如下:
aux_source_directory(<dir> <variable>)
因此,可以修改 CMakeLists.txt 如下:
# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
# 项目信息
project (Demo2)
# 查找当前目录下的所有源文件
# 并将名称保存到 DIR_SRCS 变量
aux_source_directory(. DIR_SRCS)
# 指定生成目标
add_executable(Demo ${DIR_SRCS})










