Home > Development Tools > VSCode > How to write and run C and C++ programs with VSCode

How to write and run C and C++ programs with VSCode

青灯夜游
Release: 2020-12-10 17:31:11
forward
10317 people have browsed it

How to write and run C and C++ programs with VSCode

Related recommendations: "vscode Basic Tutorial"

## 0. Preface

This article is for beginners, and each step is detailed. Read this article to learn some knowledge about the command line, program compilation and debugging, and using VS Code. If you find this article troublesome, I will give you a simplified version: install gcc and c/c extensions, open the folder, click open source code, F1, build and debug active file, and done.

Many contents of this article can be obtained from the official VS Code documentation:

C programming with Visual Studio Code and the documentation of each extension, and they will also be updated (this article has also been published several times Major updates), if you want to know more about it, you can check it out. This article is basically the result of many attempts. If there are any errors, please point them out.

Final effect: Real-time display of errors, code snippets, completion, formatting, single-file compilation and debugging during the compilation phase.

1. Environment preparation

I won’t go into details about VSC’s official website, download, and installation. VSC is just a plain text

editor(editor), not an IDE (integrated development environment). It does not contain a compiler(compiler) and many other functions, so the compiler must be installed by yourself. .

Download the compiler:

MinGW-w64 - for 32 and 64 bit Windows Scroll down a little and select x86_64-posix-seh in the latest version. It is best not to use Download Latest Version. This is an online installation package. The download may fail due to the domestic "network environment". If the browser fails to download, try downloading it via Thunder or connecting to the hotspot on your mobile phone. If it still fails, use a method that allows you to access Google.

"Install" compiler: What comes down is a 7z compressed package. If you don't know how to decompress, you can search "How to decompress a compressed package" on Baidu. After unzipping, put it in a place where it will not be easily deleted. You can remove some of the overlapping files. Be optimistic about the full path of the bin folder. In my picture it is C:\mingw64\bin, and add it to the PATH in the environment variable. If you don't know how to do this step, see "B. How to add environment variables" at the end of this article (you can search with Ctrl F on this page)

Use on Debian Linux

sudo apt update; sudo apt install build-essential is enough.

How to write and run C and C++ programs with VSCode
How to write and run C and C++ programs with VSCode

#The order is not important; the path can be different, anyway, just make sure gcc.exe is in that folder
Verification

