Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to write and run VSCode C, C++ procedures, I believe that most people do not know much, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to understand it!

0. Preface

This article is for beginners, each step is more 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'll give you a stripped-down version: install the gcc and cmax cymbal + extensions, open the folder, click on the source code, and F1 focus build and debug active file, finish.

Much of this article is available from the official VS Code documentation: C++ programming with Visual Studio Code and extended documentation, and they will be updated (several major updates have been made to this article), which you can read if you want to learn more. This article is also basically from many attempts, if there are any mistakes can be pointed out.

Final effect: real-time display of errors in the compilation phase, code snippets, completion, formatting, compilation and debugging of single files.

1. Preparation of the environment

I won't say much about the official website, download and installation of VSC. VSC is just a plain text editor (editor), not IDE (integrated development environment), no compiler (compiler) and many other features, so the compiler has to install it on its own.

Download the compiler: MinGW-w64-for 32 and 64 bit Windows turn down slightly 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, probably because the domestic "network environment" download failed. If the browser fails to download, change to Xunlei or even the hotspot on the phone, and still fail, then use the method that can access Google.

"install" compiler: the next is a 7z compression package. If you do not know how to decompress Baidu "compressed package how to decompress". After decompression, put it in a place that is not easy to be deleted, and some of it can be removed on top of each other. Keep an eye on the full path of the bin folder. The one in my picture is C:\ mingw64\ bin. Add it to the PATH in the environment variable. If you don't know how to do this, see "B. how to add environment variables" at the end of this article (you can search with Ctrl+F on this page)

Debian is Linux and sudo apt update; sudo apt install build-essential can be used.

The order doesn't matter; the path can be different. Just make sure the gcc.exe is in that folder to verify.

Press Win+R, run cmd (do not skip this step), and type gcc, which should prompt no input files instead of "not internal or external commands" or "cannot recognize the" gcc "entry as the name of a cmdlet, function, script file, or runnable program. If it is "not an internal command or an external command", the folder where gcc is located is not in the Path of the environment variable and should be added. If it is still the same, restart. If the reboot doesn't work, there's something wrong with what you're doing.

Type gcc-v to show the version of gcc. If the version shown is different / older than the one you just downloaded, it means that there is an old version of the compiler in Path, which may have been installed on other IDE fashions. You need to remove the path of the original gcc in the Path.

These two validations must match, otherwise the environment variable must be modified. Be careful not to delete it by mistake.

Don't worry about clang now, it's bound to go wrong. Clang's tutorials have been moved to the back of this article

Enter the last line of output of gcc-v. The version should correspond to your own version, for example, 64-bit should have x86room64 and seh installation extension (extension)

Debug and Format functions: also known as cpptools

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 curly braces

One Dark Pro: probably the most installed theme in VS Code

Extensions that are not recommended / need not be installed:

GBKtoUTF8: converts GBK-encoded documents into UTF8-encoded documents. This extension has not been updated for a long time and may have serious bug

C++ Intellisense: use gtags, the choice of the first version of this article. The effect is very general.

Include Autocomplete: provides the completion of header file names. Now both cpptools and vscode-clangd already have this feature, so there is no need to install it.

C _ cpptools + Snippets:Snippets means to reuse code blocks to achieve Baidu's own effect. Although this extension has a high installation volume, it doesn't feel very useful. Cpptools and clangd also come with some. You can also choose other Snippets extensions or even define them yourself.

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 the transplant of gcc under Windows, and gcc is the most popular combination of Cpicurus + compilers in the world. But the name gcc also refers to the program that compiles the C language, and C++ + is the compiler. That is, the gcc program and the Gmail + program are included in the gcc suite and MinGW. When you only say gcc, you should distinguish it according to the context.

In fact, MinGW and MinGW-w64 are just names like, they are two different projects. For convenience, the MinGW in this article actually refers to MinGW-w64. MinGW itself has not been updated for a long time, do not use it alas, the original MinGW is alive, but it can only produce 32-bit programs

The extension is extension, and the plug-in is plugin,VSC. Most articles are a mixture of the two, not rigorous but can understand, we should learn to grasp the principal contradiction. Of course, everything used in this article is correct.

Optional reading: [science popularization] [FAQ] MinGW vs MinGW-W64 and others

