ubuntu安装使用cmake
安装cmake 对任何用户而言都不该再成为一个问题。几乎所有主流的Linux发行版的源中都包含有cmake的安装包,直接从源中添加即可。当然,也可以在官方网站下载源代码自行编译安装。
对于Windows和Mac用户,cmake的官方网站上有相应的安装包,下载安装即可,无须赘述。
注:为了能够测试本文中的实例程序,如果读者的Linux系统中所带的cmake版本低于2.6,请从官网下载2.6版本或以上的源代码进行编译并安装。
在linux下安装cmake
- 首先下载源码包
http://www.cmake.org/cmake/resources/software.html
这里下载的是cmake-2.6.4.tar.gz
随便找个目录解压缩
root@lct:/home/work# tar -xzvf cmake-2.6.4.tar.gz
root@lct:/home/work# cd cmake-2.6.4
root@lct:/home/work# ./bootstrap
root@lct:/home/work# make
root@lct:/home/work# make install
cmake 会默认安装在 /usr/local/bin 下面
单文件cmake工程构建
- 单文件hello.c
#include <stdio.h>
int main(void)
{
printf("Hello World from Main!\n");
return 0;
}
- 编写 CMakeLists.txt
PROJECT(HELLO)
SET(SRC_LIST hello.c)
MESSAGE(STATUS "This is BINARY dir"${HELLO_BINARY_DIR})
MESSAGE(STATUS "This is SOURCE dir"${HELLO_SOURCE_DIR})
ADD_EXECUTABLE(hello ${SRC_LIST})
运行cmake .
此时已经自动生成Makefile
运行make,生成可执行文件hello
多文件cmake工程构建
- 编写源文件
root@lct:/home/work/myCmakePro# ls
CMakeLists.txt main.c src
root@lct:/home/work/myCmakePro# cd src
root@lct:/home/work/myCmakePro/src# ls
hello.h hello.c
- 编写CMakeLists.txt
- 顶层CMakeLists.txt
root@lct:/home/work/myCmakePro# cat CMakeLists.txt
PROJECT(main)
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
ADD_SUBDIRECTORY(src)
AUX_SOURCE_DIRECTORY(. DIR_SRCS)
ADD_EXECUTABLE(main ${DIR_SRCS})
TARGET_LINK_LIBRARIES(main hello)
使用命令 ADD_SUBDIRECTORY 指明本项目包含一个子目录 src 。第六行,使用命令 TARGET_LINK_LIBRARIES 指明可执行文件 main 需要连接一个名为hello的链接库 。
- 子目录src下面的CMakeLists.txt
root@lct:/home/work/myCmakePro# cd src
root@lct:/home/work/myCmakePro/src# cat CMakeLists.txt
AUX_SOURCE_DIRECTORY(. DIR_HELLO_SRCS)
ADD_LIBRARY(hello ${DIR_HELLO_SRCS})
在该文件中使用命令 ADD_LIBRARY 将 src 目录中的源文件编译为共享库。
运行cmake .
此时已经自动生成Makefile运行make,生成可执行文件和动态库