这篇文章介绍如何使用cmake工具编译一个最简单的helloworld.cpp文件。
首先创建一个空的文件夹。
~$ mkdir cmake_test
在该文件夹下,我们新建一个helloworld.cpp文件
~/cmake_test$ touch helloworld.cpp
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout<<"Hello World!"<<endl;
return 0;
}
为了利用CMake编译该.cpp文件,我们在当前文件夹新建CMakeLists.txt文件。
~/cmake_test$ vim CMakeLists.txt
cmake_minimum_required(VERSION 2.8) # 设置需要CMake的最低版本
project(hello) # 新建一个工程
add_executable(helloworld helloworld.cpp) # 将helloworld.cpp源文件编译成helloworld可执行文件
为了保存编译过程的中间文件,我们在当前文件夹下再创建一个build文件夹。
~/cmake_test$ mkdir build
我们进入build文件夹,使用命令:
~/cmake_test$ cd build/
~/cmake_test/build$ cmake ..
终端会输出相应的信息:
-- The C compiler identification is GNU 7.5.0
-- The CXX compiler identification is GNU 7.5.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/yuwenlu/cmake_test/build
这样一些配置文件等会储存在build文件夹中,文件较为整洁。
最后执行:
~/cmake_test/build$ make
接着终端输出:
-- Configuring done
-- Generating done
-- Build files have been written to: /home/yuwenlu/cmake_test/build
Scanning dependencies of target helloworld
[ 50%] Building CXX object CMakeFiles/helloworld.dir/helloworld.cpp.o
[100%] Linking CXX executable helloworld
[100%] Built target helloworld
说明编译成功了。
我们这时进入build文件夹中就可以看到编译生成的可执行文件helloworld了,我们执行他:
~/cmake_test/build$ ./helloworld
终端输出:
Hello World!
结果正常。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)