mac上进行c++开发的vscode配置

本配置基于哔哩哔哩上我不是小杰的教程进行配置,包含vscode上运行和调试c++代码所需的配置。本文包括三个内容:配置文件、有用的插件、好用的快捷键。这里还有我不是小杰的文本材料。我只是一个搬运工。

1、需要的文件配置

在c++进行开发需要在vscode中创建.vscode文件夹,然后在该文件夹下配置三个文件,分别是launch.json、tasks.json、settings.json。
建议将所有的cpp文件放在一个文件夹下,因为这样只需要进行一次配置即可运行所有的代码,如果在多个文件夹中,那样每个文件夹都需要配置一次(vscode有一个工作区的概念,一个工作区其实就是一个文件夹)。vscode只适合于我们在学习中做小的开发,当我们需要进行较大的项目开发的时候我们还是需要使用visual studio(在mac上我们需要安装虚拟机或者双系统才可以使用)或者其他的开发平台。

tasks.json:作用是给定一个在运行时执行的任务序列,以便在执行c++程序的时候能够知道如何去运行,例如添加在运行前进行编译的任务。
launch.json:启动器。
settings.json:在vscode中进行设置的时候分为全局设置和局部设置,这一文件是用于项目对应的局部设置,我们推荐尽量将项目个性化的东西放在局部设置之下,这样能够使得当我们更换运行的机器的时候,不会因为运行环境造成项目的运行失败。

具体方法:创建.vscode文件夹并创建相应的配置文件,然后将以下代码直接复制过去即可,然后你就可以发现能够成功的调试。至于其中的原理,可以看代码的注释或者直接去看作者的视频介绍。这个教程相比于网上其他教程的好处在于不仅能够知其然,也能知其所以然。

tasks.json

{
  // Tasks in VS Code can be configured to run scripts and start processes
  // so that many of these existing tools can be used from within VS Code 
  // without having to enter a command line or write new code.
  // Workspace or folder specific tasks are configured from the tasks.json file in the .vscode folder for a workspace.
  "version": "2.0.0",
  "tasks": [
    {
      // The task's label used in the user interface.
      // Terminal -> Run Task... 看到的名字
      "label": "g++ compile",
      // The task's type. For a custom task, this can either be shell or process.
      // If shell is specified, the command is interpreted as a shell command (for example: bash, cmd, or PowerShell).
      // If process is specified, the command is interpreted as a process to execute.
      "type": "shell",// shell: 输入命令
      // The actual command to execute.
      // 因为g++已经在环境变量中了,所以我们这里写命令就行不用写g++的绝对路径
      "command": "g++",
      "args": [
        "${file}", // 表示当前文件(绝对路径)
        // 在这里添加你还需要链接的.cpp文件
        "-o",
        "${fileDirname}/${fileBasenameNoExtension}.out",
        "-W",
        "-Wall",
        "-g",
        "-std=c++17",
      ],
      // Defines to which execution group this task belongs to.
      // It supports "build" to add it to the build group and "test" to add it to the test group.
      // Tasks that belong to the build/test group can be executed by running Run Build/Test Task from the Command Palette (sft cmd P).
      // Valid values:
      //   "build",
      //   {"kind":"build","isDefault":true}, 
      //   "test",
      //   {"kind":"test","isDefault":true}, 
      //   "none".
      "group": {
        "kind": "build",
        "isDefault": true, // Defines if this task is the default task in the group.
      },
      // Configures the panel that is used to present the task's output and reads its input.
      "presentation": {
        // Controls whether the executed command is echoed to the panel. Default is true.
        "echo": true, // 打开可以看到编译的命令,把命令本身输出一次
        // Controls whether the terminal running the task is revealed or not. Default is "always".
        //   always: Always reveals the terminal when this task is executed.
        //   silent: Only reveals the terminal if the task exits with an error or the problem matcher finds an error.(会显示错误,但不会显示警告)
        //   never: Never reveals the terminal when this task is executed.
        "reveal": "silent", // 控制在集成终端中是否显示。如果没问题那我不希望终端被切换、如果有问题我希望能看到编译过程哪里出错,所以选silent(可能always会好一些)
        // Controls whether the panel takes focus. Default is false.
        "focus": false, // 我的理解是:是否将鼠标移过去。因为这个是编译任务,我们不需要输入什么东西,所以选false
        // Controls if the panel is shared between tasks, dedicated to this task or a new one is created on every run.
        "panel": "shared", // shared:不同任务的输出使用同一个终端panel(为了少生成几个panel我们选shared)
        // Controls whether to show the `Terminal will be reused by tasks, press any key to close it` message.
        "showReuseMessage": true, // 就一句话,你想看就true,不想看就false
        // Controls whether the terminal is cleared before executing the task.
        "clear": false, // 还是保留之前的task输出信息比较好。所以不清理
      },
      // Other two choices: options & runOptions (cmd I to use IntelliSense)
      "options": {
        // The current working directory of the executed program or script. If omitted Code's current workspace root is used.
        "cwd": "${workspaceFolder}",// 默认就是这个,删掉也没问题
      },
      // problemMatcher: 用正则表达式提取g++的输出中的错误信息并将其显示到VS Code下方的Problems窗口
      // check: https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher
      "problemMatcher": {
        "owner": "cpp",
        "fileLocation": "absolute",
        "pattern": {
          "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
          "file": 1,
          "line": 2,
          "column": 3,
          "severity": 4,
          "message": 5,
        },
      },
      // 官网教程 https://code.visualstudio.com/docs/cpp/config-clang-mac#_build-helloworldcpp 
      // 提到了另一种problemMatcher,但试了之后好像不起作用,甚至还把我原本的电脑搞出了一些问题……
    },
    {
      "label": "Open Terminal.app",
      "type": "shell",
      "command": "osascript -e 'tell application \"Terminal\"\ndo script \"echo now VS Code is able to open Terminal.app\"\nend tell'",
      "problemMatcher": [],
      "group": "none",
    }
  ]
}

