VS Code configures C/C++ development environment

1. Software download

The software that needs to be downloaded is as follows:

  • VS Code
  • Compilation tools: MinGW or MSYS2 or VS2022

VS Code download address: link
MinGW download address: link or link
MSYS2 download address: link
VS2022 download address: link

After the above software is downloaded, the installation steps can be installed. It is recommended to choose MinGW as the compilation tool. If you install MinGW, you can use the GCC compiler, and if you install VS2022, you can use the MSVC compiler.

2. Environment configuration

1. Add environment variables

Add the folder MinGWof to your system's environment variables. If the following code is executed on the command line and there is no error prompt, the surface is added successfully.binPATH

gcc --version
g++ --version
gdb --version

The output is as follows:
insert image description here

2. Install the VS Code plugin

Three plugins need to be installed, namely:

  • C/C++
  • C/C++ Extension Pack
  • Atom One Dark Theme (optional, for code theme colors)

insert image description here

3. Compiler parameters

1. GCC

parameter illustrate example
-c Only compile source files, generate object files, do not link
-o Specify the name of the output file -o build\${fileBasenameNoExtension}.exe
-I <include_path> Add header file search path -I ${workspaceFolder}/include
-L <library_path> Add library file search path -L ${workspaceFolder}/lib
-l <library_name> Link the specified library file -lgdi32
-g Generate debug information
-std= Specifies the language standard used -std=c11、-std=c++14
-O Specify the optimization level, the level can be 0, 1, 2, 3, s
-Wall show all warnings
-Werror treat warnings as errors
-pthread Enable support for multithreading
-lm link math library
-mwindows remove the console window

2. MSVC

parameter illustrate example
/c Only compile source files, do not link to generate executable files
/EHsc Enable C++ exception handling support
/Fo+path Specifies the intermediate file path /Fo${workspaceFolder}\build\${fileBasenameNoExtension}.obj
/Fe+path Specify the target file path /Fe${workspaceFolder}\build\${fileBasenameNoExtension}.exe
/I Add include file directory
/D+name[=value] Define preprocessing macros
/W set warning level
/O set optimization level
/Day Generate debug information
/MD Using dynamically linked runtime libraries
/MT Statically linking the runtime library with multithreading
/link pass linker options
/P Generate preprocessed output
/showIncludes show included files
/? show help information

4. Configuration file

You can refer to the article link
to run C/C++ code in VS Code, you can use configuration files to specify: header file path, library file path, compiler path, etc. Configuration files can be automatically generated or manually configured, but most of the time the automatically generated configuration files often cannot meet our requirements, so we need to configure manually more often. It mainly includes three configuration files: c_cpp_properties.json, tasks.json, launch.jsonand the functions of the three configuration files are as follows:

  • c_cpp_properties.json: Configure the compiler path and header file search path for C/C++ extensions to ensure the normal operation of code analysis and IntelliSense
  • tasks.json: configure execution tasks, custom commands or scripts executed in the editor
  • launch.json: Configure the debugger's launch and debug settings

1. Basic configuration

c_cpp_properties.json