two。 Configure several .json files

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

Open VSC, select open folder; it is best not to choose "add workspace folder", this is the virtual workspace, I have not used, do not guarantee that there is no problem. Click to create a new folder with the name .vscode. The reason for not creating a new folder in resource management is that Windows's Explorer does not allow you to create a folder whose first character is a dot (not supported until after 1903). Then create a launch.json,tasks.json,settings.json (not setting.json) and put it under the .vscode folder. Effect picture:

Be sure to be in .vscode. Don't become parallel.

The contents of these documents are shown below. After copying the following code, Zhihu will automatically add the words with all rights reserved in front of it, which must be deleted when it is actually used. In some places, you can choose to modify it. Compare it with the notes. Note: if it is a place where you write Candles.tasks.json, you have to change it.

Launch.json code

ExternalConsole can be modified according to your preferences; cwd can be the relative path of the program run, if necessary, it can be changed to ${fileDirname} (thank you @ xhx). I won't say much about lldb if I haven't used it. It is normal that type and request do not change color.

/ / https://code.visualstudio.com/docs/cpp/launch-json-reference{ "version": "0.2.0", "configurations": [{"name": "(gdb) Launch", / / configuration name, which will display "type": "cppdbg", / / configuration type in the drop-down menu of the startup configuration. Cppdbg corresponds to the debugging function provided by cpptools. It can only be cppdbg "request": "launch", / / request configuration type, and can be launch (startup) or attach (additional) "program": "${fileDirname} / ${fileBasenameNoExtension} .exe", / / the path of the program to be debugged "args": [], / / the command line parameters passed to the program during debugging Generally set to empty "stopAtEntry": false, / / when set to true, the program will be paused at the entrance of the program, which is equivalent to the working directory of "cwd": "${workspaceFolder}", / / when the program is debugged on main. This is the workspace folder. Change ${fileDirname} to the directory where the file is located: "environment": [], / environment variable "externalConsole": true, / / use a separate cmd window, consistent with other IDE; for false, use the built-in terminal "internalConsoleOptions": "neverOpen", / / if it is not set to neverOpen, you will jump to the "debugging console" tab when debugging, you should not need to manually enter commands to gdb? "MIMode": "gdb", / / specifies the debugger for the connection, which can be gdb or lldb. But I haven't tried lldb "miDebuggerPath": "gdb.exe", / / debugger path, the suffix cannot be omitted under Windows, but not "setupCommands" under Linux: [{/ / template comes with it, it seems to better display the contents of the STL container. Google "description": "Enable pretty-printing for gdb", "text": "- enable-pretty-printing", "ignoreFailures": false}], "preLaunchTask": "Compile" / / tasks executed before the start of the debugging session, usually compilers. Corresponds to the label of tasks.json}]}

Originally, externalConsole was set to false after October 2018 to allow the use of built-in terminals, but in October 2019, cpptools 0.26.1 introduced a bug, resulting in the use of built-in terminals under Win unable to input Chinese, which has not been solved up to 0.29.0. I have open https://github.com/microsoft/MIEngine/pull/1025 to fix, but a month later they do not have review, bad reviews.

Tasks.json code

If you are writing a clocked compiler, the compiler needs to change it to a glossy compiler; if you don't want an additional warning, delete the-Wall section;-std modifies it according to your own needs, but there seems to be a problem with cymbals 17, so it's best to use it instead of adding-fexec-charset under Linux. Anyway, I have added notes to these, but I still can't understand them. Baidu gcc usage tutorial.

Reveal controls whether to jump to the terminal panel at compile time. You can modify it according to your preferences; even if it is set to never, it just doesn't jump automatically, and you can still see the message by manual click.