Press Win R, run cmd (don't skip this step), enter gcc, you should be prompted

no input files

instead of "Not an internal or external command" or "The "gcc" item cannot be recognized as The name of a cmdlet, function, script file, or executable program." If it is "not an internal command or an external command", it means that the folder where gcc is located is not in the Path of the environment variable and needs to be added. If the problem persists after adding it, restart. If it still doesn't work after restarting, there is something wrong with your own operations. Enter

gcc -v

to display the gcc version. If the version displayed is different/older than the you just downloaded, it means that there is an old version of the compiler in Path, which may have been installed by installing another IDE. You need to remove the original gcc path in Path. These two verificationsmust comply with

, otherwise the environment variables must be modified. Be careful

not to delete by mistake.

How to write and run C and C++ programs with VSCode
#Don't worry about clang now, something will go wrong. The clang tutorial has been moved to the back of this article
How to write and run C and C++ programs with VSCode
Enter the last line of output of gcc -v. The version must correspond to your own, for example, 64-bit must have x86_64 and seh

Install extension

  • C/C: also known as cpptools, provides Debug And Format function
  • Code Runner: right-click to compile and run a single file, which is very convenient; but cannot Debug

Other optional extensions:

  • Bracket Pair Colorizer 2: Rainbow Braces
  • One Dark Pro: Probably the theme with the highest number of VS Code installations

Not recommended/not required to install extensions:

  • GBKtoUTF8: Convert GBK-encoded documents to UTF8-encoded documents. This extension has not been updated for a long time and may have serious bugs
  • C Intellisense: uses gtags, the choice for the first version of this article. The effect is very very general
  • Include Autocomplete: Provides header file name completion. Now cpptools and vscode-clangd already have this function, so there is no need to install it
  • C/C Snippets: Snippets That is to say, reuse code blocks, and the effect will be Baidu by yourself; although the installation volume of this extension is high, I personally feel that it is not very useful. cpptools and clangd also come with some; you can also choose other Snippets extensions or even define your own

Supplementary knowledge

  • The compiler turns the source code into an executable file, and the editor is the software you type. Notepad is an editor, and VSC is also an editor. The editor cannot compile and run the program, because that is the job of the compiler
  • MinGW is a port of gcc under Windows, and gcc is the most popular C/C compiler combination in the world . But the name gcc also refers to the program that compiles the C language, and g is the C compiler. That is, the gcc program and the g program are included in the gcc suite and MinGW. When only gcc is mentioned, it must be distinguished according to the context
  • In fact, MinGW and MinGW-w64 are just similar in name, they are two different projects. For convenience, MinGW in this article actually refers to MinGW-w64. MinGW itself has not been updated for a long time, don’t use itOh, it turns out that MinGW is alive, but it can only produce 32-bit programs
  • Extensions are extensions, and plug-ins are plugins. VSC uses the former name. Most articles use a mixture of the two, which is not rigorous but can be understood. You must learn to grasp the main contradiction. Of course, the correct ones are used in this article.
  • Optional reading: [Popular Science][FAQ]MinGW vs MinGW-W64 and others

2. Configuration few A .json file

Create a folder where you plan to store the code, called the workspace folder; The path cannot contain Chinese characters and quotation marks , and it is best not to have spaces. I use C:\VS-Code-C. C and C need to create different folders respectively, unless a virtual workspace is used. Do not select the folder where the compiler is stored in the previous section. The source code and compiler should be kept separately.

Open VSC, choose to open the folder; it is best not to select "Add workspace folder". This is a virtual workspace. I have not used it, so I cannot guarantee that it will be OK. Click to create a new folder named .vscode. The reason for not creating a new one in resource management is that Windows Explorer does not allow the first character of a created folder to be a dot (supported after 1903). Then create launch.json, tasks.json, settings.json ( is not setting.json) and put them in the .vscode folder. Rendering:

How to write and run C and C++ programs with VSCode
It must be in .vscode, don’t make it parallel

The contents of these files are as follows. After copying the following code, Zhihu will automatically add a few lines in front of it saying that all rights are reserved. You must delete it when you actually use it. Some places are optional to modify, so check it out by yourself according to the comments. Note: If writing in C, one part of tasks.json must be modified.

launch.json code

externalConsole can be modified according to your own preferences; cwd can be the relative path when the program is running, and can be changed to ${ if necessary fileDirname} (Thanks @xhx). I have never used lldb so I won’t say much. It is normal for type and request not to change color.

// https://code.visualstudio.com/docs/cpp/launch-json-reference
{
    "version": "0.2.0",
    "configurations": [{
        "name": "(gdb) Launch", // 配置名称,将会在启动配置的下拉菜单中显示
        "type": "cppdbg", // 配置类型,cppdbg对应cpptools提供的调试功能;可以认为此处只能是cppdbg
        "request": "launch", // 请求配置类型,可以为launch(启动)或attach(附加)
        "program": "${fileDirname}/${fileBasenameNoExtension}.exe", // 将要进行调试的程序的路径
        "args": [], // 程序调试时传递给程序的命令行参数,一般设为空即可
        "stopAtEntry": false, // 设为true时程序将暂停在程序入口处,相当于在main上打断点
        "cwd": "${workspaceFolder}", // 调试程序时的工作目录,此为工作区文件夹;改成${fileDirname}可变为文件所在目录
        "environment": [], // 环境变量
        "externalConsole": true, // 使用单独的cmd窗口,与其它IDE一致;为false时使用内置终端
        "internalConsoleOptions": "neverOpen", // 如果不设为neverOpen,调试时会跳到“调试控制台”选项卡,你应该不需要对gdb手动输命令吧?
        "MIMode": "gdb", // 指定连接的调试器,可以为gdb或lldb。但我没试过lldb
        "miDebuggerPath": "gdb.exe", // 调试器路径,Windows下后缀不能省略,Linux下则不要
        "setupCommands": [
            { // 模板自带,好像可以更好地显示STL容器的内容,具体作用自行Google
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": false
            }
        ],
        "preLaunchTask": "Compile" // 调试会话开始前执行的任务,一般为编译程序。与tasks.json的label相对应
    }]
}
Copy after login

Originally, after October 2018, the built-in terminal could be used by setting externalConsole to false, but in October 2019, cpptools 0.26.1 introduced a bug, which made it impossible to input Chinese using the built-in terminal under Win. As of now, 0.29 .0 still unresolved. I have opened itgithub.com/microsoft/MI Came to fix it, but a month later they had no review, negative review.

tasks.json code

If is written in C , the compiler needs to be changed to g; if you don’t want additional warnings, delete the -Wall one; -std Modify it according to your own needs, but there seems to be a problem with c 17. It is best to use c 14 at most; there is no need to add -fexec-charset under Linux. Anyway, I have added comments to these, but I still can’t understand them, Baidu gcc usage tutorial.

reveal controls whether to jump to the terminal panel during compilation. You can modify it according to your own preferences; even if it is set to never, it will not jump automatically, and you can still see the information by manually clicking in.

// https://code.visualstudio.com/docs/editor/tasks
{
    "version": "2.0.0",
    "tasks": [{
        "label": "Compile", // 任务名称,与launch.json的preLaunchTask相对应
        "command": "gcc",   // 要使用的编译器,C++用g++
        "args": [
            "${file}",
            "-o",    // 指定输出文件名,不加该参数则默认输出a.exe,Linux下默认a.out
            "${fileDirname}/${fileBasenameNoExtension}.exe",
            "-g",    // 生成和调试有关的信息
            "-m64", // 不知为何有时会生成16位应用而无法运行,加上此条可强制生成64位的
            "-Wall", // 开启额外警告
            "-static-libgcc",     // 静态链接libgcc,一般都会加上
            "-fexec-charset=GBK", // 生成的程序使用GBK编码,不加这条会导致Win下输出中文乱码;繁体系统改成BIG5
            // "-std=c11", // 要用的语言标准,根据自己的需要修改。c++可用c++14
        ], // 编译的命令,其实相当于VSC帮你在终端中输了这些东西
        "type": "process", // process是把预定义变量和转义解析后直接全部传给command;shell相当于先打开shell再输入命令,所以args还会经过shell再解析一遍
        "group": {
            "kind": "build",
            "isDefault": true // 不为true时ctrl shift B就要手动选择了
        },
        "presentation": {
            "echo": true,
            "reveal": "always", // 执行任务时是否跳转到终端面板,可以为always,silent,never。具体参见VSC的文档
            "focus": false,     // 设为true后可以使执行task时焦点聚集在终端,但对编译C/C++来说,设为true没有意义
            "panel": "shared"   // 不同的文件的编译信息共享一个终端面板
        },
        "problemMatcher":"$gcc" // 捕捉编译时终端里的报错信息到问题面板中,修改代码后需要重新编译才会再次触发
        // 本来有Lint,再开problemMatcher就有双重报错,但MinGW的Lint效果实在太差了;用Clang可以注释掉
    }]
}
Copy after login

settings.json code

Put the contents of this file into "User Settings" to override global settings, otherwise they will only be valid in the current workspace. Each of these two points has its own advantages.

Code Runner's command line and some options can be modified here according to your own needs. If you want to customize it or want to know what it means, please refer to the documentation of this extension and the Baidu gcc usage tutorial. If the terminal uses cmd (Win7default), you need to comment it out, or change terminal.integrated.shell.windows to PowerShell; Win10 defaults to PS and does not need to be changed.

Thanks@Wellin Boss for the snippetSuggestions mentioned; however, there are still some problems with using top, so it is changed to optional.

{
    "files.defaultLanguage": "c", // ctrl+N新建文件后默认的语言
    "editor.formatOnType": true,  // 输入分号(C/C++的语句结束标识)后自动格式化当前这一行的代码
    "editor.suggest.snippetsPreventQuickSuggestions": false, // clangd的snippets有很多的跳转点,不用这个就必须手动触发Intellisense了
    "editor.acceptSuggestionOnEnter": "off", // 我个人的习惯,按回车时一定是真正的换行,只有tab才会接受Intellisense
    // "editor.snippetSuggestions": "top", // (可选)snippets显示在补全列表顶端,默认是inline

    "code-runner.runInTerminal": true, // 设置成false会在“输出”中输出,无法输入
    "code-runner.executorMap": {
        "c": "gcc '$fileName' -o '$fileNameWithoutExt.exe' -Wall -O2 -m64 -lm -static-libgcc -std=c11 -fexec-charset=GBK && &'./$fileNameWithoutExt.exe'",
        "cpp": "g++ '$fileName' -o '$fileNameWithoutExt.exe' -Wall -O2 -m64 -static-libgcc -std=c++14 -fexec-charset=GBK && &'./$fileNameWithoutExt.exe'"
        // "c": "gcc $fileName -o $fileNameWithoutExt.exe -Wall -O2 -m64 -lm -static-libgcc -std=c11 -fexec-charset=GBK && $dir$fileNameWithoutExt.exe",
        // "cpp": "g++ $fileName -o $fileNameWithoutExt.exe -Wall -O2 -m64 -static-libgcc -std=c++14 -fexec-charset=GBK && $dir$fileNameWithoutExt.exe"
    }, // 右键run code时运行的命令;未注释的仅适用于PowerShell(Win10默认)和pwsh,文件名中有空格也可以编译运行;注释掉的适用于cmd(win7默认)、PS和bash,但文件名中有空格时无法运行
    "code-runner.saveFileBeforeRun": true, // run code前保存
    "code-runner.preserveFocus": true,     // 若为false,run code后光标会聚焦到终端上。如果需要频繁输入数据可设为false
    "code-runner.clearPreviousOutput": false, // 每次run code前清空属于code runner的终端消息,默认false
    "code-runner.ignoreSelection": true,   // 默认为false,效果是鼠标选中一块代码后可以单独执行,但C是编译型语言,不适合这样用
    "code-runner.fileDirectoryAsCwd": true, // 将code runner终端的工作目录切换到文件目录再运行,对依赖cwd的程序产生影响;如果为false,executorMap要加cd $dir

    "C_Cpp.clang_format_sortIncludes": true, // 格式化时调整include的顺序(按字母排序)
}
Copy after login

c_cpp_properties.json

If you are sure you don’t need to use other people’s libraries, then the current version (after 0.18.0) No need to create this file, cpptools The default settings will be used automatically. Therefore, this article no longer contains the configuration of this file.

If you have written the header file yourself and it is not under the workspaceFolder, or you are using someone else's library, you need to manually create this file and put it under .vscode. For templates, please refer to: Microsoft/vscode-cpptools.

Some past experience:

  • The path of the library should be added to includePath and browse
  • If recursive inclusion is required, add /**# at the end ##.
  • This json does not allow comments. In fact, according to the json standard, it cannot have comments.
  • It seems that the compilerPath must be the full path of MinGW, accurate to gcc.exe, otherwise it will prompt that the header file cannot be found; Under Linux, it is /usr/bin/gcc; but I haven’t tested it for a long time.
  • The directory separator under Windows is a backslash. Originally, two backslashes should be used to escape, but directly use a slash. Bang here also accepts
  • In addition to configuring this file, other operations need to be performed. For part of it, please refer to the "Multiple File Compilation" below
Supplementary Knowledge

json is a data exchange format, most of it is a subset of JavaScriptconfiguration file. VSC and various extensions will read the entries in json to determine certain functions and behaviors.

Where do so many entries come from? This is actually similar to API. Extension developers will "tell" VSC the options that allow modification, which are written on the installation page of each extension. As a user, VSC will prompt you what is available when typing, so it is actually very easy to write.

Why do we need to write so many things into json? Because VSC itself does not give special treatment to the C language, nor to many other languages. And the most critical compilation command has nothing to do with VSC. This is the matter of the editor and compiler mentioned above. VSC is not responsible for, cannot, or cannot compile C language.

The variables starting with $ are VSC predefined variables. For details, see: Variables Reference. For example, $file will be replaced by the currently opened file name during actual operation.

3. Write code, compile and debug

You can write code after creating a new file. The suffix of c language source code is .c, and c is .cpp or .C or .cxx (this Do you want me to teach you too...). Code files can be saved in the workspace. You can create your own folder. does not need to be placed in the .vscode folder , but the path (including the file name) should not contain Chinese characters and quotation marks , preferably without spaces. The main reason is that many symbols are valid shell syntax. Otherwise, try using rm to delete a file called -rf under Linux? I definitely can’t write it down without checking it out.

Press Alt Shift F (or use the right-click menu) to format the code. To modify the formatting method, such as whether the curly braces are wrapped in new lines, you can see: Format Curly Braces on Same Line in C VSCode. When Intellisense appearspress tab to complete the code. When typing snippets, multiple jump points will appear. Press tab to jump to the next one.

After you stop typing for a short period of time (one second), Lint will appear. The extension will give you some suggestive warnings (such as declaring variables but not using them). Just be clear about it yourself. If you feel uncomfortable, there are ways to prevent it from prompting. For example, removing -Wall will reduce the number of prompts. If you want to remove more warnings, let me remind you: -Wno-.... After finding the parameters, you can use #pragma GCC diagnostic ignored or add them to various Flags. Anyway, do your own research. However, Lint of cpptools does not support setting Flags, which is a bit confusing. Follow: Error and Warning Flags? · Issue #2814 · microsoft/vscode-cpptools

Next, let’s talk about running. First, compilation is the process of generating an executable file from source code. Debugging is actually a special kind of operation, which is a means to control the operation of the program and facilitate subsequent modifications. These are two different stages. Compilation may pass but debugging fails, compilation may fail directly, or compilation may fail before compilation starts. If you just say "operation failed", others will not be able to tell which stage the problem is. If it is determined that a certain stage has been passed, then you don't have to worry about that stage and can focus on solving problems in other stages.

Press Ctrl Shift B to simply compile, and press F5 to compile and debug; originally ctrl F5 was to run but not debug, but now cpptools does not support it, and it will still debug. Follow: Support "Run without debugging" · Issue #1201 · microsoft/vscode-cpptools

In the early stages of writing a program, I strongly recommend not to use f5 as a compiler, because some bugs will only generate warnings and will not prevent compilation, but the earlier these things are resolved, the better. The compilation information will be in the "Terminal" panel at the bottom. If there is an error in the code, click on it to see the information reported by the compiler; but because of Lint, common errors can be discovered and corrected immediately, making it much easier to write code.

To add a breakpoint, just click in front of the column number. You can add a conditional breakpoint by right-clicking. If you want to stop it from the beginning, you can add it to the main function, or there is a setting in launch.json. After starting debugging, press f11 to proceed step by step. The line of code pointed by the arrow is the code to be run next; f5 will run until the next breakpoint. Right-click a line of code to choose to run it all the time. to the specified line.

There is a debugging bar on the left, where you can see the values ​​of variables. If there is no automatic bar, you can add it manually: select the expression to be monitored in the code, right-click and there are options to directly add it to the Watch. It is complicated. Just need to hit by hand. You can see the value of the variable by placing the mouse on it, but only simple expressions can be recognized. Stack frames are useful for observing recursion. In case of stack overflow and segmentation fault, you can also capture "exceptions" and automatically jump to the wrong line.

Specially, for arrays: arrays in C language will degenerate into pointers after being passed by functions. If you add an expression directly, you can only see the first element. At this time, you can force convert it to a fixed-size array pointer and then dereference it: for example, int arr[10] will become int* arr after it is passed into the function, in Watch Add *(int(*)[10])arr so you can see the complete array. But the length must be specified, so be careful if you cross the line. Or a simple program can always see it using the global variable array. Another way of writing that is only valid for gdb and is non-void*: *arr@10.

Shortcut keys: vscode: Visual Studio Code common shortcut keys - Zhiwen Studio. Of course, there are shortcut key descriptions in the English document, and you can also view the Cheet Sheet, and the English document will be updated. This one is listed separately only for beginners.

If you encounter an error, first read the "Some Possible Errors" below and the comment area.

Code Runner

If you don’t need to debug, you can directly right-click and select run code, or click the play button in the upper right corner. If run in the terminal, data can be input, but the function of displaying time is missing; in "output", the above two items are reversed.

Press Ctrl C in the terminal to terminate the program. You must ensure that the current program has been terminated before running it next time (the same is true for tasks). If you want to copy, just right-click after selecting the content; to paste, right-click when it is not selected; this operation is limited to Win10, ctrl c can also copy, but the program may be terminated accidentally.

It can also be used to compile and run programs in non-workspaces, but gcc is used by default unless executorMap is placed in the global settings. According to my configuration, there is one difference between task and Code Runner: working directory. The former is the folder you opened, and the latter is the folder where the file is located. Of course, they can also be modified by themselves.

In fact, Code Runner only replaces your manual input of commands , and its function is not strong. It is applicable to different scenarios. Don't think that running code to run Hello World is easy, Code Runner is very powerful, and all the previous configurations are garbage.

In addition, the respondent downstairs, Han Jun, is the author of this extension. If you have any questions, please contact him (funny).

Multi-file compilation

If you want to perform a small amount of multi-file compilation, use C language directlygcc source file 1.c source file 2.c header file 1.hThis is good, C uses g. A.exe is generated by default, add -o to specify the output file name, and the remaining options are Baidu gcc usage tutorial. If you need to compile multiple times, you can write a batch process.

If you want to do a lot of multi-file compilation, learn how to write makefiles or use cmake. Then change the tasks command to call make (or mingw32-make), etc.

If you want to use other people's libraries, such as ffmpeg, you may need to specify -I, -l (lowercase L), - in the command L. Read the documentation of that library for specific parameters. You may also need to add the path to c_cpp_properties.json to configure Intellisense.

In these cases, you can consider building a separate workspace and do not share it with single-file compilation. In fact, debugging only a single file without creating a new project is not conducive to future use and understanding of large-scale IDEs. However, beginners don’t need to master so much. Don’t think that building a project is troublesome. You can compile very well without building a project.

In short, these have nothing to do with VSC. You will encounter similar problems when using other IDEs or manual compilation, which is also a bit complicated. This article will not discuss these in detail, and we will solve them by ourselves.

Save the folder

LaterWhen writing code, you must open the previously created folder to write, otherwise all Intellisense will be gone, and only Code Runner can be used. (Mainly need those four jsons. To create other folders, you need to copy those jsons.)

You can create a shortcut (right-click to create) and pass the workspace path as a parameter. VSC main program, remember to put double quotes; you can also add an icon. 1.18 has a real virtual workspace, and one window can contain multiple folders that are not together. There is also a "Save Workspace" function in the "File" menu, but I have not tried it, so I can't guarantee that it will be OK.

How to write and run C and C++ programs with VSCode

Clean up temporary files

According to this configuration, there will definitely be a big problem when compiling the code for a long time The pile of exe may also be scattered in different folders.

可以考虑修改一下json文件,把生成文件的目录指定到一个专门放exe的文件夹里;如果不会,百度gcc使用教程以及看我的json里的注释。或者资源管理器右上角搜索*.exe然后手动删除。

也可也写个bat,放到工作区里,要用的时候右键Run Code:

del %~dp0*.exe /q /s
del %~dp0tempCodeRunnerFile.c /q /s
del %~dp0a.out /q /s
del %~dp0*.o /q /s
Copy after login

其中%~dp0会被替换成该批处理所在目录,这是为了防止有同学选错工作目录,误删根目录下的文件;code runner的设置我也调整成了先切换到文件目录,双保险。

添加纯英文输入法

Windows 10,默认输入法只有一个微软拼音,按一次shift就能进行中英转换;为了保持兼容,按ctrl加空格也能进行中英转换,但这个快捷键正是强制触发Intellisense的快捷键。

所以,我强烈建议手动添加“英语”语言输入法,正常代码时切换到纯英文输入法(win+空格),在需要频繁中文注释或者在字符串里写中文时才用中文输入法的英文模式。

这样也可以解决某些游戏需要用到shift键但同样快捷键冲突的问题。具体操作可以自己百度,也可以看我写的这篇有点复杂的文章:Windows 切换显示语言与添加纯英文输入法

某些可能出现的错误

为了阅读的连贯性,这一部分移到了“A. 一些其它可能出现的错误”。遇到问题优先查看那里是否已经提了。

4. 其他设置

我的一些其他的设置,用在全局settings.json里,根据自己的情况调整,不需要全部照着我的写。写完一个以后要打逗号;最外面的那个大括号我没加,就别弄丢了

现在的VSC用的是可视化的设置界面,其实原本是手动编辑且出现两列设置的。点击右上角那个花括号就能手动编辑。

作者:谭九鼎
链接:https://www.zhihu.com/question/30315894/answer/154979413
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

"editor.fontFamily": "等距更纱黑体 SC", // 控制编辑器字体
"editor.fontSize": 16, // 同上
"editor.fontLigatures": true, // 连体字,效果不太好形容,见 https://typeof.net/Iosevka 最后一部分
"editor.minimap.enabled": false, // 我个人不用minimap,就是右边那个东西
"editor.dragAndDrop": false, // 选中文字后,可以拖动它们调整位置。我是不需要
"editor.cursorSmoothCaretAnimation": true, // 移动光标时变得平滑
"editor.smoothScrolling": true, // 滚动平滑,不过效果很微弱
 
"files.trimTrailingWhitespace": true, // 保存时,删除每一行末尾的空格
"files.insertFinalNewline": true, // 保存后文件最末尾加一整行空行,Linux下的习惯
"files.autoGuessEncoding": false, // 启用后,会在打开文件时尝试猜测字符集编码。我关闭的理由见6,默认也是禁用的

"workbench.colorTheme": "One Dark Pro", // 主题
"workbench.colorCustomizations": {
      "activityBar.foreground": "#39C5BB" // 自定义颜色;想定义其它位置参见官方文档
},
"workbench.settings.useSplitJSON": true, // 恢复手动编辑时的两列设置
"window.zoomLevel": 0.2, // 整体放大

"git.enabled": false, // 如果你不用git,可以考虑关闭它
"git.ignoreMissingGitWarning": true, // 同上

"[c]": {
    // "files.encoding": "gbk" // 这样的格式可以对指定后缀的文件应用设置,如果你实在想用gbk,就这样设置吧。cpp同理。
},
Copy after login

更纱黑体是楼下B神做的字体,特点是标点好看(误):be5invis/Sarasa-Gothic

Consolas虽然是Windows自带字体中还算行的,但它只有英文字体;微软雅黑虽然是非衬线字体,但它不是等距的,这一点非常不适合编程,等线也不等距;中易宋体……告辞。不下新的字体,其他两大系统我不清楚,Windows下简直没有编程可用的字体。Consolas加雅黑嘛,也还行吧,不过能用更好的干嘛不用呢。

6. 关于中文和乱码

VS Code输出中文会出现乱码,很多人都遇到过。这是因为源代码默认是UTF-8编码,cmd/PowerShell是GBK编码。直接编译,会把“你好”输出成“浣犲ソ”。Linux就没有这个问题。

一种解决方法是用gcc,编译时用-fexec-charset=GBK这个参数(目前的配置是有的),生成的程序就是GBK编码的,源文件仍是UTF8而clang的execution-charset supports only UTF-8,所以用clang就无解。

另一种方法是用宽字符输出,有点复杂,见:C语言与中文的一些测试 (Win, UTF8源码) 。此文也提到了chcp 65001的事。

直接修改非Unicode程序的语言为UTF8(beta)会导致所有用GBK的程序乱码,这是不可接受的。

当然,如果你不打算坚持用UTF8作为源代码的编码,那直接用GBK编码也行。

如果是打开已有的以GBK编码的文件,VS Code默认会以UTF-8编码打开(除非你设置了猜测编码),这样编辑器内的中文就会乱码,此时要点右下角的GBK,选“通过编码重新打开”,选UTF-8即可。那为什么不打开自动猜测编码呢?可以参见我的这个回答:VS Code 中文注释显示乱码怎么办?。如果你不担心,那就开吧。

如果把代码文件发给其他用Windows的人,最好转成GBK,否则别人用记事本打开有可能会乱码(1803后的记事本改善了一些,联通已经不会乱码了)。

对于调试,无论怎么做,gdb都无法调试路径中存在中文的程序。这个貌似是gdb的bug,但是优先级极低:[gdb] cannot not open source file with Chinese/Unicode characters in path when debugging · Issue #602 · microsoft/vscode-cpptools

总之,对于Windows,这些问题没什么好办法,因为本文用的这一套就是从Linux搬过来的。用Linux应该就没有这些问题了。

7. Header file not found error

How to write and run C and C++ programs with VSCode

    ##gcc is not in Path. Go back and look at the verification step above
  • C_cpp_properties.json was manually configured and the included path was incorrect. If you haven’t created this file, don’t worry.
  • Restart and try
If you ensure that these points meet the requirements, then I don’t have any good ideas...or give me another answer Master's tutorial. Note that this sentence is the ultimate fallback. If you are sure that you did not make a mistake, then there is no need to ask me. I can't solve it.

Another error that the header file cannot be found:

How to write and run C and C++ programs with VSCode

This situation is Because the default target of clang is msvc, you need to add the

--target=x86_64-w64-mingw parameter.

This default target is hard-coded in the source code. I searched around and couldn't find a normal way to modify it. Download the source code of clang, change it yourself, and then compile clang itself, maybe you can solve it. Or install Windows SDK instead of using mingw, which will comply with the default target.

Of course the easiest way at this time is to compile with gcc.

12. Using clang under Win

In fact, this part was originally the main part of this article, but it does introduce too many concepts, and the effect is not that good (because there is no libc), Now it's all optional here. Theoretically, it's better to use it in WSL, but maybe it will jump from one pit to another. I haven't tried it. This part is only for pitfall experience.

    Q: Why should I install Clang?
  • A: The error message is more friendly. And:
    How is Clang better than GCC?
  • Q: How to pronounce Clang?
  • A: The correct answer is /?kl??/, that is, c sounds "ke"; however, it is actually based on mutual understanding. For example, it is also understandable to say SQL as circle.
  • Q: Why do I need to install both Clang and MinGW?
  • A: Because Clang under Win does not have libc. You can also choose to install VS and use Windows SDK, which does not require MinGW. This is more official, but larger.
  • Q: MSVC integration install failed / unable to find a Visual Studio installation...
  • A: It’s the reason for the previous one. Clang uses the MSVC backend by default. But this part uses MinGW, so you don't need to worry about this prompt. Otherwise, install Windows SDK

Environment

  • LLVM Download Page: Download Clang on this page. Select Windows (64-bit) in Pre-Built Binaries, there is no need to download the .sig file
  • vscode-clangd: Provides Intellisense and Lint functions; for the warehouse and usage, see:
  • clangd/clangd
  • C/C Clang Command Adapter: This article has used it before. If there is a problem with vscode-clangd, you can consider changing to this one. The configuration is a little different, so you need to change clang.cflags; if there is no problem, don’t install it.
  • Clang-Format: Only installed if you want to customize the code style, such as whether the curly braces are newline. Need to additionally learn how to use
  • CodeLLDB: the vscode extension of lldb, which requires a Python environment; I have never used it

Configuration

    Add
  • --target=x86_64-w64-mingw to the compilation command. The default target of clang is msvc. If you don’t add it, the header files
  • C_Cpp.errorSquiggles, C_Cpp.autocomplete, C_Cpp.suggestSnippets will not be found. Turn them off, otherwise they will be repeated as reported by clangd

compile_flags.txt

In fact, it is to set those compilation options, basically Just use -Wall and --target=x86_64-w64-mingw. clangd will only use the compile_flags.txt closest to the file being evaluated. Because you need to ensure that there is a --target, it is best to create a root directory on the workspace disk for fallback.

But what’s more confusing is that both C and C will use .h as the header file. If you don’t add any std, .c and .cpp can lint correctly, but .h will use the C mode. There seems to be no good solution for fallback. Again, just install Windows SDK.

13. My experience in writing code

In terms of size, the ontology compiler extension, if only used to write C, the hard disk occupation is not too small, up to 1G. The memory usage is still relatively small (about 0.5g); there was a bug that used a lot of memory, but of course it has been fixed long ago.

The first advantage of VSC may be that it looks good? Although it is not specifically designed for C/C, it should be the most modern plain text editor now. And Lint alone is much better than wintc, cfree, and dev c, not to mention that dev c's own Debug function has bugs.

Other IDEs, CodeBlocks is still alive, although the historical baggage is very obvious. Clion has a beautiful interface and powerful functions, but it is only in English, so it may be a bit difficult to get started. Students can apply for a key for free, otherwise there is a fee. If you want to use the Windows SDK, next Visual Studio (Installer), the Community version is checked for C desktop development. This will comply with Clang's default Target, but I think it is better to use VS directly. For other respondents’ evaluations of some C IDEs, you can read this answer: I am a novice with no programming foundation who is going to learn C language. Should I use VC6 or VS2015? .

I also want to say something to the student party: If you can Baidu to this article, try to understand it, and configure it yourself, you are already better than the countless people who reach out to Tieba and wait for the teacher to distribute the IDE in the QQ group Much stronger. If you have the ability, I still recommend that you read the VSC documentation: Documentation for Visual Studio Code. It is not complicated. It is also good to experience the practical application of English.

A. Some other possible errors

  • If you only write hello world without adding any breakpoints, the black box will flash past/flashback after pressing f5 It's a normal phenomenon. If you want the program to pause, you can add one or two getchar(); at the end. I don’t understand why two are sometimes used? Ask your C language teacher; or use system("pause"), or add breakpoints, or use the built-in terminal (externalConsole false) in launch.json. If you insist on using an external terminal and do nothing, and just want to pause it after running, then VSC can't do it, at least not with my configuration, and I don't want to study it, because I use the built-in terminal.
  • preLaunchTask "Compile" has been terminated, the exit code is 1: there is an error in compilation and you use F5 to run, you will have this prompt; if you click Still debug, the file that was successfully compiled last time will be debugged. . In fact, all compilation failures will trigger this error. Isn't it common sense that the return value of an error is 1? So just telling me that this promptis useless at all, it means something went wrong and no one can see the reason.The reason is in the "Terminal" panel. If Hello World can be debugged and run normally, but this error occurs in some other code, it is likely that there is an error in your own code .
  • The terminal will be reused by the task, press any key to close: Ever heard of "press any key to continue"? This is what this sentence means. This sentence is even more useless than the exit code 1 above. It does not contain any valid information at all. It will be displayed regardless of success or error. It is just an explanatory text.
  • Cannot open..., file not found (file:///build/glibc-OTsEL5/glibc-2.27/...): I encountered this problem under Linux, it looks like it should be You are trying to step in a library function, but do not have the source code. The solution is to put the next glibc in the specified location. Or see this:
  • Disable "Unable to open file" during debug · Issue #811 · Microsoft/vscode-cpptools.
  • undefined reference to xxx ... linker command failed: An undeclared function was called. It may be that the function name is typed incorrectly, or there is no include header file. In short, there is an error in your own code.
  • ld: cannot open output file ... permission denied: The original program is still running (such as an infinite loop) and cannot be overwritten, so the generation fails. Just end that process in Task Manager.
  • Under MinGW, using strcmp in the Watch window will cause gdb to crash and exit for unknown reasons. Normal under linux.
  • After renaming the file, the existing Lint will still be in the problem column; breakpoints may become invalid after modifying the file. There are also some other small bugs like this. Generally, just close VSC and reopen it.
  • This configuration cannot be used with Bash for Windows or WSL because backslashes in bash are recognized as newlines. cpptools now provides a
  • Bash on Windows Launch snippets for launch.json. Now there is another Remote WSL. But I haven't tried using any of these.
  • If you want to debug, don't turn on optimization. Gcc can still retain some debugging information by using -Og, but after clang is used, gdb cannot be used for debugging. Even so, I encountered the problem of being unable to jump into a function when I was writing code, but VS could jump into it.
  • vscode-clangd could not correctly detect printf, scanf and realloc for the first time, but it got better after using it once in the code. I do not know why either.
  • There should be no & at this time: Use PowerShell or code runner's executorMap in the terminal to use the two commands I commented out. See the description of settings.json above for details.
  • crt0_c.c:(.text.startup 0x2e): undefined reference to `WinMain': There is no main function, or main is written as main.
  • Use clang mingw under Win, #include will report 'float.h' file not found, change it to g and it will be fine. I think this should be a bug in the library. Anyway, I don't know how to solve it. Or don’t use C 17 and try
B. How to add environment variables

Graphical way: right-click "This Computer" and select properties; or press win PauseBreak. Select Advanced System Settings, Advanced, Environment Variables on the left. Select Path among the items above, edit, and create new. Then fill in the path to the folder containing the target exe. For example, if gcc is in

C:\mingw\bin\gcc, fill in C:\mingw\bin. Win is not case sensitive.

Command line method: open cmd or PS,

setx /m path "%path%;C:\mingw\bin\". This command does not require administrator privileges and will not exit when the terminal exits (it has the same graphical effect as above).

If you still don’t know how to modify it, you can search for “environment variables” on Baidu or Bilibili and watch the video. Most of them are not C but the difference is not big, just be careful

and don’t delete by mistake.


If you have any questions, you can leave a message for discussion, but it is best to describe it in detail. And I say it again, Don't just tell me the sentence "preLaunchTask terminated with code 1". This sentence is useless.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of How to write and run C and C++ programs with VSCode. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:zhihu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template