{
    
    
    "configurations": [
        // 32{
    
    
            "name": "Win32", // 当前配置的名称
            "includePath": [
                "${workspaceFolder}/**",
                "D:\\C\\VS2022\\Community\\VC\\Tools\\MSVC\\14.35.32215\\include" // 编译器的头文件路径
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            // 此处是你的 Windows SDK 版本号
            "windowsSdkVersion": "10.0.20348.0",
            // 此处是编译器的地址
            "compilerPath": "D:\\C\\VS2022\\Community\\VC\\Tools\\MSVC\\14.35.32215\\bin\\Hostx64\\x86\\cl.exe",
            "cStandard": "c17", // C 标准 
            "cppStandard": "c++17", // C++ 标准
            "intelliSenseMode": "windows-msvc-x86" // 智能感知的模式
        },
        // x64位
        {
    
    
            "name": "x64",
            "includePath": [
                "${workspaceFolder}/**",
                "D:\\C\\VS2022\\Community\\VC\\Tools\\MSVC\\14.35.32215\\include" // 编译器的头文件路径
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            // 此处是你的 Windows SDK 版本号
            "windowsSdkVersion": "10.0.20348.0",
            // 此处是编译器的地址
            "compilerPath": "D:\\C\\VS2022\\Community\\VC\\Tools\\MSVC\\14.35.32215\\bin\\Hostx64\\x64\\cl.exe",
            "cStandard": "c17", // C 标准 
            "cppStandard": "c++17", // C++ 标准
            "intelliSenseMode": "windows-msvc-x64" // 智能感知的模式
        }
    ],
    "version": 4
}

tasks.json

{
    
    
    "tasks": [
        {
    
    
            "label": "MSVC编译",
            "type": "shell",
            "command": "cmd.exe",
            "args": [
                "/c",
                // 编译器地址
                "D:\\C\\VS2022\\Community\\VC\\Auxiliary\\Build\\vcvars32.bat && cl.exe",
                "main.cpp",
                "/Zi",
                "/Od",
                "/EHsc",
                // 中间文件生成目录
                "/Fo${workspaceFolder}\\build\\${fileBasenameNoExtension}.obj", 
                // 目标文件生成目录
                "/Fe${workspaceFolder}\\build\\${fileBasenameNoExtension}.exe", 
            ],
            "options": {
    
    
                "cwd": "${workspaceFolder}" // 作为当前打开目录
            },
            "problemMatcher": [
                "$msCompile"
            ],
            "group": "build",
            "detail": "Task generated by Debugger."
        },
    ],
    "version": "2.0.0"
}

launch.json

{
    
    
    "version": "0.2.0",
    "configurations": [
        {
    
    
            "name": "C/C++: gcc.exe 生成和调试活动文件",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}\\build\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "miDebuggerPath": "D:\\A\\MinGW64\\bin\\gdb.exe", //此处为你的gdb.exe路径
            "setupCommands": [
                {
    
    
                    "description": "为 gdb 启用整齐打印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
    
    
                    "description": "将反汇编风格设置为 Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "MSVC编译"
        }
    ]
}

2. Delete file task configuration

{
    
    
 "label": "删除中间文件",
 "type": "shell",
 "command": "cmd.exe",
 "args": [
     "/c",
     "del",
     "${workspaceFolder}\\build\\*.obj",  	// 删除build文件夹下的所有.obj文件
     "${workspaceFolder}\\build\\*.ilk",	// 删除build文件夹下的所有.ilk文件
     "${workspaceFolder}\\*.pdb",      		// 删除工作空间下的所有.pdb 文件
 ],
 "group": "build",
},

3. Compile, delete and execute

The following tasks.jsonconfiguration files will be executed sequentially: compile source files, delete intermediate files, execute executable file operations.

{
    
    
    "tasks": [
        // MSVC编译
        {
    
    
            "label": "MSVC编译",
            "type": "shell",
            "command": "cmd.exe",
            "args": [
                "/c",
                "D:\\C\\VS2022\\Community\\VC\\Auxiliary\\Build\\vcvars32.bat && cl.exe",
                "main.cpp",
                "/Zi",
                "/Od",
                "/EHsc",
                // 中间文件生成目录
                "/Fo${workspaceFolder}\\build\\${fileBasenameNoExtension}.obj", 
                 // 目标文件生成目录
                "/Fe${workspaceFolder}\\build\\${fileBasenameNoExtension}.exe",
            ],
            "options": {
    
    
                "cwd": "${workspaceFolder}" // 作为当前打开目录
            },
            "problemMatcher": [
                "$msCompile"
            ],
            "group": "build",
            "detail": "Task generated by Debugger."
        },
        // 删除中间文件
        {
    
    
            "label": "删除中间文件",
            "type": "shell",
            "command": "cmd.exe",
            "args": [
                "/c",
                "del",
                "${workspaceFolder}\\build\\*.obj",
                "${workspaceFolder}\\build\\*.ilk",
                "${workspaceFolder}\\*.pdb",
            ],
            "group": "build",
            "dependsOn": [
                "MSVC编译",
            ]
        },
        // RUN
        {
    
    
            "label": "RUN",
            "type": "shell",
            "command": "cmd.exe",
            "args": [
                "/c echo. && echo. && echo. && echo. && echo. && echo ================================================================================ && .\\build\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
    
    
                "cwd": "${workspaceFolder}"
            }, // 作为当前打开目录
            "group": {
    
    
                "kind": "build",
                "isDefault": true
            },
            "dependsOn": [
                "删除中间文件",
            ]
        },
    ],
    "version": "2.0.0"
}

5. Problem solving

1. Solve the problem of executing code console flashback

Method 1
Modify the parameter value launch.jsonin the file toexternalConsolefalse

"externalConsole":false

Method 2
Add at the end of the main program: system("pause");
Method 3
Add at the end of the main program:getchar();

2. Garbled code solution

Method 1
Add the header file <windows.h> and call the API function SetConsoleOutputCP(65001)
insert image description here
Method 2
Change the encoding format of VScode to GBK, or open the source code file with Notepad and save it as ANSI encoding format.
insert image description here
insert image description here
insert image description here
Method 3
Modify the setting.json configuration file of VScode and unify it into one encoding format.
insert image description here
Method 4
The default character set of Windows (Chinese) is Windows-936 (GBK), and the GCC compiler parses it according to UTF-8 when compiling by default. When the character set is not specified, it will be treated as UTF-8, so cause garbled characters. Therefore, it can be solved by adding the following parameters when compiling with GCC.

-fexec-charset=gbk
-finput-charset=gbk

Guess you like

Origin blog.csdn.net/hfy1237/article/details/130781012