Visual Studio Code 如何配置 C 编译器

Visual Studio Code 是一款功能强大的代码编辑器,它可以通过安装一些扩展和进行配置来支持 C 语言的开发。以下是一步一步的指南,帮助您在 Visual Studio Code 中配置 C 编译器。

1. 安装 C 编译器

首先需要安装一个 C 编译器,常用的有 GCC 和 Clang。以下是一些不同操作系统下的选择:

  • Windows
    • MinGW-w64: 一种常用的 GCC 编译器移植版本,可以从 https://www.mingw-w64.org/ 下载并安装。
    • Cygwin: 另一个 GCC 编译器的移植版本,可以从 https://www.cygwin.com/ 下载并安装。
    • Visual Studio: 安装 Visual Studio 时可以选择安装 C++ 编译器,这样就可以使用 Visual Studio 的编译器。
  • macOS: macOS 系统默认已经安装了 Clang 编译器。

2. 安装 C/C++ 扩展

在 Visual Studio Code 中,需要安装 C/C++ 扩展来支持 C 语言的开发。在扩展商店中搜索 'C/C++',找到并安装 C/C++ 扩展。

3. 配置编译器路径

在 Visual Studio Code 中,需要配置编译器路径。打开 'File' -> 'Preferences' -> 'Settings',在搜索栏中输入 'executable',找到 'C_Cpp: Intelli Sense Engine' 选项,点击 'Edit in settings.json'。

在 settings.json 文件中加入以下代码:

"configurations": [
    {
        "name": "Win32",
        "includePath": [
            "${workspaceFolder}/**"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE",
            "_UNICODE"
        ],
        "compilerPath": "D:/mingw/bin/gcc.exe",
        "cStandard": "c11",
        "cppStandard": "c++17",
        "intelliSenseMode": "windows-gcc-x64"
    }
],

其中 'compilerPath' 需要根据您的编译器安装路径进行修改。

4. 配置任务

在 Visual Studio Code 中,可以通过配置任务来完成编译和运行。在菜单栏中选择 'Terminal' -> 'Configure Tasks',选择 'Create tasks.json file from templates',选择 'C/C++: g++ build active file'。

在生成的 tasks.json 文件中,可以修改 'command' 和 'args' 来指定编译器路径和编译选项。例如:

"command": "D:/mingw/bin/gcc.exe",
"args": [
    "-g",
    "${file}",
    "-o",
    "${fileDirname}/${fileBasenameNoExtension}.exe"
]

其中 '-g' 表示生成调试信息,'${file}' 表示当前打开的文件,'${fileDirname}/${fileBasenameNoExtension}.exe' 表示生成的可执行文件路径。

5. 编译运行

在 Visual Studio Code 中,可以通过快捷键 'Ctrl+Shift+B' 来编译当前文件。也可以在终端中输入 'task build' 来编译。编译成功后,可以通过 'Ctrl+Shift+P' 打开命令面板,输入 'Run',选择 'Run Code' 来运行程序。也可以在终端中输入 './filename' 来运行程序。

总结

通过以上步骤,您就可以在 Visual Studio Code 中配置 C 编译器并开始编写和运行 C 代码。祝您编程愉快!

Visual Studio Code 配置 C 编译器:入门指南

原文地址: https://www.cveoy.top/t/topic/mUFq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录