/ / https://code.visualstudio.com/docs/editor/tasks{ "version": "2.0.0", "tasks": [{"label": "Compile", / / task name, corresponding to launch.json 's preLaunchTask "command": "gcc", / / compiler to be used C++ uses Gmail + "args": ["${file}", "- o", / / to specify the output file name. If this parameter is not added, a.exe is output by default. Under Linux, the default a.out "${fileDirname} / ${fileBasenameNoExtension} .exe", "- g", / / generates information related to debugging "- M64", / / somehow 16-bit applications are generated and cannot be run. Add this to force the generation of 64-bit "- Wall", / / enable additional warning "- static-libgcc", / / static link libgcc, usually add "- fexec-charset=GBK", / / the generated program uses GBK coding, without this entry will result in garbled Chinese output under Win Change the traditional system to BIG5 / / "- std=c11", / / the language standard to be used, and modify it according to your own needs. The command compiled by C++ is equivalent to "type": "process". / / the predefined variables and escapes are parsed and passed directly to command. Shell is equivalent to opening shell first and then entering a command So args will parse "group": {"kind": "build", "isDefault": true / / manually selected by ctrl shift B if it is not true via shell, "presentation": {"echo": true, "reveal": "always", / / whether to jump to the terminal panel when executing a task. Can be always,silent,never. For more information, see the VSC document "focus": false, / / set to true to focus on the terminal when executing task, but for compiling task Set to true meaningless "panel": "shared" / / the compilation information of different files shares a terminal panel}, "problemMatcher": "$gcc" / / captures the error message from the terminal at compilation time to the problem panel, and recompiles the code to trigger / / the original Lint again. If you open problemMatcher again, there will be a double error. But the Lint effect of MinGW is so bad. You can comment out}]} settings.json code with Clang

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

Code Runner command line and some options can be modified here according to your needs, want to customize or want to know what it means or refer to this extended documentation and Baidu gcc tutorial. If the terminal uses cmd (Win7 default), you need to use comment-out instead, or change terminal.integrated.shell.windows to PowerShell;Win10. The default is PS.

Thank you for the snippetSuggestions; mentioned by @ Wellin Boss, but it is sometimes a bit problematic to use top, so change it to optional.

{"files.defaultLanguage": "c", / / ctrl+N the default language "editor.formatOnType" after creating a new file: true, / / enter the semicolon (sentence end identification of CAccord +) and automatically format the current line of code "editor.suggest.snippetsPreventQuickSuggestions": false, / / clangd snippets has a lot of jump points If you don't need this, you must manually trigger Intellisense "editor.acceptSuggestionOnEnter": "off", / / my personal habit. Press enter to really wrap the line. Only tab will accept Intellisense / / "editor.snippetSuggestions": "top", / / (optional) snippets is displayed at the top of the completion list. The default is inline "code-runner.runInTerminal": true, / / set to false will be output in "output". Cannot enter "code-runner.executorMap": {"c": "gcc'$fileName'-o'$fileNameWithoutExt.exe'-Wall-O2-M64-lm-static-libgcc-std=c11-fexec-charset=GBK &'. / $fileNameWithoutExt.exe'" "cpp": "gcc +'$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": "cpp + $fileName-o $fileNameWithoutExt.exe-Wall-O2-M64-static-libgcc-std=c++14-fexec-charset=GBK & & $dir$fileNameWithoutExt.exe"}, / / the command that runs when you right-click run code Uncommented only applies to PowerShell (Win10 default) and pwsh, and spaces in the file name can also be compiled and run; commented out applies to cmd (win7 default), PS and bash, but can not run "code-runner.saveFileBeforeRun": true, / / run code before saving "code-runner.preserveFocus": true, / / if the false,run code cursor will focus on the terminal. If you need to input data frequently, you can set it to false "code-runner.clearPreviousOutput": false, / / clear the terminal messages belonging to code runner before each run code. The default false "code-runner.ignoreSelection": true, / / defaults to false. The effect is that a piece of code can be selected by the mouse and executed separately, but C is a compiled language. It is not suitable to use "code-runner.fileDirectoryAsCwd": true, / / change the working directory of the code runner terminal to the file directory and run it again, which will have an impact on cwd-dependent programs. If you want to add cd $dir "C_Cpp.clang_format_sortIncludes": true for false,executorMap, / / adjust the order of include (in alphabetical order)} c_cpp_properties.json when formatting

If you are sure you do not need to use someone else's library, then the current version (after 0.18.0) does not need to create this file, cpptools will automatically use the default settings. So the configuration of this file is no longer included in this article.

If you write your own header file that is not under workspaceFolder, or use someone else's library, you need to manually create this file and put it under .vscode. The template can be referred 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.

Comments are not allowed in this json. In fact, according to the json standard, there can be no comments in the first place.

CompilerPath seems to be the full path of MinGW, accurate to gcc.exe, or 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 delimiter under Windows is a backslash, which should have been escaped with two backslashes, but it is also accepted here by using a slash directly.

In addition to configuring this file, something else needs to be done. Some of them can refer to "multi-file compilation" below.

Supplementary knowledge

Json is a data exchange format, and most of it is a subset of JavaScript, which is now a complete subset. Here it is used as a configuration file. VSC and individual extensions read entries in the json to determine certain functions and behaviors.

Where did so many entries come from? This is actually similar to API. Extension developers will "tell" VSC about the options that are allowed to be modified, and the installation pages of each extension will be written. As a user, VSC prompts you what is available when typing, so it's easy to write.

Why write so much into json? Because VSC itself does not give preferential treatment to C, nor does it to many other languages. And the most critical compilation command has nothing to do with VSC, which is the editor and compiler mentioned above. VSC is not responsible, cannot compile the C language.

The variables that start with $are predefined by VSC, as specified in: Variables Reference. For example, $file will be replaced with the currently open file name when it is actually running.

3. Write code, compile, debug

After you create a new file, you can write code, the c language source code suffix is .c, and C++ is .cpp or .C or .cxx. ). Code files can be saved in the workspace, you can create your own folder, do not have to put in the .vscode folder, but the path (including file names) do not contain Chinese and quotation marks, it is best not to have spaces. The main reason is that many symbols are valid shell syntax, why don't you try deleting a file called-rf with rm under Linux? You can't write it if you haven't checked it.

