cmake使用实践(一)

来源:互联网 发布:太极集团知乎 编辑:程序博客网 时间:2024/05/18 03:15

cmake使用实践(一)

1.初试cmake,编写简单的helloworld

本节选择了一个最简单的例子Helloworld来演练一下cmake的完整构建过程,本节并不会深入的探讨cmake,仅仅展示一个简单的例子,平台为ubuntu16.04操作系统

1、准备工作

首先建立一个cmake文件夹,所有的cmake文件都放在这个文件夹中,并且建立一个新的文件夹test1(可自行定义目录)

<pre name="code" class="html">$mkdir cmake$cd cmake$mkdir test1
建立两个文件,分别为hello.cpp CMakeLists.txt(这个文件名为固定格式),内容为
#include<iostream>using namespace std;int main(){    cout << "Hello Cmake!!!" << endl;    return 0;}

CMakeLists.txt
project(hello)set(SRC_LIST hello.cpp)message(STATUS "this is binary dir" ${HELLO_BINARY_DIR})message(STATUS "this is source dir" ${HELLO_SOURCE_DIR})add_executable(hello ${SRC_LIST})

2、构建文件
cmake .        //注意这个点,点代表目录
输出(大致输出内容)
$cmake .-- The C compiler identification is GNU 5.4.0-- The CXX compiler identification is GNU 5.4.0-- Check for working C compiler: /usr/bin/cc-- Check for working C compiler: /usr/bin/cc -- works-- Detecting C compiler ABI info-- Detecting C compiler ABI info - done-- Detecting C compile features-- Detecting C compile features - done-- Check for working CXX compiler: /usr/bin/c++-- Check for working CXX compiler: /usr/bin/c++ -- works-- Detecting CXX compiler ABI info-- Detecting CXX compiler ABI info - done-- Detecting CXX compile features-- Detecting CXX compile features - done-- this is binary dir-- this is source dir-- Configuring done-- Generating done-- Build files have been written to: /home/quan/cmake/test1
用ls查看目录内生成的文件,大概是这样
$ lsCMakeCache.txt  CMakeFiles  cmake_install.cmake  CMakeLists.txt  hello.cpp  Makefile
你会发现生成了上面几个文件,最重要的是生成了Makefile,其他文件暂时别管,不用理解,运行make(可用 make VERBOSE=1查看详细构建过程)
$ makeScanning dependencies of target hello[ 50%] Building CXX object CMakeFiles/hello.dir/hello.cpp.o[100%] Linking CXX executable hello[100%] Built target hello
会产生如上内容,并且会生成一个hello可执行文件

3、解析CMakeLists.txt
project
语法
project(projectname [CXX][C][JAVA] )
可以用这个指令定义工程名称,并可制定工程支持语言,支持的语言列表是可以忽略的。这个指令隐式的定义了定义了两个cmake变量:
<projectname>_BINARY_DIR<projectname>_SOURCE_DIR可以直接调用,上面的message就直接引用了这两个变量,也可以直接用PROJECT_BINARY_DIR,PROJECT_SOURCE_DIR(推荐使用,方便管理)

set
语法 set(VAR [VALUE] [CACHE TYPE DOCSTRING [FORCE] ])
目前只要了解可以用来显示的定义变量即可
多个源文件也可以定义成:
set(SRC_LIST  hello.cpp test.cpp test1.cpp)

message
语法message([SEND_ERROR | STATUS | FATAL_ERROR]  "message to display"  ...)
向终端输出用户定义的信息,有三种类型
SEND_ERROR,产生错误、生成过程被跳过。
STATUS,输出前缀为--的信息。
FATAL_ERROR,立即终止所有cmake过程

add_executable(hello ${SRC_LIST})
定义这个工程会生成文件名为hello的可执行文件,相关的源文件是SRC_LIST中定义的文件列表。${}是cmake的变量应用方式。

注:命令格式不区分大小写,本人倾向于使用小写


1 0
原创粉丝点击