Cmake如何简化生成过程:第1部分(基本编译系统)

本文介绍如何使用CMake简化项目的构建过程。通过设置项目名称、指定所需CMake版本、使用宏确保外部构建,并定义源文件,可以轻松创建复杂的构建系统。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关键字: 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 构建一个从基本到复杂项目有用的技巧系列的第一部分。如果您需要进一步信息,请您在 本教程的网站 看看。

 

附:原文及原文地址: http://cabledogs.org/abinader/2009/12/07/how-cmake-simplifies-the-build-process-part-1-basic-build-system/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值