Press Alt+Shift+F (or right-click menu) to format the code and modify the format, such as whether the curly braces wrap. See: Format Curly Braces on Same Line in C++ VSCode. Press tab when Intellisense appears to complete the code. There will be multiple jump points when typing snippets. Press tab to jump to the next one.

After stopping typing for a short period of time (one second), there will be Lint, and the extension will give some suggested warning (such as declaring variables but not using them), as long as you know it. If you feel uncomfortable, there are ways not to let it prompt, such as removing-Wall will be less. If you want to remove more warnings, I'll give you a hint:-Wno-.... After finding the parameters, you can use # pragma GCC diagnostic ignored or add to various Flags. Anyway, do your own research. However, cpptools's Lint does not support setting Flags. It's a bit crappy. Follow:Error and Warning Flags? Issue # 2814 microsoft/vscode-cpptools

Next, let's talk about the operation. First, compilation is the process of generating an executable file from the source code. In fact, debugging is a kind of special operation, which can control the operation of the program and is convenient to modify later. These are two different phases. Compilation may pass but debugging may fail, or compilation may fail directly, or compilation may fail before compilation begins. If you only say "failed to run", others will not be able to tell which stage went wrong. If it is certain that a certain stage has passed, then regardless of that stage, you can focus on solving problems at other stages.

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

In the early days of writing a program, I strongly recommend not using f5 as a compilation, because some bug will only generate warnings and will not prevent compilation, but the sooner these things can be solved, the better. The compilation information will be in the "terminal" panel below, and if there is an error in the code, you can click in to see the information reported by the compiler, but because of Lint, ordinary errors can be found and modified immediately, making it much easier to write code.

Just click the breakpoint in front of the column number, and right-click to add a conditional breakpoint. If you want to stop from the beginning, you can add it to the main function, or there is a setting in launch.json. After you start debugging, press f11 to proceed step by step, and the line of code indicated by the arrow is the code to run next; f5 runs all the way to the next breakpoint, and right-click a line of code to choose to run all the way to the specified line

There is a debug bar on the left, you can see the value of the variable, the automatic bar does not have can be manually added: select the expression to be monitored in the code, click the right button and have the option to add directly to the Watch, complex ones need to be manually typed. You can see the value of a variable by hovering your mouse over it, but you can only recognize simple expressions. Stack frames are useful for observing recursion. When stack overflows and segment errors occur, you can also grab "exceptions" and automatically jump to the wrong line.

