Page tree
Skip to end of metadata
Go to start of metadata

命令行编译C++语言程序

C++程序

#include <iostream>
using namespace std;
int main()
{
	cout << "Hello, world!" << endl;
	return 0;
}

编译应用

$ $CXX helloworld.cpp -o helloworld

CMake工具构建C++语言程序

很多时候,我们使用C++语言开发应用程序,会对项目的功能进行模块化分类,也就会有多个CPP文件。这里我们推荐使用CMake工具来对项目进行管理。同样我们使用上面例子中的hello.cpp文件,通过编写CMake命令相应的配置文件来达到编译的目的。


编写CMakeLists.txt文件,内容如下

project (test)

add_executable(hello hello.cpp)

这里声明了,该项目名称为test,将名为 hello.cpp 源文件编译成一个名称为 hello 的可执行文件。

下面使用cmake命令来构建这个简单的test项目。

$ tree
.
├── CMakeLists.txt
└── hello.cpp
$ mkdir build
$ cd build
$ cmake ..
-- Toolchain file defaulted to '/home/i2som/workspace/pangu-weston/2.6-snapshot/sysroots/x86_64-openstlinux_weston_sdk-linux/usr/share/cmake/OEToolchainConfig.cmake'
-- The C compiler identification is GNU 8.2.0
-- The CXX compiler identification is GNU 8.2.0
-- Check for working C compiler: /home/i2som/workspace/pangu-weston/2.6-snapshot/sysroots/x86_64-openstlinux_weston_sdk-linux/usr/bin/arm-openstlinux_weston-linux-gnueabi/arm-openstlinux_weston-linux-gnueabi-gcc
-- Check for working C compiler: /home/i2som/workspace/pangu-weston/2.6-snapshot/sysroots/x86_64-openstlinux_weston_sdk-linux/usr/bin/arm-openstlinux_weston-linux-gnueabi/arm-openstlinux_weston-linux-gnueabi-gcc -- 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: /home/i2som/workspace/pangu-weston/2.6-snapshot/sysroots/x86_64-openstlinux_weston_sdk-linux/usr/bin/arm-openstlinux_weston-linux-gnueabi/arm-openstlinux_weston-linux-gnueabi-g++
-- Check for working CXX compiler: /home/i2som/workspace/pangu-weston/2.6-snapshot/sysroots/x86_64-openstlinux_weston_sdk-linux/usr/bin/arm-openstlinux_weston-linux-gnueabi/arm-openstlinux_weston-linux-gnueabi-g++ -- 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/i2som/workspace/test/build

$ make
Scanning dependencies of target hello
[ 50%] Building CXX object CMakeFiles/hello.dir/hello.cpp.o
[100%] Linking CXX executable hello
[100%] Built target hello

最终会生成hello可执行文件。上面在构建前先创建build目录,是因为中会产生一些中间文件,为了源代码目录和构建目录保持干净,这样即便构建后不需要,可以直接删除build目录即可。

更多CMake工具的使用,可以参考构建工具

  • No labels