视觉SLAM学习笔记1:Cmake的使用
1、创建CMakeLists.txt
博主开发环境是ubuntu 18.04,cmake版本为3.10.2 。
首先打开终端,创建用于存放工程的文件夹:
$ mkdir slamlearn
$ mkdir ch1
$ cd ch1
$ gedit CMakeLists.txt test.cpp
2、编写CMakeLists文件和程序代码
CMakeLists.txt 文件:
cmake_minimum_required( VERSION 2.8 ) #指定最低cmake版本
project( TEST ) #工程名
add_executable( test1 test.cpp ) #添加可执行程序
test.cpp 文件:
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout << "this is a test " << endl;
return 0;
}
3、cmake分析,make编译
cmake:
执行cmake命令可生成一些中间文件,最重要的是makefile,学过嵌入式Linux的应该知道这个脚本语言,这里不解释其中原理。cmake只是处理工程文件之间的关系,解决代码间的依赖。
make:
执行make命令实际是调用g++编译程序,Makefile文件其实就是写明各个文件间的依赖关系,cmake则可帮我们自动完成这一过程。使我们对项目的编译管理工作,从输入一串 g++ 命令,变成了维护若干个比较直观的 CMakeLists.txt 文件,这将明显降低维护整个工程的难度。
在执行cmake之前首先创建一个用于存放中间文件的文件夹,以便将代码分享给他人或git上传的时候可以尽快删除,减少传输量:
$ mkdir build
$ cd build/
$ cmake ..
在build文件夹编译上一层文件夹的CMakeLists.txt 即可使中间文件全部放入build文件夹里,分享代码时直接将build删除即可。
使用make进行工程编译:
$ make
$ ls
可以看到生成了可执行文件test,执行这个程序:
$ ./test1
可以看到输出结果:
4、cmake下使用库
重新创建文件夹ch2,按上述步骤创建CMakeLists.txt文件,hello.cpp,hellofunc.cpp,hellofunc.h,各代码如下:
hello.cpp:
#include "hellofunc.h"
int main(int argc, char** argv)
{
hellofunc();
return 0;
}
hellofunc.cpp:
#include <iostream>
using namespace std;
void hellofunc(void)
{
cout << "hello slam " << endl;
}
hellofunc.h:
#ifndef __HELLOFUNC_H
#define __HELLOFUNC_H
void hellofunc(void);
#endif
CMakeLists.txt:
cmake_minimum_required( VERSION 2.8 )
project( helloslam )
add_executable( hello hello.cpp )
add_library( hellofunc_shared SHARED hellofunc.cpp )
target_link_libraries( hello hellofunc_shared )
其中add_library()告诉cmake要把hellofunc.cpp编译成叫做hellofunc_shared的库,在 Linux 中,库文件分成静态库和共享库两种,静态库以.a 作为后缀名,共享库以.so结尾。所有库都是一些函数打包后的集合,差别在于静态库每次被调用都会生成一个副本,而共享库则只有一个副本,更省空间。
target_link_libraries( hello hellofunc_shared )指将可执行程序hello和库hellofunc_shared链接起来。
5、使用IDE
以qt creator 5为例:
打开工程:
选择CMakeLists打开,编译器即可自动构建程序。
ctrl+r运行程序,编译器下方显示输出结果。