In particular, for arrays: C language arrays will be reduced to pointers after passing functions, and you can only see the first element by adding an expression directly. At this point, you can force it to point to a fixed size array pointer and then de-reference: for example, int arr [10] is passed into the function and becomes int* arr, add * (int (*) [10]) arr to the Watch, so you can see the complete array. But the length must be written to death, be careful to cross the line. Or a simple program can see it all the time with an array of global variables. Another valid way of writing is only for gdb and not void*: * arr@10.

Keyboard shortcuts: vscode: Visual Studio Code commonly used shortcut keys-Zhiwen Studio. Of course, there is a description of shortcut keys in the English document, and Cheet Sheet can be read, and the English document will be updated. This is listed separately for beginners only.

If you encounter mistakes, first look at "some possible mistakes" below and look at the comments section.

Code Runner

If you don't need to debug, you can right-click run code, or click the play button in the upper right corner. If you are running in a terminal, you can enter data, but without the function of displaying time; in "output", the above two items are opposite.

Press Ctrl + C in the terminal to terminate the program, and you must make sure that the current program has been terminated before the next run (the same is true for task). If you want to copy, select the content and right-click it; paste is not selected by right-click; this operation is limited to Win10,ctrl+c can also copy but may accidentally terminate the program.

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

In fact, Code Runner is only for you to manually enter commands, the function is not strong, it is applicable to different scenarios. Don't think that it is easy for run code to run Hello World, but Code Runner is very strong, and so many of the previous configurations are rubbish.

In addition, Han Jun, the respondent downstairs, is the author of this extension, looking for him for everything (funny).

Multi-file compilation

If you want to do a small amount of multi-file compilation, C language directly use gcc source file 1.c source file 2.c header file 1.h that's fine, C++ uses Gmail +. A.exe is generated by default, plus-o can specify the output file name, and the rest options Baidu gcc use tutorials. If you need to compile multiple times, you can write a batch.

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

If you want to use someone else's library, such as ffmpeg, you may need to specify-I,-l (lowercase L),-L in the command. For specific parameters, read the documentation for that library. You may also need to add a path to c_cpp_properties.json to configure Intellisense.

In these cases, you can consider creating a separate workspace instead of sharing it with single-file compilation. In fact, do not build a new project (Project), only a single file can be debugged, is not conducive to the future use and understanding of large IDE. However, beginners do not need to master so much, do not think that the construction project is very troublesome, without the construction project can be compiled very strong.

In short, these have nothing to do with VSC, using other IDE or manual compilation will encounter similar problems, but also a bit complicated. This article will not discuss these, and solve it on its own.

Save folder

To write code in the future, you must open the previously established folder before you can write, otherwise all Intellisense is not available, only Code Runner can be used. (mainly because the four json are needed. If you create other folders, you need to copy those json and then you can use them.)

You can create a shortcut (right-click New), pass the workspace path as a parameter to the VSC main program, remember to put in double quotes, and add an icon. 1.18 with a real virtual workspace, a window can contain multiple folders that are not together, and the File menu also has the function of "Save Workspace", but I haven't tried it. I'm not sure it's all right.

Clean up temporary files

With this configuration, there must be a lot of exe in the compiled code over a long period of time, and it may be scattered in different folders.

You can consider modifying the json file to specify the directory of the generated file to a folder dedicated to exe; if not, Baidu gcc use tutorials and see the notes in my json. Or search for * .exe in the upper right corner of the explorer and delete it manually.

You can also write a bat, put it in the workspace, and right-click Run Code when you want to use it:

Del% ~ dp0*.exe / Q / sdel% ~ dp0tempCodeRunnerFile.c / Q / sdel% ~ dp0a.out / Q / sdel% ~ dp0*.o / Q / s

Among them,% ~ dp0 will be replaced with the directory where the batch is located, in order to prevent students from choosing the wrong working directory and mistakenly deleting files in the root directory. I also adjusted the setting of code runner to switch to the file directory first, double insurance.

Add pure English input method

Windows 10, the default input method is only one Microsoft Pinyin, and you can convert from Chinese to English by pressing shift once; to maintain compatibility, you can also convert between Chinese and English by pressing ctrl plus space, but this shortcut key is the shortcut that forces Intellisense to be triggered.

Therefore, I strongly recommend adding the "English" language input method manually, switching to pure English input method (win+ space) when normal code, and using the English mode of Chinese input method only when frequent Chinese comments are needed or when writing Chinese in a string.

