cmake入门

在这里将运用cmake的内部构建和外部构建

首先创建一个文件夹

mkdir cmake_test

cd make_test

首先创建一个helloc.c文件

1 #include<stdio.h>                                                                 
2 
3 int main(int argc, char **agrv) {
4 
5     printf("Hello world from cMake pro1\n");
6 
7 
8     return 0; 
9 }

然后创建一个CMakeLists.txt文件

1 cmake_minimum_required(VERSION 3.10)                                              
2 PROJECT(Pro1)
3 SET(SRC_LIST helloc.c)
4 MESSAGE(STATUS"This is BINARY_dir" ${PROJECT_BINARY_DIR})
5 MESSAGE(STATUS"This is SOURCE_dir"${PROJECT_SOURCE_DIR} )
6 ADD_EXECUTABLE(helloc ${SRC_LIST} )

第一行:为了不让cmake出现错误,设置cmake的版本

第二行:设置项目的名称为Pro1,并可以指定文件类型(默认支持所有语言)该指令隐式的定义了两个cmake变量:<projectname>_BINARY_DIR以及<projectname>_SOURCE_DIR,内部编译的情况下,两个变量相同

前一个是可执行文件的目录,后一个是源代码的文件目录

第三行:SET指令相当于将SRC_LIST设置为helloc.c,如果有更多的源文件可用空格或分号隔开

第四行:MESSAGE  为打印指令,STATUS表明正常消息, ${PROJECT_BINARY_DIR} 可执行文件的文件目录

第五行:源文件的文家目录

第六行:生成可执行文件和$()中的文件依赖

 

开始构建

执行cmake CMakeLitsts生成makefile文件

miao@openlib:~/cmake_test$ cmake CMakeLists.txt 
-- The C compiler identification is GNU 7.4.0
-- The CXX compiler identification is GNU 7.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
STATUS"This is BINARY_dir"/home/miao/cmake_test
STATUS"This is SOURCE_dir"/home/miao/cmake_test
-- Configuring done
-- Generating done
-- Build files have been written to: /home/miao/cmake_test

cmake 生成的中间文件可以使用make clean来清除

这里make helloc可生成可执行文件

./helloc则可以执行

miao@openlib:~/cmake_test$ make helloc
Scanning dependencies of target helloc
[ 50%] Building C object CMakeFiles/helloc.dir/helloc.c.o
[100%] Linking C executable helloc
[100%] Built target helloc
miao@openlib:~/cmake_test$ ./helloc 
Hello world from cMake pro1

 

外部构建

先在该文件下创建一个build的文件夹

mkdir build

cd build

然后惊醒编译 cmake ..     ..是指上一层目录

直接make就生成了可执行文件

这样生成的中间文件就全部在build文件中

 

posted @ 2019-10-30 20:55  miaorn  阅读(382)  评论(0编辑  收藏  举报