launch.json

{
  // One of the key features of Visual Studio Code is its great debugging support.
  // VS Code's built-in debugger helps accelerate your edit, compile and debug loop.
  // VS Code keeps debugging configuration information in a launch.json file
  // located in a .vscode folder in your workspace (project root folder).
  "version": "0.2.0",
  "configurations": [
    {
      /* ------ these three options are mandatory ------ */
      // The type of debugger to use for this launch configuration.
      "type": "cppdbg", // C++ debug
      // The request type of this launch configuration. Currently, launch and attach are supported.
      //   If you come from a server or desktop background, 
      //   it's quite normal to have your editor launch your process for you, 
      //   and your editor automatically attaches its debugger to the newly launched process.
      //   A launch configuration starts your app in debug mode before VS Code attaches to it.
      // 大概意思是说,如果你开始debug的时候你的项目已经启起来了,那就attach(把debug的工具附加上去)
      // 如果你开始debug的时机和你启动项目的时机是相同的,那就launch
      "request": "launch", // debug的类型,launch表示启动,attach表示附加
      // The reader-friendly name to appear in the Debug launch configuration drop-down.
      "name": "C++ Debug", // 在VSCode侧边栏Run那里看到的名字(可以随便起)
      /* ------ some optional attributes available to all launch configurations ------ */
      // To launch a task before the start of a debug session, set this attribute to the label of a task specified in tasks.json.
      "preLaunchTask": "g++ compile", //在调试之前要进行的工作 compile是在 tasks.json 的编译任务里面的label
      /* ------ Many debuggers support some of the following attributes: ------ */
      // executable or file to run when launching the debugger
      // !!不要在程序和代码的路径及文件名中出现空格!!否则无法调试(我尝试解决这个问题,但真的无法解决)
      "program": "${fileDirname}/${fileBasenameNoExtension}.out", // debug的对象(-g编译出来的二进制文件),需要和.vscode/tasks.json中生成的可执行文件一致
      // arguments passed to the program to debug
      "args": [], // 比如运行你的程序添加输入参数(argc/argv),需要在这里添加
      // Environment variables to add to the environment for the program
      "environment": [], // 放置环境变量
      // current working directory for finding dependencies and other files
      "cwd": "${workspaceFolder}",
      // break immediately when the program launches
      "stopAtEntry": false,
      // If true, a console is launched for the debuggee.
      // If false, on Linux and Windows, it will appear in the Integrated Console.
      "externalConsole": true,
      // 为true则会打开系统终端在其中进行交互
      // 如果为 true,则为调试对象启动控制台。如果为 false,它在 Linux 和 Windows 上会显示在集成控制台中
      // macOS不适用:https://code.visualstudio.com/docs/cpp/launch-json-reference#_externalconsole
      /* ------ Customizing GDB or LLDB ------ */
      // Indicates the debugger that VS Code will connect to. Must be set to gdb or lldb. 
      // 但是macOS只安装了llbd(有可能是安装命令行工具的时候安装的),那就用lldb吧
      "MIMode": "lldb",
    }
  ]
}

settings.json

第一部分的files.exclude使得vscode在显示的时候隐藏一些后缀名的文件,可以使得目录中不显示不关心的文件,目录会更加的清晰。
第二部分是对code runner的配置,每个参数的含义详细可看注释。