This can also solve the problem that some games need to use the shift key but the same shortcut key conflicts. The specific operation can be their own Baidu, you can also see I wrote this somewhat complex article: Windows switch display language and add pure English input method.

Some possible errors

For the sake of reading coherence, this section has been moved to "A. some other possible mistakes". If you have a problem, it is a priority to see if it has been mentioned there.

4. Other settin

Some of my other settings are used in the global settings.json and adjusted according to my own situation. I don't need to write them all as I do. Put a comma after you finish one; don't lose it if I haven't added the outermost braces.

Today's VSC uses a visual settings interface, but it was originally edited manually and there are two columns of settings. Click the curly braces in the upper right corner to edit them manually.

Author: Tan Jiuding link: https://www.zhihu.com/question/30315894/answer/154979413 Source: Zhihu copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source. " Editor.fontFamily ":" equidistant boldface SC ", / / control editor font" editor.fontSize ": 16, / / ditto" editor.fontLigatures ": true, / / the effect is not easy to describe, see the last part of https://typeof.net/Iosevka" editor.minimap.enabled ": false, / / I personally do not use minimap, which is the thing on the right" editor.dragAndDrop ": false, / / after the text is selected You can drag them to adjust their position. I don't need "editor.cursorSmoothCaretAnimation": true, / / smooth when I move the cursor "editor.smoothScrolling": true, / / smooth scrolling, but the effect is very weak "files.trimTrailingWhitespace": true, / / when saving, delete the space "files.insertFinalNewline" at the end of each line: true, / / add a whole line at the end of the saved file, the habit "files.autoGuessEncoding" under Linux: false, / / when enabled Attempts to guess the character set encoding when opening the file. See 6 for my reasons for closing it. The default is also disabled "workbench.colorTheme": "One Dark Pro", / / theme "workbench.colorCustomizations": {"activityBar.foreground": "# 39C5BB" / / Custom Color To define other locations, see the official documentation}, "workbench.settings.useSplitJSON": true, / / restore the two-column setting "window.zoomLevel": 0.2, / / overall zoom in "git.enabled": false, / / if you do not use git You can consider closing it "git.ignoreMissingGitWarning": true, / / as above "[c]": {/ / "files.encoding": "gbk" / / this format can be applied to files with specified suffixes. If you really want to use gbk, set it this way. Cpp is the same. }

Veil boldface is a font made by God B downstairs, characterized by good-looking punctuation (error): be5invis/Sarasa-Gothic

Although Consolas is OK in Windows's own font, it only has English font. Although Microsoft Yahei is a sans serif font, it is not equidistant, which is very unsuitable for programming, and isometric lines are not equidistant. Good-bye. Without the new fonts, I don't know about the other two major systems, but there are simply no fonts available for programming in Windows. Consolas Garyahei, it's okay, but why not use a better one?

6. About Chinese and garbled codes

VS Code output Chinese will appear garbled, many people have encountered. This is because the source code defaults to UTF-8 encoding and cmd/PowerShell is GBK encoding. If you compile directly, you will output "Hello" as "raccoon". Linux doesn't have this problem.

One solution is to use gcc, compile with the parameter-fexec-charset=GBK (the current configuration is available), the generated program is GBK-encoded, and the source file is still UTF8. And clang's execution-charset supports only UTF-8, so there is no solution with clang.

Another method is to use wide character output, which is a bit complicated, see: C language and some tests in Chinese (Win, UTF8 source code). This article also mentions chcp 65001.

Directly changing the language of non-Unicode programs to UTF8 (beta) will result in garbled code for all programs that use GBK, which is unacceptable.

Of course, if you are not going to insist on using UTF8 as the source code encoding, you can just use GBK coding.

If you are opening an existing GBK-encoded file, VS Code will open by default with UTF-8 encoding (unless you set up a guess encoding), so that the Chinese in the editor will be garbled, at this time to point the lower right corner of the GBK, select "re-open by encoding", select UTF-8. Then why not turn on automatic guessing coding? You can refer to my answer: what if the VS Code Chinese comments show garbled codes? If you're not worried, go ahead.

If you send the code file to other people who use Windows, it is best to convert it to GBK, otherwise others may get garbled when they open it with notepad (the notepad after 1803 has been improved a little, and Unicom will not garble any more).

