Python脚本 - 快速建立VSCode C/C++的配置文件

本文介绍了一个Python脚本,用于自动在VSCode中配置C/C++的开发环境。通过创建.vscode文件夹及其中的launch.json和tasks.json文件,可以简化配置过程并快速启动编译调试。

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

Python脚本 - 快速建立VSCode C/C++的配置文件

VSCode运行C/C++代码需要事先编写配置文件,本文则编写一个脚本来实现此功能。

本文配置文件内容摘自Blackkitty’s Blog - 【VSCode】Windows下VSCode编译调试c/c++【更新】。对于MinGW安装和配置的问题、VSCode运行代码的问题,也可参考此链接。

所需条件

  • VSCode软件
  • MinGW安装完毕
  • Python 3

脚本代码

执行脚本时,脚本会创建文件夹.vscode,并在其中写入配置文件。

脚本代码如下:

import os
import codecs

s_launch = """
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team        
// ${file}: the current opened file                     
// ${fileBasename}: the current opened file's basename 
// ${fileDirname}: the current opened file's dirname    
// ${fileExtname}: the current opened file's extension  
// ${cwd}: the current working directory of the spawned process
{
    "version": "0.2.0",
    "configurations": [{
        "name": "C++ Launch (GDB)",     // 配置名称,将会在启动配置的下拉菜单中显示
        "type": "cppdbg",               // 配置类型,这里只能为cppdbg
        "request": "launch",            // 请求配置类型,可以为launch(启动)或attach(附加)
        "targetArchitecture": "x64",    // 生成目标架构,一般为x86或x64,可以为x86, arm, arm64, mips, x64, amd64, x86_64
        "program": "${cwd}\\\\${fileBasenameNoExtension}.exe",  // 将要进行调试的程序的路径

        "miDebuggerPath": "gdb.exe",    // miDebugger的路径,注意这里要与MinGw的路径对应

        "args": [],                     // 程序调试时传递给程序的命令行参数,一般设为空即可
        "stopAtEntry": false,           // 设为true时程序将暂停在程序入口处,一般设置为false
        "cwd": "${fileDirname}",        // 调试程序时的工作目录,一般为${workspaceRoot}即代码所在目录
        "externalConsole": true,        // 调试时是否显示控制台窗口,一般设置为true显示控制台
        "preLaunchTask": "g++"          // 调试会话开始前执行的任务,一般为编译程序,c++为g++, c为gcc
    }]
}
"""

s_tasks = """
{
    "version": "0.1.0",
    "command": "g++",
    "args": ["-g","${file}","-o","${fileBasenameNoExtension}.exe"],    // 编译命令参数
    "problemMatcher": {
        "owner": "cpp",
        "fileLocation": ["relative", "${workspaceRoot}"],
        "pattern": {
            "regexp": "^(.*):(\\\\d+):(\\\\d+):\\\\s+(warning|error):\\\\s+(.*)$",
            "file": 1,
            "line": 2,
            "column": 3,
            "severity": 4,
            "message": 5
        }
    }
}
"""

if not os.path.exists('.vscode'):
    os.mkdir('.vscode')

f_launch = codecs.open('.vscode//launch.json', 'w', 'utf-8')
f_tasks = codecs.open('.vscode//tasks.json', 'w', 'utf-8')

f_launch.write(s_launch)
f_tasks.write(s_tasks)

f_launch.close()
f_tasks.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值