{
  // 添加希望被忽略的文件,这样一些文件虽然存在于当前工作目录下,但是不会被显示在左侧的文件浏览器里
  "files.exclude": {
    // dSYM文件具有调试信息,普通使用的话不看到它就可以了
    "**/*.dSYM": true,
    "**/*.out": true,
  },
  // --------------------------------------------------------------------------------------
  // Code Runner
  // To run code:
  //   use shortcut "Ctrl Opt N" *
  //   or press F1 and then select/type Run Code,
  //   or right click the Text Editor and then click Run Code in editor context menu
  //   or click Run Code button in editor title menu
  //   or click Run Code button in context menu of file explorer
  // To stop the running code:
  //   use shortcut "Ctrl Opt M" *
  //   or press F1 and then select/type Stop Code Run
  //   or right click the Output Channel and then click Stop Code Run in context menu
  "code-runner.executorMap": {
    // Introduction:
    //   Make sure the executor PATH of each language is set in the environment variable.
    //   You could also add entry into "code-runner.executorMap" to set the executor PATH.
    // Supported customized parameters:
    //   $workspaceRoot: The path of the folder opened in VS Code
    //   $dir: The directory of the code file being run
    //   $fullFileName: The full name of the code file being run
    //   $fileName: The base name of the code file being run, that is the file without the directory
    //   $fileNameWithoutExt: The base name of the code file being run without its extension
    /* ------ 编译、运行只有一个文件的cpp文件 ------ */
    // 注:路径中有空格不会出现问题
    "cpp": "g++ $fullFileName -o $dir\"$fileNameWithoutExt\"\".out\" -W -Wall -O2 -std=c++17 && $dir\"$fileNameWithoutExt\"\".out\"",
    // 其中 $fullFileName 是绝对路径,是主文件
    // 自己决定是否加入 && rm $dir\"$fileNameWithoutExt\"\".out\"(也可以添加"files.exclude")
    /* ------ 编译、运行多个cpp文件 ------ */
    // "cpp": "g++ $fullFileName <file_to_link> -o $dir\"$fileNameWithoutExt\"\".out\" -W -Wall -O2 -std=c++17 && $dir\"$fileNameWithoutExt\"\".out\"",
    // <file_to_link>的写法:
    //   一般的,你也可以直接写绝对路径
    //     \"/path/xxxx.cpp\"
    //   如果你链接的cpp文件和主文件在一个目录下:
    //     $dir\"xxxx.cpp\"
    //   更一般的,如果你链接的cpp文件不和主文件在一个目录下,需要从当前VSCode的工作目录补充相对路径从而形成绝对路径:
    //     $workspaceRoot\"relative/path/xxxx.cpp\"
    /* ------ 编译c文件 ------ */
    "c": "gcc $fullFileName -o $dir\"$fileNameWithoutExt\"\".out\" -W -Wall -O2 -std=c17 && $dir\"$fileNameWithoutExt\"\".out\"",
    // "c": "gcc $fullFileName <file_to_link> -o $dir\"$fileNameWithoutExt\"\".out\" -W -Wall -O2 -std=c17 && $dir\"$fileNameWithoutExt\"\".out\"",
  },
  // Whether to clear previous output before each run (default is false):
  "code-runner.clearPreviousOutput": true,
  // Whether to save all files before running (default is false):
  "code-runner.saveAllFilesBeforeRun": false,
  // Whether to save the current file before running (default is false):
  "code-runner.saveFileBeforeRun": true,
  // Whether to show extra execution message like [Running] ... and [Done] ... (default is true):
  "code-runner.showExecutionMessage": true, // cannot see that message is you set "code-runner.runInTerminal" to true
  // Whether to run code in Integrated Terminal (only support to run whole file in Integrated Terminal, neither untitled file nor code snippet) (default is false):
  "code-runner.runInTerminal": true, // cannot input data when setting to false
  // Whether to preserve focus on code editor after code run is triggered (default is true, the code editor will keep focus; when it is false, Terminal or Output Channel will take focus):
  "code-runner.preserveFocus": false,
  // Whether to ignore selection to always run entire file. (Default is false)
  "code-runner.ignoreSelection": true,
  // --------------------------------------------------------------------------------------
}

2、一些有用的插件

Chinese:vscode的中文(简体)语言包
C/C++:写C或C++代码必须的插件
Dracula Official:一个好用的主题
vscode-icons-mac:调整文件管理器的图标,使得图标更加符合我们的习惯(与finder的图标相同),更容易辨认,注意插件一定要是这个名字,否则会不一样
Bracket Pair Colorizer:将白色的括号变为匹配的彩色,并且配对的括号会标记出来
Code Runer:使得vscode中出现一个运行按钮,可以一键运行所有的文件。

3、好用的快捷键

格式化文档:右键Format Document,自动对代码进行排版
command+j:打开终端terminal
command+k+t:更换颜色主题

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270