For debugging, no matter what you do, gdb cannot debug a program that exists in Chinese in the path. This looks like gdb's bug, but the priority is very low: [gdb] cannot not open source file with Chinese/Unicode characters in path when debugging Issue # 602 microsoft/vscode-cpptools

In short, there is no good way to solve these questions for Windows, because the set used in this article was moved from Linux. There should be no such problems with Linux.

7. Error not finding header file

Gcc is not in Path. Go back to the verification step above.

C_cpp_properties.json is manually configured and contains incorrect paths. If you don't create this file, don't worry about it.

Try rebooting.

If you guarantee that all these points meet the requirements, then there is nothing I can do. Or change to other tutorials of the interviewee. Note that this sentence is the ultimate Fallback, if you are sure you have no operational errors, then do not have to ask me, I can not solve.

Another error in which the header file cannot be found:

This is because the default target of clang is msvc, which requires the parameter-- target=x86_64-w64-mingw.

This default target is written in the source code, I looked 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 it can be solved. Or install Windows SDK instead of using mingw, which conforms to the default target.

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

twelve。 Using clang under Win

In fact, this section was originally the main part of this article, but it does introduce too many concepts, and the effect is not so good (because there is no libc++), now it is all here to become optional content. In theory, it works better in WSL, but maybe it will jump from one pit to another. I haven't tried it. This section is only reserved for trampling experience.

Q: why install Clang?

A: error prompts are more friendly. And: where is Clang better than GCC?

How do you pronounce Q:Clang?

A: the correct answer is /? kl??/, that is, c pronounces "OK"; but in fact, it is based on mutual understanding. For example, it is understandable to say SQL as circle.

Q: why install both Clang and MinGW?

A: because Clang under Win does not have libc++. You can also choose to install VS with Windows SDK, so you don't need MinGW. This is more official, but it's bigger.

Q:MSVC integration install failed / unable to find a Visual Studio installation...

A: that's why Clang uses the backend of MSVC by default. But this section uses MinGW, so don't worry about the hint. Or install Windows SDK.

Environment

LLVM Download Page: download Clang from this page. Select Windows (64-bit) in Pre-Built Binaries. No .sig file is required.

Vscode-clangd: provide Intellisense and Lint functions; for warehouse and usage, please see: clangd/clangd

This article has been used in this article. If there is a problem with vscode-clangd, you can consider changing it to this one. The configuration is different. You need to change the clang.cflags;. If there is no problem, do not install it.

Clang-Format: install it only if you want to customize the code style, such as whether the curly braces wrap. You need to learn how to use the

CodeLLDB:lldb 's vscode extension requires a Python environment; I haven't used it

Configuration

The compilation command adds a sentence-- target=x86_64-w64-mingw. The default target of clang is msvc. If you don't add it, the header file will not be found.

C_Cpp.errorSquiggles, C_Cpp.autocomplete and C_Cpp.suggestSnippets are all turned off, otherwise it will be repeated with the clangd report.

Compile_flags.txt

In fact, just set those compilation options, basically using-Wall and-- target=x86_64-w64-mingw. Clangd uses only the compile_flags.txt that is closest to the file to be evaluated. Because you need to guarantee-- target, it's best to create a root directory that is placed on the workspace disk to use as a fallback.

But what's awkward is that both C and C++ will use .h as the header file, so if you don't add any std,.c and .cpp, you can lint correctly, but .h will use C mode. It doesn't feel like a good idea for fallback. Again, or pretend to be Windows SDK.

13. My experience of writing code

Volume, ontology + compiler + extension, if only used to write C, the hard disk occupation is not small, up to 1G. The memory footprint is relatively small (about 0.5g); the bug that used to eat a lot of memory has been fixed long ago.

Perhaps the first advantage of VSC is that it looks good? Although it is not specifically designed for CCompact +, it should be the most modern plain text editor today. And Lint alone is much stronger than wintc, cfree and dev C++, not to mention dev C++ 's own Debug function has bug.

