本文主要是介绍Linux cmake使用笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
CMake:
All problems in computer science can be solved by another level of indirection.
cmake会根据cmake-language编写的 CMakeLists.txt 或.cmake后缀文件编译自动生成Makefile
CMake使用流程:
在 linux 平台下使用 CMake 生成 Makefile 并编译的流程如下:
1.编写 CMake 配置文件 CMakeLists.txt 。
2.执行命令 cmake PATH 或者 ccmake PATH 生成 Makefile 1 1ccmake 和 cmake 的区别在于前者提供了一个交互式的 界面。其中, PATH 是 CMakeLists.txt 所在的目录。
3.使用 make 命令进行编译。
ccmake 需要安装cmake-curses-gui:
The program ‘ccmake’ is currently not installed. You can install it by typing:
sudo apt install cmake-curses-gui
生成可执行文件:
1.最简单的cmake
1.新建目录Test
2.进入Test目录,创建main.c, CMakeLists.txt
//main.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{printf("CMake Test ....\n");return 0;
}//CMakeLists.txt
cmake_minimum_required (VERSION 2.8) # cmake 最低版本需求
project (Test) # Test 是 CMakeLists.txt所在目录
add_executable(test main.c) # 生成可执行文件test, main.c是源码$cmake .
生成文件及目录:CMakeCache.txt CMakeFiles cmake_install.cmake Makefile
$make #生成文件:test
$./test 输出 CMake Test ....
2.同一目录,多个源文件:
Test1|->main.c|->func.c|->func.h|->CMakeLists.txt//CMakeList.s.txt
cmake_minimum_required (VERSION 2.8)
project(Test1)
add_executable(test1 main.c func.c) #此行添加了多个源码文件
$cmake . #create makefile
$make #bulid and create Test1
$./Test1 #execut Test1另一种实现方法:
//CMakeList.s.txt
# cmake version mini
cmake_minimum_required (VERSION 2.8)
project(Test1)
aux_source_directory(. SRCS) #将CMakeLists.txt目录下的源码文件保存到SRCS环境变量
add_executable(Test1 ${SRCS}) #使用环境变量
3.多个目录,多个源码文件:
Test2
|->main.c
|->CMakeLists.txt
|->mm //先编译成库文件libfunc.a|->func.c|->func.h|->CMakeLists.txtTest2/CMakeLists.txt
cmake_minimum_required (VERSION 2.8) # cmake mini version
project(Test2) # 工程目录
aux_source_directory (. SRCS) # 保存源码环境变量SRCS
add_subdirectory (mm) # 添加子目录 mm
add_executable (Test2 main.c) # 指定生成目标可执行文件Test2
target_link_libraries (Test2 func) # 目标连接库 libfunc.aTest2/mm/CMakeLists.txt
aux_source_directory (. LIB_SRCS) # 保存库源码环境变量LIB_SRCS 注意环境变量不可重复
add_library (func ${LIB_SRCS}) # 指定生成目标库文件及库源码, libfunc.aTest2/
$cmake .
$make
$./Test2
4.自定义编译选项
Test3/
|->main.c
|->CMakeLists.txt
|->config.h.in
|->mm|->func.c|->func.h|->CMakeLists.txtTest3/CMakeLists.txt
cmake_minimum_required (VERSION 2.8)
project (Test3)
# 添加配置文件
configure_file ("${PROJECT_SOURCE_DIR}/config.h.in""${PROJECT_BINARY_DIR}/config.h")
option (USE_MYMATH "use my math library" ON)
if (USE_MYMATH)include_directories ("${PROJECT_SOURCE_DIR}/mm")add_subdirectory (mm)set (EXTRA_LIBS ${EXTRA_LIBS} func )
endif (USE_MYMATH)
aux_source_directory (. SRCS)
add_executable (Test3 ${SRCS})
target_link_libraries (Test3 ${EXTRA_LIBS})Test3/mm/CMakeLists.txt
aux_source_directory (. SRC_LIBS)
add_library (func ${SRC_LIBS})Test3/config.h.in
#cmakedefine USE_MYMATH
#cmakedefine USE_STANDERTest3/config.h //cmake . or ccmake . 生成,ccamke . 可以手动配置option
#define USE_MYMATH // option ON
/* #undef USE_STANDER */ // option OFFTest3/main.c
#include <stdio.h>
#include <stdlib.h>
#include "config.h" #ifdef USE_MYMATH
#include "func.h" //不需要写路经
#endifint main(int argc, int argv)
{int a = 88;int b = 66;#ifdef USE_MYMATHprintf("%d + %d = %d\n", a, b, add(a, b));printf("%d , %d min:%d\n", a, b, min(a, b));printf("%d , %d, max:%d\n", a, b, max(a, b));#elseprintf("not support add min max...\n");#endifreturn 0;
}Test3/mm/func.c
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b)
{return (int)(a + b);
}
int min(int a, int b)
{return a>b ? b : a;
}
int max(int a, int b)
{return a<b ? a : b;
}Test3/mm/func.h
#ifndef _FUNC_H_
#define _FUNC_H_int add(int a, int b);
int min(int a, int b);
int max(int a, int b);#endif
$ccmake . //编辑配置项Press [enter] to edit option CMake Version 3.5.1
Press [c] to configure
Press [h] for help Press [q] to quit without generating
Press [t] to toggle advanced mode (Currently Off)
方向键上下左右移动光标
enter键编辑选项,ON/OFF切换,编辑行
c:生成配置
g:退出并生成(或更新)config.h
5.定制安装规则
首先先在 mm/CMakeLists.txt 文件里添加下面两行:
指定 func 库的安装路径
install (TARGETS func DESTINATION bin)
install (FILES func.h DESTINATION include)指明 func 库的安装路径。之后同样修改根目录的 CMakeLists 文件,在末尾添加下面几行:指定安装路径
install (TARGETS Test4 DESTINATION bin)
install (FILES "${PROJECT_BINARY_DIR}/config.h"DESTINATION include)
通过上面的定制,生成的 Test4 文件和 func 库 libfunc.o 文件将会被复制到 /usr/local/bin
config.h func.h被复制到 /usr/local/include
$sudo make install
[sudo] password for song:
[ 50%] Built target func
[100%] Built target Test4
Install the project...
-- Install configuration: ""
-- Installing: /usr/local/bin/Test4
-- Installing: /usr/local/include/config.h
-- Installing: /usr/local/bin/libfunc.a
-- Installing: /usr/local/include/func.h
6.支持 gdb
让 CMake 支持 gdb 的设置也很容易,只需要指定 Debug 模式下开启 -g 选项:
set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
之后可以直接对生成的程序使用 gdb 来调试。
7.添加环境检查
有时候可能要对系统环境做点检查,例如要使用一个平台相关的特性的时候。在这个例子中,我们检查系统是否自带 pow 函数。如果带有 pow 函数,就使用它;否则使用我们定义的 power 函数。
添加 CheckFunctionExists 宏首先在顶层 CMakeLists 文件中添加 CheckFunctionExists.cmake 宏,并调用 check_function_exists 命令测试链接器是否能够在链接阶段找到 pow 函数。
# 检查系统是否支持 pow 函数
include (${CMAKE_ROOT}/Modules/CheckFunctionExists.cmake)
check_function_exists (pow HAVE_POW)将上面这段代码放在 configure_file 命令前。
预定义相关宏变量接下来修改 config.h.in 文件,预定义相关的宏变量。
// does the platform provide pow function?
#cmakedefine HAVE_POW在代码中使用宏和函数最后一步是修改 main.cc ,在代码中使用宏和函数:
#ifdef HAVE_POWprintf("Now we use the standard library. \n");double result = pow(base, exponent);
#elseprintf("Now we use our own Math library. \n");double result = power(base, exponent);
#endif
8.添加版本号
首先修改顶层 CMakeLists 文件,在 project 命令之后加入如下两行:
set (Demo_VERSION_MAJOR 1)
set (Demo_VERSION_MINOR 0)分别指定当前的项目的主版本号和副版本号。之后,为了在代码中获取版本信息,我们可以修改 config.h.in 文件,添加两个预定义变量:
// the configured options and settings for Tutorial
#define Demo_VERSION_MAJOR @Demo_VERSION_MAJOR@
#define Demo_VERSION_MINOR @Demo_VERSION_MINOR@这样就可以直接在代码中打印版本信息了:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "config.h"
#include "math/MathFunctions.h"
int main(int argc, char *argv[])
{if (argc < 3){// print version infoprintf("%s Version %d.%d\n",argv[0],Demo_VERSION_MAJOR,Demo_VERSION_MINOR);printf("Usage: %s base exponent \n", argv[0]);return 1;}double base = atof(argv[1]);int exponent = atoi(argv[2]);#if defined (HAVE_POW)printf("Now we use the standard library. \n");double result = pow(base, exponent);
#elseprintf("Now we use our own Math library. \n");double result = power(base, exponent);
#endifprintf("%g ^ %d is %g\n", base, exponent, result);return 0;
}
9.生成安装包
本节对应的源代码所在目录:Demo8。本节将学习如何配置生成各种平台上的安装包,包括二进制安装包和源码安装包。为了完成这个任务,我们需要用到 CPack ,它同样也是由 CMake 提供的一个工具,专门用于打包。首先在顶层的 CMakeLists.txt 文件尾部添加下面几行:
# 构建一个 CPack 安装包
include (InstallRequiredSystemLibraries)
set (CPACK_RESOURCE_FILE_LICENSE"${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
set (CPACK_PACKAGE_VERSION_MAJOR "${Demo_VERSION_MAJOR}")
set (CPACK_PACKAGE_VERSION_MINOR "${Demo_VERSION_MINOR}")
include (CPack)上面的代码做了以下几个工作:导入 InstallRequiredSystemLibraries 模块,以便之后导入 CPack 模块;设置一些 CPack 相关变量,包括版权信息和版本信息,其中版本信息用了上一节定义的版本号;导入 CPack 模块。接下来的工作是像往常一样构建工程,并执行 cpack 命令。生成二进制安装包:cpack -C CPackConfig.cmake生成源码安装包
cpack -C CPackSourceConfig.cmake
我们可以试一下。在生成项目后,执行 cpack -C CPackConfig.cmake 命令:[ehome@xman Demo8]$ cpack -C CPackSourceConfig.cmake
CPack: Create package using STGZ
CPack: Install projects
CPack: - Run preinstall target for: Demo8
CPack: - Install project: Demo8
CPack: Create package
CPack: - package: /home/ehome/Documents/programming/C/power/Demo8/Demo8-1.0.1-Linux.sh generated.
CPack: Create package using TGZ
CPack: Install projects
CPack: - Run preinstall target for: Demo8
CPack: - Install project: Demo8
CPack: Create package
CPack: - package: /home/ehome/Documents/programming/C/power/Demo8/Demo8-1.0.1-Linux.tar.gz generated.
CPack: Create package using TZ
CPack: Install projects
CPack: - Run preinstall target for: Demo8
CPack: - Install project: Demo8
CPack: Create package
CPack: - package: /home/ehome/Documents/programming/C/power/Demo8/Demo8-1.0.1-Linux.tar.Z generated.此时会在该目录下创建 3 个不同格式的二进制包文件:
[ehome@xman Demo8]$ ls Demo8-*
Demo8-1.0.1-Linux.sh Demo8-1.0.1-Linux.tar.gz Demo8-1.0.1-Linux.tar.Z这 3 个二进制包文件所包含的内容是完全相同的。我们可以执行其中一个。此时会出现一个由 CPack 自动生成的交互式安装界面:
[ehome@xman Demo8]$ sh Demo8-1.0.1-Linux.sh
Demo8 Installer Version: 1.0.1, Copyright (c) Humanity
This is a self-extracting archive.
The archive will be extracted to: /home/ehome/Documents/programming/C/power/Demo8
If you want to stop extracting, please press <ctrl-C>.
The MIT License (MIT)
Copyright (c) 2013 Joseph Pan(http://hahack.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Do you accept the license? [yN]:
y
By default the Demo8 will be installed in:"/home/ehome/Documents/programming/C/power/Demo8/Demo8-1.0.1-Linux"
Do you want to include the subdirectory Demo8-1.0.1-Linux?
Saying no will install in: "/home/ehome/Documents/programming/C/power/Demo8" [Yn]:
y
Using target directory: /home/ehome/Documents/programming/C/power/Demo8/Demo8-1.0.1-Linux
Extracting, please wait...
Unpacking finished successfully完成后提示安装到了 Demo8-1.0.1-Linux 子目录中,我们可以进去执行该程序:
[ehome@xman Demo8]$ ./Demo8-1.0.1-Linux/bin/Demo 5 2
Now we use our own Math library.
5 ^ 2 is 25关于 CPack 的更详细的用法可以通过 man 1 cpack 参考 CPack 的文档。
这篇关于Linux cmake使用笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!