Windows下使用cmake运行第一个程序

本文介绍如何使用CMake配合MinGW-W64在Windows环境下搭建C/C++开发环境,并通过一个简单的Hello World示例程序演示整个编译流程。

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

说明

系统:Windows
编译运行:cmake+MinGW-W64

运行文件

main.cpp主函数:

#include <iostream>
#include "function.h"

int main(){
    printhello();
    return 0;
}

printhello.cpp文件:

#include <iostream>
#include "function.h"

void printhello(){
    int i;
    std::cout<< "Hello World!" <<std::endl;
}

function.h头文件:

_Pragma("once")
#ifndef __FUNCTION_H_
#define __FUNCTION_H_

void printhello();

#endif

在程序目录下建立CMakeLists.txt文件:

cmake_minimum_required(VERSION 3.15) %cmake最小版本要求,根据需要确定

project(hello)

add_executable(hello main.cpp printhello.cpp)

在程序目录下打开终端,建立bulid目录:

mkdir bulid

进入bulid目录下:

cd bulid

运行命令:

cmake -G "MinGW Makefiles" ..

运行结果:

-- The C compiler identification is GNU 8.1.0
-- The CXX compiler identification is GNU 8.1.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: D:/Language_env/mingw64/bin/g++.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: D:/Desktop/Temprary_Files/temp/cpp_tmp/bulid

运行:

make

运行结果:

[ 33%] Building CXX object CMakeFiles/hello.dir/main.cpp.obj
[ 66%] Building CXX object CMakeFiles/hello.dir/printhello.cpp.obj
[100%] Linking CXX executable hello.exe
[100%] Built target hello

产生可执行文件hello.exe,直接运行:

./hello

运行结果:

Hello World!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值