关键字: Cmake research tutorial work
经过长时间与博客隔绝(主要是因为内部工作烦透了,搞得我头都大了),我想分享学习如何使用 CMake 的经验。我必须承认,作为一个以前的 autotools (又叫做 auto-hell )和 qmake 用户我得到一点点关于 CMake 的偏见,但看过几个例子和阅读一些文档后,我发现它比以前我用过的构建系统更容易学习和使用。基本上, CMake 的使用一系列宏和函数用一种简单而准确的方式为您找到所需的组件,这意味着没有任何不必要的依赖关系!
例如,我发现一个非常有用的宏调用 MacroOutOfSourceBuild ,这个宏要求用户在源码目录外编译代码(编译目录 = ! 代码目录)。通过这种方式,是非常好的实践,确保了用户使用影子编译目录。闲话少说,让我们看一些代码示例。假定你有一个小项目 —“Hello World” ( helloworld-part1.tgz ),代码文件安排如下:
helloworld/
/_ CMakeLists.txt
/_ cmake/
/_ modules/
/_ MacroOutOfSourceBuild.cmake
/_ src/
/_ CMakeLists.txt
/_ main.cpp
/_ helloworld.cpp
/_ helloworld.h
在上面的例子,文件 helloworld.cpp , main.cpp 中和 hello.h 位于里面的 src/ 目录,而 src 本身就是在项目的根目录中。 CMake 的 规定,每个项目目录(包括递归子目录),其中包含源代码应该有一个所谓的 CMakeLists.txt ,其中包含建立每个目录的说明。 由于“ Hello World “的项目确实有两个目录(根目录加 src / 目录),然后两个的 CMakeLists.txt 文件的创建(如下所示):
l 根目录 CMakeLists.txt
# Project name is not mandatory, but you should use it
project ( helloworld)
# States that CMake required version must be >= 2.6
cmake_minimum_required ( VERSION 2.6)
# Appends the cmake/modules path inside the MAKE_MODULE_PATH variable which stores the
# directories of additional CMake modules (eg MacroOutOfSourceBuild.cmake):
set ( CMAKE_MODULE_PATH ${helloworld_SOURCE_DIR} /cmake/modules ${CMAKE_MODULE_PATH} )
l src 目录 CMakeLists.txt
# The macro below forces the build directory to be different from source directory:
include ( MacroOutOfSourceBuild)
macro_ensure_out_of_source_build(
"
${PROJECT_NAME}
requires an out of source build."
)
add_subdirectory ( src)
# Include the directory itself as a path to include directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Create a variable called helloworld_SOURCES containing all .cpp files:
set(helloworld_SOURCES helloworld.cpp main.cpp)
# For a large number of source files you can create it in a simpler way
# using file() function:
# file(GLOB hellworld_SOURCES *.cpp)
# Create an executable file called helloworld from sources:
add_executable(helloworld ${helloworld_SOURCES})
现在你创建一个影子编译目录 ( 比如: build/) 并编译你的项目,如下面这些命令:
$ mkdir build
$ cd build
$ cmake ..
$ make
就是这样!这完成了关于使用 Cmake 构建一个从基本到复杂项目有用的技巧系列的第一部分。如果您需要进一步信息,请您在 本教程的网站 看看。