主要步骤为:
1. 我使用的ubuntu环境,安装了ros,所以带Cmake,也安装过了Eigen库。
2. 新建个工程文件夹,写cpp文件,写CMakeLists.txt文件
3. 编译并执行。
新建个工程文件夹hellocmake
mkdir hellocmake
cd hellocmake
touch Eigentest.cpp
写入如下代码,参考官方文档,Eigen: Getting started
#include <iostream>
#include <eigen3/Eigen/Dense>
using Eigen::MatrixXd;
int main() {
MatrixXd m(2,2);
m(0,0) = 3;
m(1,0) = 2.5;
m(0,1) = -1;
m(1,1) = m(1,0) + m(0,1);
std::cout << "hello cmake" << std::endl;
std::cout << "hello eigen" << std::endl;
std::cout << m << std::endl;
return 0;
}
新建CMakeLists.txt文件
touch CMakeLists.txt
写入以下内容,参考官方文档 Eigen: Using Eigen in CMake Projects
cmake_minimum_required(VERSION 3.16)
project(hellocmake)
find_package (Eigen3 3.3 REQUIRED NO_MODULE)
add_executable(Eigentest Eigentest.cpp)
target_link_libraries (Eigentest Eigen3::Eigen)
在项目根目录建立一个build目录
mkdir build && cd build
cmake ../
ls -l 查看build目录下内容,可以看到生成的Makefile,执行
make
ls -l 再次查看build目录下内容,可以看到生成的Eigentest可执行文件
./Eigentest
TIPS: Eigen库的安装
查看是否安装eigen库
pkg-config --modversion eigen3
如果没有安装的话,就重新安装一下
1. apt安装(只能安装默认版本),其安装路经位于/usr/include/eigen3
sudo apt-get install libeigen3-dev
2、源码安装(可以安装所有的历史版本)
git clone https://gitlab.com/libeigen/eigen.git
cd eigen
git checkout -p 3.3.4 //输入需要安装的版本
mkdir build
cd build
cmake…
sudo make install
安装成功后,再次查看版本
pkg-config --modversion eigen3
例子2:打印hello world
第一步:新建hello.cpp
#include <iostream>
using namespace std;
int main() {
std::cout << "hello cmake" << std::endl;
return 0;
}
第二步:新建CMakeLists.txt
add_executable(hello hello.cpp)
第三步:使用“惯例”方法来构建
cmake ../
make
./hello
以上就是使用CMake来构建一个Hello World C++项目的过程,可以看到相对于自己编写Makefile,使用CMake是简单很多的,仅需要一句:
add_executable(hello, hello.cpp)
就搞定了。
编译更加灵活的用法:
cmake ../opensim-moco/dependencies
make --jobs 4 ipopt
../opensim-moco/dependencies
:这是CMake要配置的项目的源代码目录的路径。在这个例子中,它指向当前目录的上一级目录中的opensim-moco/dependencies
子目录。这意味着CMake将在这个目录中查找CMakeLists.txt
文件,并根据该文件中的指令来配置项目。
这个命令通常会在当前目录(或指定的构建目录)中生成一系列构建文件(如Makefile)。
--jobs 4
:这是make的一个选项,用于指定并行编译的作业数。
ipopt
:这通常指定了要构建的目标或目标集。ipopt
作为目标的确切含义取决于Makefile
(或CMake生成的Makefile
)中的内容。如果Makefile
中没有明确的目标名为ipopt
,则这个命令可能会失败。