VSCode 的 C/C++ 开发环境配置(Windows 10)

前置条件

  1. 操作系统:Windows 10
  2. 能够自由访问国际互联网
  3. VSCode 安装 C/C++ Extension Pack 插件

安装 mingw

Download MinGW-w64 - for 32 and 64 bit Windows from SourceForge.net 下载。

image-20210506234653957

运行安装程序,途中设置如下:

image-20210506234821529

Architecture: x85_64
Threads: posix
Exception: seh

之后的选项全部默认,点 Next 即可。

环境变量 PATH 增加:

C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin

CMD 执行:

g++

输出如下则安装成功:

g++: fatal error: no input files
compilation terminated.

配置 VSCode

cmd 执行:

C:\Users\i>mkdir C:\doc\Projects\cpp\my_proj_1

C:\Users\i>cd C:\doc\Projects\cpp\my_proj_1

C:\doc\Projects\cpp\my_proj_1>code .

从而创建项目文件夹,并调用 VSCode 编辑该文件夹。

创建 main.c:

#include <stdio.h>
int main(int argc, char const *argv[])
{
    printf("test.\n");
    return 0;
}

VSCode 中,按 F1,选择 C/C++: Edit Configurations (JSON):

image-20210506235749405

可以看到已经自动生成了如下配置:

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\gcc.exe",
            "cStandard": "gnu17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "windows-gcc-x64"
        }
    ],
    "version": 4
}

F5(运行),会产生 lauch.json 文件:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "gcc.exe - 生成和调试活动文件",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\\\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\gdb.exe",
            "setupCommands": [
                {
                    "description": "为 gdb 启用整齐打印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: gcc.exe 生成活动文件"
        }
    ]
}

切换到 Terminal 选项卡,可以看到程序已经运行成功:

image-20210507000011009

此时还需要配置代码格式化。按 F1,搜索 settings,选 Preferences: Open User Settings

image-20210507000610194

搜索 @ext:ms-vscode.cpptools format

image-20210507000639041

Clang_format_fallback Style 中填写 Visual Studio(或者其他格式化方案)。此后,按 Alt + Shift + F 可格式化 C/C++ 代码。

此时仍然没有完成,因为只有单文件能运行。

创建 need.h, need.c:

#if !defined(__NEED_H__)
#define __NEED_H__
#include <stdio.h>

void head();

#endif // __NEED_H__

#include "need.h"

void head(){
    printf("head.\n");
}

main.c 改为:

#include <stdio.h>
#include "need.h"

int main(int argc, char const *argv[])
{
    head();
    printf("test.\n");
    return 0;
}

将会产生如下报错

C:/doc/Projects/cpp/my_proj_1/main.c:6: undefined reference to `head'
collect2.exe: error: ld returned 1 exit status

可以手动修改 tasks.json:

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: gcc.exe 生成活动文件",
            "command": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\gcc.exe",
            "args": [
                "-g",
                "${fileDirname}/**.c",
                "-o",
                "${fileDirname}\\\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "调试器生成的任务。"
        }
    ],
    "version": "2.0.0"
}

对于 C++,使用 ${fileDirname}/**.cpp 来代替。

这种方法不好,因为无法跨平台,也无法应对更复杂的情况。更好的办法是用 CMakeFileLists.txt,有空再写。

配置 CMake

Download | CMake 下载 cmake-xx.xx.xx-windows-x86_64.zip。解压到 C:\Program Files\cmake\cmake-3.20.2-windows-x86_64

C:\Program Files\cmake\cmake-3.20.2-windows-x86_64\bin 添加到环境变量 PATH

创建项目目录 my_proj_2

PS C:\doc\Projects\cpp> mkdir my_proj_2


    目录: C:\doc\Projects\cpp


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        2021-05-07      0:35                my_proj_2


PS C:\doc\Projects\cpp> cd .\my_proj_2\
PS C:\doc\Projects\cpp\my_proj_2> code .

建立目录和文件结构:

image-20210507004157384

CMakeLists.txt

cmake_minimum_required (VERSION 3.3)
project (my_proj_2 CC)
set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c++14 -g")
add_subdirectory(src)

src\CMakeLists.txt:

include_directories(${PROJECT_SOURCE_DIR}/include)
aux_source_directory(. SRCS)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
add_executable(my_proj_2 ${SRCS})

demo.h:

#if !defined(__DEMO_H__)
#define __DEMO_H__
#include <iostream>

class Demo
{
public:
    Demo();
    ~Demo();
};

#endif // __DEMO_H__

demo.cc:

#include "demo.h"

Demo::Demo()
{
    std::cout << "created!\n";
}

Demo::~Demo()
{
    std::cout << "destroyed!\n";
}

main.cc:

#include "demo.h"
#include <iostream>
int main(int argc, char const *argv[])
{
    auto s = new Demo();    
    delete s;
    std::cin.get();
    return 0;
}

对于如下报错:

image-20210507004738466

请检查文件名后缀应该是 .cc (.cpp, c++, cxx)

创建 build_run.bat

if not exist build md build
cd build
cmake -G "MinGW Makefiles" ..
make

运行 build_run.bat

PS C:\doc\Projects\cpp\my_proj_2> .\build_run.bat

C:\doc\Projects\cpp\my_proj_2>if not exist build md build

C:\doc\Projects\cpp\my_proj_2>cd build

C:\doc\Projects\cpp\my_proj_2\build>cmake -G "MinGW Makefiles" ..
-- The CXX compiler identification is GNU 8.1.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/bin/g++.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: C:/doc/Projects/cpp/my_proj_2/build

C:\doc\Projects\cpp\my_proj_2\build>make
[ 33%] Building CXX object src/CMakeFiles/my_proj_2.dir/demo.cc.obj
[ 66%] Building CXX object src/CMakeFiles/my_proj_2.dir/main.cc.obj
[100%] Linking CXX executable ..\bin\my_proj_2.exe
[100%] Built target my_proj_2

至此,自动 build 已经实现。

配置一键运行

按一下 F5

image-20210507005709702

C++ (GDB/LLDB)。会生成 launch.json,修改如下:

{
    "version": "0.2.0",
    "configurations": [

        {
            "name": "C++ Launch (GDB)",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/build/bin/my_proj_2.exe", // 可执行文件位置
            "miDebuggerPath":"gdb", //gdb 位置
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "preLaunchTask": "compile", //task.json 中的 label
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

其中要改的就是 my_proj_2,其他的以后复制即用。

再按一次 F5,报错如下:

image-20210507005921923

随便创建,会出现 task.json,修改为:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "compile",
            "type": "shell",
            "command": "./build_run.bat",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

再按一次 F5,可以正常运行。