Other IDE,CodeBlocks are still alive, though the historical baggage is obvious. Clion has a beautiful interface and strong functions, but only in English, it may be difficult to use it. Students can apply for key free of charge, otherwise they will charge for it. If you want to use Windows SDK, the next Visual Studio (Installer), Community version of C++ desktop development is, which is in line with Clang's default Target, but I think it is better to directly use VS. Other respondents' comments on some C's IDE can be seen in this answer: rookies with no programming foundation are ready to learn C, using VC6 or VS2015?

I also want to say to the student party: being able to read and configure this article on Baidu by myself is much better than posting countless hand-holding parties and people waiting for teachers to post IDE in QQ groups. If you have the ability, I suggest you read the VSC document: Documentation for Visual Studio Code, it's not complicated, it's good to experience the practical application of English.

a. Some other possible mistakes

If you only write a hello world without any breakpoints, it is normal to flash / flicker after pressing f5. If you want the program to stop running, you can add one or two getchar () at the end. I don't understand why you use two sometimes. Ask your C language teacher; either use system ("pause"), or add a point, or use a built-in terminal (externalConsole false) in launch.json. If you insist on using an external terminal and do nothing, you just want to run it and pause it there, then VSC can't do it, at least my configuration can't, and I don't want to study it, because I use a built-in terminal.

PreLaunchTask "Compile" has been terminated and the exit code is 1: this prompt will be given when error is compiled and you are running with F5; if you click to 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 the error is 1? So it's no use just telling me that this prompt appears, it means something went wrong, no one can see the reason, the reason is in the "terminal" panel. If Hello World can debug and run properly, but this error occurs in some other code, it is likely that there is something wrong with your own code.

The terminal will be reused by the task, press any key to close: have you ever heard of "press any key to continue"? That's 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, regardless of success or error will display it, it is an illustrative text.

Can't open..., can't find the file (file:///build/glibc-OTsEL5/glibc-2.27/...): I encountered this problem under Linux, it looks like you are trying to step in a library function, but there is no source code. The solution is to place 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. Maybe the function name is mistyped, or there is no include header file. Anyway, there is something wrong with your own code.

Ld: cannot open output file... Permission denied: the original program is still running (such as an endless loop) and cannot be overwritten, so the generation fails. The task manager can end that process.

Under MinGW, using strcmp in the Watch window will cause gdb to crash and exit for unknown reasons. It is normal under linux.

After renaming the file, the existing Lint will still be in the problem bar; the breakpoint may become invalid after modifying the file. And there are some other small bug like this, usually just turn off the VSC and then turn it on.

Bash for Windows or WSL cannot be used in this configuration because the backslash in bash is recognized as a newline. Cpptools now provides a snippets for Bash on Windows Launch for launch.json. Now there is another Remote WSL. But I haven't tried how to use these.

If you want to debug, do not turn on optimization. Gcc can also retain some debugging information with-Og, but after using clang, you can no longer debug with gdb. Even so, I had a problem when I was writing code that I couldn't jump into a function, and VS could jump in.

Vscode-clangd failed to detect printf and scanf and realloc correctly for the first time, but it was fine after using it once in the code. I don't know why.

There should be no &: the terminal should use PowerShell or code runner's executorMap instead with the two commands I commented out. Take a look at the instructions of settings.json above.

Crt0_c.c: (.text.startup + 0x2e): undefined reference to `WinMain': has no main function, or writes main as mian.

Use clang+mingw,#include to report 'float.h' file not found' under Win and change it to Gmail +. I think this should be the library's bug, anyway, I don't know how to solve it. Or try not to use Clover 17.

b. How to add environment variables

Graphical method: right-click "this computer" and select Properties, or press win+PauseBreak. Select the advanced system settings, advanced, environment variables on the left. Select Path from the above entries, edit, and create a new one. Then fill in the path of the folder containing the target exe. For example, if gcc is in C:\ mingw\ bin\ gcc, enter C:\ mingw\ bin,Win is case-insensitive.

Command line: open cmd or PS,setx / m path "% path%;C:\ mingw\ bin\". This command does not require administrator privileges and does not exit with the exit of the terminal (just like the graphical effect above).

If you don't know how to modify it, you can search Baidu or bilibili for "environment variables" to watch the video. Most of them are not C, but there is not much difference. Be careful not to delete them by mistake.

The above is all the contents of this article "how to write and run C, C++ programs in VSCode". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report