Related recommendations: "vscode Basic Tutorial"
## 0. PrefaceThis 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 preparationI won’t go into details about VSC’s official website, download, and installation. VSC is just a plain texteditor(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.
sudo apt update; sudo apt install build-essential is enough.
#The order is not important; the path can be different, anyway, just make sure gcc.exe is in that folder
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
not to delete by mistake.
Other optional extensions:
Not recommended/not required to install extensions:
Supplementary knowledge
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:
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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
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 ithttps://github.com/microsoft/MIEngine/pull/1025 Came to fix it, but a month later they had no review, negative review.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
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:
/**# at the end ##.
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.
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.
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).
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.h
This 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.
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.
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:
1 2 3 4 |
|
其中%~dp0
会被替换成该批处理所在目录,这是为了防止有同学选错工作目录,误删根目录下的文件;code runner的设置我也调整成了先切换到文件目录,双保险。
Windows 10,默认输入法只有一个微软拼音,按一次shift就能进行中英转换;为了保持兼容,按ctrl加空格也能进行中英转换,但这个快捷键正是强制触发Intellisense的快捷键。
所以,我强烈建议手动添加“英语”语言输入法,正常代码时切换到纯英文输入法(win+空格),在需要频繁中文注释或者在字符串里写中文时才用中文输入法的英文模式。
这样也可以解决某些游戏需要用到shift键但同样快捷键冲突的问题。具体操作可以自己百度,也可以看我写的这篇有点复杂的文章:Windows 切换显示语言与添加纯英文输入法。
为了阅读的连贯性,这一部分移到了“A. 一些其它可能出现的错误”。遇到问题优先查看那里是否已经提了。
我的一些其他的设置,用在全局settings.json里,根据自己的情况调整,不需要全部照着我的写。写完一个以后要打逗号;最外面的那个大括号我没加,就别弄丢了。
现在的VSC用的是可视化的设置界面,其实原本是手动编辑且出现两列设置的。点击右上角那个花括号就能手动编辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
更纱黑体是楼下B神做的字体,特点是标点好看(误):be5invis/Sarasa-Gothic
Consolas虽然是Windows自带字体中还算行的,但它只有英文字体;微软雅黑虽然是非衬线字体,但它不是等距的,这一点非常不适合编程,等线也不等距;中易宋体……告辞。不下新的字体,其他两大系统我不清楚,Windows下简直没有编程可用的字体。Consolas加雅黑嘛,也还行吧,不过能用更好的干嘛不用呢。
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应该就没有这些问题了。
--target=x86_64-w64-mingw parameter.
Environment
Configuration
to the compilation command. The default target of clang is msvc. If you don’t add it, the header files
,
C_Cpp.autocomplete,
C_Cpp.suggestSnippets will not be found. Turn them off, otherwise they will be repeated as reported by clangd
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.
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.
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. C:\mingw\bin\gcc, fill in
C:\mingw\bin. Win is not case sensitive.
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).
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!