编译器安装
gcc编译C程序,g++编译C++程序
sudo apt-get install gcc
sudo apt-get install g++
编写hello world程序
1.新建hello.cpp文件
vim hello.cpp
2.vim编写代码,i进入编写,编写结束后esc,键入:wq保存退出
#include <iostream>
using namespace std;
int main(){
cout<<"hello world!"<<endl;
return 0;
}
3.g++编译代码
没有输出报错则编译成功,ls命令可以看到一个a.out文件,这个文件为可执行文件
g++ hello.cpp
4.运行可执行文件
./a.out
结果
(base) xx@Ex-amax:~/workdir/slambook/test$ ls
a.out hello.cpp
(base) xx@Ex-amax:~/workdir/slambook/test$ ./a.out
hello world!
编写C++工程文件
安装CMake
sudo apt-get install cmake
1.新建CMakeLists.txt文件
vim CMakeList.txt
2.编写CMakeList文件
project(hello)
add_executable(sayHello hello.cpp)
3.cmake编译
cmake .
生成了一些中间文件
(base) liran@E701-amax:~/workdir/slambook/test$ ls
CMakeCache.txt CMakeFiles cmake_install.cmake CMakeLists.txt hello.cpp Makefile
可以用cat查看文件内容,比如 cat Makefile
4.make编译生成可执行文件
make
结果
(base) xx@Ex-amax:~/workdir/slambook/test$ ls | grep sayHello
sayHello
5.执行
./sayHello
结果
(base) xx@Ex-amax:~/workdir/slambook/test$ ./sayHello
hello world!
注意:为了简洁起见,不希望一共工程文件下面有许多中间文件,因此会新建一个build文件,在该目录下cmake上一个目录的工程
mkdir build
cd build
cmake ..
make
这样管理的文件结构如下
└── test #根目录
├── CMakeLists.txt
├── build
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ ├── cmake_install.cmake
│ ├── Makefile
│ └── sayHello
└── hello.cpp