[camke]CMake实践构建一个“Hello world!“

文章介绍了如何在C++中创建一个简单的HelloWorld程序,然后使用CMake工具进行构建,生成可执行文件的过程。详细步骤包括创建源文件、配置CMakeLists.txt和执行构建命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们新增一个C++程序,内容是输出"Hello world!",在example目录下新建文件main.cpp,其内容如下:

#include <iostream>

int main(int argc, char** argv)
{
    std::cout << "Hello world!" << std::endl;
    return 0;
}

完成后,当前的文件目录结构如下:

example
├── CMakeCache.txt
├── CMakeFiles
├── cmake_install.cmake
├── CMakeLists.txt
├── main.cpp
└── Makefile

要构建出可执行文件,需要使用到CmakeADD_EXECUTABLE命令(命令的介绍可以参考这里),它可以将指定的源文件生成目标可执行文件,在CMakeLists.txt文件中添加如下行:

ADD_EXECUTABLE(example main.cpp)

在命令行执行cmake --build .,或分别执行cmake .make两条命令,构建过程中命令行会有类似下面的输出:

-- The C compiler identification is GNU 11.4.0
-- The CXX compiler identification is GNU 11.4.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
……
Consolidate compiler generated dependencies of target example
[100%] Built target example

构建信息[100%] Built target example表明已经生成可执行文件example,当前的目录结构如下:

example
├── CMakeCache.txt
├── CMakeFiles
├── cmake_install.cmake
├── CMakeLists.txt
├── example
├── main.cpp
└── Makefile

执行./example后,就可以看到输出了:

./example 
Hello world!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海神之光.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值