Как настроить visual studio code для c
Перейти к содержимому

Как настроить visual studio code для c

  • автор:

 

Configure VS Code for Microsoft C++

In this tutorial, you configure Visual Studio Code to use the Microsoft Visual C++ compiler and debugger on Windows.

After configuring VS Code, you will compile and debug a simple Hello World program in VS Code. This tutorial does not teach you details about the Microsoft C++ toolset or the C++ language. For those subjects, there are many good resources available on the Web.

If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.

Prerequisites

To successfully complete this tutorial, you must do the following:

Install the C/C++ extension for VS Code. You can install the C/C++ extension by searching for ‘c++’ in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).

C/C++ extension

Install the Microsoft Visual C++ (MSVC) compiler toolset.

If you have a recent version of Visual Studio, open the Visual Studio Installer from the Windows Start menu and verify that the C++ workload is checked. If it’s not installed, then check the box and select the Modify button in the installer.

You can also install the Desktop development with C++ workload without a full Visual Studio IDE installation. From the Visual Studio Downloads page, scroll down until you see Tools for Visual Studio 2022 under the All Downloads section and select the download for Build Tools for Visual Studio 2022.

Build Tools for Visual Studio download

This will launch the Visual Studio Installer, which will bring up a dialog showing the available Visual Studio Build Tools workloads. Check the Desktop development with C++ workload and select Install.

Cpp build tools workload

Note: You can use the C++ toolset from Visual Studio Build Tools along with Visual Studio Code to compile, build, and verify any C++ codebase as long as you also have a valid Visual Studio license (either Community, Pro, or Enterprise) that you are actively using to develop that C++ codebase.

Check your Microsoft Visual C++ installation

To use MSVC from a command line or VS Code, you must run from a Developer Command Prompt for Visual Studio. An ordinary shell such as PowerShell, Bash, or the Windows command prompt does not have the necessary path environment variables set.

To open the Developer Command Prompt for VS, start typing ‘developer’ in the Windows Start menu, and you should see it appear in the list of suggestions. The exact name depends on which version of Visual Studio or the Visual Studio Build Tools you have installed. Select the item to open the prompt.

Developer Command Prompt

You can test that you have the C++ compiler, cl.exe , installed correctly by typing ‘cl’ and you should see a copyright message with the version and basic usage description.

Checking cl.exe installation

If the Developer Command Prompt is using the BuildTools location as the starting directory (you wouldn’t want to put projects there), navigate to your user folder ( C:\users\\ ) before you start creating new projects.

Note: If for some reason you can’t run VS Code from a Developer Command Prompt, you can find a workaround for building C++ projects with VS Code in Run VS Code outside a Developer Command Prompt.

Create Hello World

From the Developer Command Prompt, create an empty folder called "projects" where you can store all your VS Code projects, then create a subfolder called "helloworld", navigate into it, and open VS Code ( code ) in that folder ( . ) by entering the following commands:

The "code ." command opens VS Code in the current working folder, which becomes your "workspace". As you go through the tutorial, you will see three files created in a .vscode folder in the workspace:

  • tasks.json (build instructions)
  • launch.json (debugger settings)
  • c_cpp_properties.json (compiler path and IntelliSense settings)

Add a source code file

In the File Explorer title bar, select the New File button and name the file helloworld.cpp .

Add hello world source code

Now paste in this source code:

Now press ⌘S (Windows, Linux Ctrl+S ) to save the file. Notice how the file you just added appears in the File Explorer view ( ⇧⌘E (Windows, Linux Ctrl+Shift+E ) ) in the side bar of VS Code:

File Explorer

You can also enable Auto Save to automatically save your file changes, by checking Auto Save in the main File menu.

The Activity Bar on the far left lets you open different views such as Search, Source Control, and Run. You’ll look at the Run view later in this tutorial. You can find out more about the other views in the VS Code User Interface documentation.

Note: When you save or open a C++ file, you may see a notification from the C/C++ extension about the availability of an Insiders version, which lets you test new features and fixes. You can ignore this notification by selecting the X (Clear Notification).

Explore IntelliSense

In your new helloworld.cpp file, hover over vector or string to see type information. After the declaration of the msg variable, start typing msg. as you would when calling a member function. You should immediately see a completion list that shows all the member functions, and a window that shows the type information for the msg object:

Statement completion IntelliSense

You can press the Tab key to insert the selected member; then, when you add the opening parenthesis, you will see information about any arguments that the function requires.

Run helloworld.cpp

Remember, the C++ extension uses the C++ compiler you have installed on your machine to build your program. Make sure you have a C++ compiler installed before attempting to run and debug helloworld.cpp in VS Code.

Open helloworld.cpp so that it is the active file.

Press the play button in the top right corner of the editor.

Choose C/C++: cl.exe build and debug active file from the list of detected compilers on your system.

You’ll only be asked to choose a compiler the first time you run helloworld.cpp . This compiler will be set as the "default" compiler in tasks.json file.

After the build succeeds, your program’s output will appear in the integrated Terminal.

If you get an error trying to build and debug with cl.exe, make sure you have started VS Code from the Developer Command Prompt for Visual Studio using the code . shortcut.

The first time you run your program, the C++ extension creates tasks.json , which you’ll find in your project’s .vscode folder. tasks.json stores build configurations.

Your new tasks.json file should look similar to the JSON below:

Note: You can learn more about tasks.json variables in the variables reference.

The command setting specifies the program to run; in this case that is "cl.exe". The args array specifies the command-line arguments that will be passed to cl.exe. These arguments must be specified in the order expected by the compiler.

This task tells the C++ compiler to take the active file ( $ ), compile it, and create an executable file ( /Fe: switch) in the current directory ( $ ) with the same name as the active file but with the .exe extension ( $.exe ), resulting in helloworld.exe for our example.

The label value is what you will see in the tasks list; you can name this whatever you like.

The detail value is what you will as the description of the task in the tasks list. It’s highly recommended to rename this value to differentiate it from similar tasks.

The problemMatcher value selects the output parser to use for finding errors and warnings in the compiler output. For cl.exe, you’ll get the best results if you use the $msCompile problem matcher.

From now on, the play button will read from tasks.json to figure out how to build and run your program. You can define multiple build tasks in tasks.json , and whichever task is marked as the default will be used by the play button. In case you need to change the default compiler, you can run Tasks: Configure default build task. Alternatively you can modify the tasks.json file and remove the default by replacing this segment:

Modifying tasks.json

You can modify your tasks.json to build multiple C++ files by using an argument like "$/*.cpp" instead of $ .This will build all .cpp files in your current folder. You can also modify the output filename by replacing "$\\$.exe" with a hard-coded filename (for example "$\\myProgram.exe" ).

Debug helloworld.cpp

  1. Go back to helloworld.cpp so that it is the active file.
  2. Set a breakpoint by clicking on the editor margin or using F9 on the current line.
  3. From the drop-down next to the play button, select Debug C/C++ File.
  4. Choose C/C++: cl.exe build and debug active file from the list of detected compilers on your system (you’ll only be asked to choose a compiler the first time you run/debug helloworld.cpp ).

The play button has two modes: Run C/C++ File and Debug C/C++ File. It will default to the last-used mode. If you see the debug icon in the play button, you can just click the play button to debug, instead of selecting the drop-down menu item.

If you get an error trying to build and debug with cl.exe, make sure you have started VS Code from the Developer Command Prompt for Visual Studio using the code . shortcut.

Explore the debugger

Before you start stepping through the code, let’s take a moment to notice several changes in the user interface:

The Integrated Terminal appears at the bottom of the source code editor. In the Debug Output tab, you see output that indicates the debugger is up and running.

The editor highlights the line where you set a breakpoint before starting the debugger:

The Run and Debug view on the left shows debugging information. You’ll see an example later in the tutorial.

At the top of the code editor, a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.

Debugging controls

Step through the code

Now you’re ready to start stepping through the code.

Click or press the Step over icon in the debugging control panel.

This will advance program execution to the first line of the for loop, and skip over all the internal function calls within the vector and string classes that are invoked when the msg variable is created and initialized. Notice the change in the Variables window on the left.

Debugging windows

In this case, the errors are expected because, although the variable names for the loop are now visible to the debugger, the statement has not executed yet, so there is nothing to read at this point. The contents of msg are visible, however, because that statement has completed.

Press Step over again to advance to the next statement in this program (skipping over all the internal code that is executed to initialize the loop). Now, the Variables window shows information about the loop variables.

Press Step over again to execute the cout statement. (Note that as of the March 2019 release, the C++ extension does not print any output to the Debug Console until the loop exits.)

If you like, you can keep pressing Step over until all the words in the vector have been printed to the console. But if you are curious, try pressing the Step Into button to step through source code in the C++ standard library!

Breakpoint in gcc standard library header

To return to your own code, one way is to keep pressing Step over. Another way is to set a breakpoint in your code by switching to the helloworld.cpp tab in the code editor, putting the insertion point somewhere on the cout statement inside the loop, and pressing F9 . A red dot appears in the gutter on the left to indicate that a breakpoint has been set on this line.

Breakpoint in main

Then press F5 to start execution from the current line in the standard library header. Execution will break on cout . If you like, you can press F9 again to toggle off the breakpoint.

Set a watch

Sometimes you might want to keep track of the value of a variable as your program executes. You can do this by setting a watch on the variable.

Place the insertion point inside the loop. In the Watch window, select the plus sign and in the text box, type word , which is the name of the loop variable. Now view the Watch window as you step through the loop.

Watch window

Add another watch by adding this statement before the loop: int i = 0; . Then, inside the loop, add this statement: ++i; . Now add a watch for i as you did in the previous step.

To quickly view the value of any variable while execution is paused on a breakpoint, you can hover over it with the mouse pointer.

Mouse hover

Customize debugging with launch.json

When you debug with the play button or F5 , the C++ extension creates a dynamic debug configuration on the fly.

There are cases where you’d want to customize your debug configuration, such as specifying arguments to pass to the program at runtime. You can define custom debug configurations in a launch.json file.

To create launch.json , choose Add Debug Configuration from the play button drop-down menu.

You’ll then see a dropdown for various predefined debugging configurations. Choose C/C++: cl.exe build and debug active file.

VS Code creates a launch.json file, which looks something like this:

In the JSON above, program specifies the program you want to debug. Here it is set to the active file folder ( $ ) and active filename with the .exe extension ( $.exe ), which if helloworld.cpp is the active file will be helloworld.exe . The args property is an array of arguments to pass to the program at runtime.

By default, the C++ extension won’t add any breakpoints to your source code and the stopAtEntry value is set to false .

Change the stopAtEntry value to true to cause the debugger to stop on the main method when you start debugging.

From now on, the play button and F5 will read from your launch.json file when launching your program for debugging.

C/C++ configurations

If you want more control over the C/C++ extension, you can create a c_cpp_properties.json file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.

You can view the C/C++ configuration UI by running the command C/C++: Edit Configurations (UI) from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).

Command Palette

This opens the C/C++ Configurations page. When you make changes here, VS Code writes them to a file called c_cpp_properties.json in the .vscode folder.

Command Palette

Visual Studio Code places these settings in .vscode\c_cpp_properties.json . If you open that file directly, it should look something like this:

You only need to add to the Include path array setting if your program includes header files that are not in your workspace or in the standard library path.

Compiler path

The compilerPath setting is an important setting in your configuration. The extension uses it to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide useful features like smart completions and Go to Definition navigation.

The C/C++ extension attempts to populate compilerPath with the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.

The compilerPath search order is:

  • First check for the Microsoft Visual C++ compilerOpe
  • Then look for g++ on Windows Subsystem for Linux (WSL)
  • Then g++ for Mingw-w64.

If you have g++ or WSL installed, you might need to change compilerPath to match the preferred compiler for your project. For Microsoft C++, the path should look something like this, depending on which specific version you have installed: "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/cl.exe".

Reusing your C++ configuration

VS Code is now configured to use the Microsoft C++ compiler. The configuration applies to the current workspace. To reuse the configuration, just copy the JSON files to a .vscode folder in a new project folder (workspace) and change the names of the source file(s) and executable as needed.

Run VS Code outside the Developer Command Prompt

In certain circumstances, it isn’t possible to run VS Code from Developer Command Prompt for Visual Studio (for example, in Remote Development through SSH scenarios). In that case, you can automate initialization of Developer Command Prompt for Visual Studio during the build using the following tasks.json configuration:

Note: The path to VsDevCmd.bat might be different depending on the Visual Studio version or installation path. You can find the path to VsDevCmd.bat by opening a Command Prompt and running dir "\VsDevCmd*" /s .

Troubleshooting

The term ‘cl.exe’ is not recognized

If you see the error "The term ‘cl.exe’ is not recognized as the name of a cmdlet, function, script file, or operable program.", this usually means you are running VS Code outside of a Developer Command Prompt for Visual Studio and VS Code doesn’t know the path to the cl.exe compiler.

VS Code must either be started from the Developer Command Prompt for Visual Studio, or the task must be configured to run outside a Developer Command Prompt.

Как настроить Visual Studio Code для C, C++, Java, Python

Visual Studio Code — популярный редактор кода, бесплатный и с открытым исходным кодом. Но я уверен: каждый из нас, кто пытался настроить Visual Studio Code для разработки приложений на C++, Java или Python, прошел через стадию: “О Боже! Почему нельзя как-нибудь попроще?” Я сам пробовал настроить VS Code пару раз и в итоге закончил тем, что использовал CodeBlocks. 🙁

Прочитав много документации, посмотрев ряд роликов на YouTube и потратив несколько дней на саму настройку VS Code, я пишу эту статью, чтобы все это не пришлось проделывать уже вам!

Сегодня я покажу, как настроить среду разработки для спортивного программирования на C++, Java и Python в VS Code с нуля. Мы также посмотрим, какие расширения больше всего пригодятся, чтобы начать работу с VS Code. В конечном счете, ваша среда разработки будет выглядеть примерно так:

1. Устанавливаем Visual Studio Code

Скачайте последнюю версию Visual Studio Code с официального сайта. Рекомендуется загрузить системный установщик (System Installer), но если у вас нет прав администратора, то пользовательский установщик (User Installer) тоже подойдет. Выполните все обычные шаги по установке и обязательно проставьте все следующие чекбоксы:

Если у вас уже установлен VS Code, но вы все равно хотите начать с чистого листа, следуйте этим инструкциям, чтобы полностью удалить VS Code.

2. Настраиваем расширения

Ниже приведен список расширений, которые нам понадобятся для правильной настройки VS Code. Откройте VS Code и перейдите на панель расширений (Ctrl + Shift + X), которая находится на левой панели инструментов, и начните загружать друг за другом следующие расширения:

    от Microsoft[Важно] Для корректной работы этого расширения нам понадобится установленный и добавленный в PATH компилятор MinGW. Если у вас его нет, следуйте этому руководству. от austin. от Microsoft — вам нужно будет настроить Python для работы этого расширения. Загрузите и установите последнюю версию отсюда. от Microsoft — [Важно] Перед установкой убедитесь, что в вашей системе настроены Java 8 JDK и JRE и указаны все необходимые переменные среды для Java. Если нет, посмотрите это видео о том, как настроить Java на вашем компьютере. от Jun Han — мы будем использовать это расширение для запуска всех наших программ. Для этого необходимо выполнить некоторые шаги по настройке. Мы увидим эти шаги в следующих разделах.

Расширения, перечисленные ниже, необязательны для дальнейшей настройки, но я рекомендую вам обратить на них внимание, посмотреть, заинтересуют ли они вас, и если нет, то перейти к следующему разделу.

  • (Необязательно) Material Theme от Mattia Astronio — это расширение содержит множество приятных глазу тем. Вы можете выбрать любую, какая понравится. Лично я предпочитаю Monokai, которая доступна в VS Code по умолчанию, без каких-либо расширений.

Чтобы выбрать тему, нажмите Ctrl + Shift + P. Откроется палитра команд. Осуществите поиск по слову “theme” и выберите опцию Color Theme. Чтобы настроить иконки, можете выбрать опцию File Icon Theme.

Расширения для тех, кто интересуется FrontEnd-фреймворками для веб-разработки, такими как Angular и React:

  • (Необязательно) Angular Language Service от Angular.
  • (Необязательно) Angular Snippets от John Papa.
  • (Необязательно) ES7 React / Redux / GraphQL / React-Native snippets от dsznajder.
  • (Необязательно) React Native Tools от Microsoft.
  • (Необязательно) Live Server от Ritwick Dey.

3. Настраиваем внешний вид редактора

Итак, мы уже установили VS Code и несколько расширений. Теперь мы готовы настраивать среду разработки. Я создал шаблон для спортивного программирования в VS Code и загрузил его в свой профиль на Github.

Перейдите по этой ссылке и загрузите шаблон себе на компьютер. Распакуйте его в любое место по вашему выбору. После этого откройте получившуюся папку в VS Code. Вы должны увидеть что-то вроде этого:

Пройдитесь по файлам main.cpp, Main.java и main.py и посмотрите на записанный в них образец кода. По сути, шаблонный код, предоставленный в образцах для каждого из этих трех языков, принимает входящие данные из файла input.txt и обеспечивает вывод в файл output.txt. Для каждой программистской задачи, которую вы хотите решить, просто создайте копию этого шаблона и напишите свой код в функции solve().

Теперь создадим ту разбивку экрана, которую вы могли видеть на самом первом изображении в этой статье. Эта разбивка позволяет сразу видеть как ввод, так и вывод вашего кода, что делает ее очень удобной в использовании.

Visual Studio Code — C/C++ Setup

Visual Studio Code is a great open-source editor with plenty of useful plugins for insane amount of languages and frameworks.

However, as C and C++ environment is pretty janky for today’s standards, so is the configuration. So i made this guide to streamline the process and make it easy for somebody new in C, C++ or VSCode to setup a reasonably working dev environment with some useful quality-of-life tools. It might not be IntelliJ-level of quality, but hey — it’s free.

In this guide, i will tell you:

  • What tools you’ll need to start developing C and C++ apps in VSCode
  • What extensions you might want to install to ease up the code writing process, and how to configure them
  • How do you create a C/C++ project in VSCode (with CMake) and integrate it with VSCode

Prerequisites⌗

VSCode⌗

The obvious prerequisite is Visual Studio Code. Install it from the official site: https://code.visualstudio.com/, or from a repository if you’re using a package manager.

For Windows: either download the installer from official site and run it, or install VSCode via scoop: scoop install vscode . btw; i strongly recommend scoop — great package manager

For Linux: if you have it in your package manager repository, install it from there. Otherwise, use the installer from official site.

For MacOS: same as for Linux. Probably. I don’t use MacOS so i can’t really tell.

Fun fact; there are two versions of VSCode you can find on the internet and in package managers — OSS version, and Non-OSS. The OSS version is basically the VSCode you’d get by downloading it from official repository and building it yourself. Non-OSS version is the one from Microsoft distribution (for example, their official site), and the only difference between them is that Non-OSS version uses some Microsoft propertiary code, while OSS doesn’t. There is some functional difference (IIRC, OSS version lacks proprietary features like Settings Sync or Remote WSL/SSH/Containers), but both are fully compatible in terms of plugins and configuration, so you usually don’t need to worry about the exact version you’ve installed.

C/C++ Toolchain⌗

There are many C/C++ toolchains available, and i’m not gonna enforce one, because this guide is mostly toolchain-independent (in the end we’re gonna use build system, but most of the examples are for GCC). However, if you are new to C/C++, i’d recommend starting with GCC (or MinGW, if you’re on Windows) as it’s easy to install and use out of the box.

If you already have your preferred toolchain installed and configured, feel free to go to the next step. If not, here’s the guide:

For Windows:

  • Download MinGW-w64 installer from here — that’s basically 64-bit GCC for Windows.
  • Run the installer. Make sure to change the Architecture setting to x86_64 , otherwise you’ll get a 32-bit toolchain and that’s not what we want here. Also; make sure the Threads setting is configured as posix , otherwise you won’t be able to use standard C++ threading library. Don’t change other settings there.
  • After installation, add the /bin subdirectory (with gcc.exe and g++.exe inside) of installed toolchain to system PATH variable. It, obviously, can be different than the one on the screenshot belowGo to “Edit the system environment variables” settings in Windows, then press the “Environment variables…” button and add the new entry with GCC bin directory, either to user, or system PATH variable — doesn’t really matter which one.
  • Check if you’ve done it correctly by running PowerShell or cmd.exe and trying out gcc —version command. You should see something like this: If that’s not what you see, check if you’ve added correct path to PATH variable. Or restart the shell/computer, and try again.

Important note about MinGW and MinGW-w64 — Both official MinGW and MinGW-w64 distributions are pretty outdated (they’re using GCC 8.1.0, while the latest release at the time of writing is 11.0). If you want a fresh new version of GCC on your Windows machine, either use MSYS2 or WinLibs package. However, MSYS2 setup is a bit longer than MinGW, and both of these packages can have their issues (i’ve managed to get issues with WinAPI and terminal output using both of them), so if you’re an absolute beginner, stick to MinGW-w64 for a while.

For Linux:

Usually, you should have GCC in your repository. On Ubuntu, Debian and similar distributions (Mint, Kubuntu, Lubuntu, PopOS!, Zorin, and so on), you have build-essential package with most tools needed to build C/C++ programs.

On Arch Linux and similar distributions (Manjaro), you have base-devel package.

On other distributions, search for similar package or install latest gcc and g++ packages from your repository.

Test it the same way as on Windows — open terminal and try gcc —version , see what happens.

You also have to install gdb (GCC debugger) separately, as it may not come with the base development packages, and you definitely do want to have it and use it.

For MacOS: probably same thing as on Linux, look for GCC (or any other preferred toolchain) in package manager and install it from there. Verify the installation the same way as on Linux.

VSCode Essential Plugins⌗

If you already have working C/C++ toolchain, time to run VSCode and install some plugins. Run VSCode and go to the Extensions menu.

Now, for some general C++ plugins:

  • C/C++ — that’s the core extension we’ll need. It contains the fundamental stuff to work with C/C++ in VSCode.
  • Better C++ Syntax — it’s always nice to have better syntax colouring, so i strongly recommend that one. You might want to use one of the themes from this extension description to get full experience.
  • C/C++ Snippets — pretty useful extension that adds automatic generation of snippets in C/C++ code — instead of writing loops, structures and class definitions by hand, you can generate them with autocompletion support.
  • C++ Intellisense — pretty good plugin with some intelligent autocompletion features.
  • C++ Helper — simple extension which adds automatic function definition generation feature.
  • C-mantic — very useful plugin that adds auto-generation of function definitions, getters, setters and more. An alternative to C++ Helper — pick whatever seems more ergonomic for you.

And i’d also recommend these:

  • Bracket Pair Colorizer 2 — very useful extension which colorize the matching bracket pairs, increasing code clarity. Strongly recommended.
  • GitLens — if you want to work with Git repositories, that’s the extension you’re looking for. You need git installed to use it!
  • Material Icon Theme — better looking than default ones

With these plugins, you will have a pretty decent bare-bones environment to work with C and C++. You’ll have autocompletion, some refactoring features, some code generation and a pretty decent syntax highlighting. The screenshot below is outdated — use the list above for updated recommended plugins

I have one more plugin to show you, an alternative language server with many useful features, but i’ll leave it as a bonus at the end of this guide, because it needs a bit more configuration. Make sure to check it out!

Creating a project — VSCode and CMake⌗

We’ll start with something simple. As i’ve mentioned before, i’m not gonna teach you how to make a raw VSCode project, which builds the app from scratch and without any other tools, because that’s simply painful, not really scalable, and not worth the trouble.

 

Instead, i’m gonna teach you how to use a build system.

But what’s a build system?⌗

Well, build system is a tool that tells the toolchain (compiler and his friends) how to create a program out of all the source (and resource) files you’ve created. And sometimes does other things, but that’s out of this tutorial scope.

Without it, you’d have to enter the toolchain commands manually each time you’d want to build the application. That’s fine for small apps with one, two or maybe five files. But it gets messy when your program starts to grow.

So, for example, assuming you use gcc , to build your C program manually, you’d have to enter something like this:

gcc [list of your source files] [some fancy flags for your compiler] [maybe some flags telling the compiler where the libraries are] -o program.exe

An actual example would be:

gcc main.c lib.c lib2.c -O2 -Wall -Wextra -L./some/lib -lmylib -lsomeotherlib -o program.exe

That doesn’t look so bad, right? You could even put this command in some shell script and easily run it every time you’d like to build the code. But then, you’d have to change this command every time your project structure changes — so, every time you add a new file, or library, or change some directory name, you gotta edit this script. And yes, i know that wildcards exist, but for the sake of this example i’m gonna ignore them.

Another issue is that if you’d want to give this code to your friend or teacher, he would either have to use the same shell as you, and gcc , or write his own build script (or project) for the compiler/shell he’s using, and that’s not very user-friendly (or, rather, programmer-friendly) solution.

There are also some other issues with manual building, but the point is: manual building is not comfortable or scalable on a larger scale. So, we’ll use a build system to do it for us and make everyone’s life easier!

Bonus note: Tool i’m going to talk about next — CMake — isn’t technically a build system. It’s a meta-build system. The difference between those is that build system runs the toolchain commands directly, while meta-build system generates the build system files. Basically, meta-build systems are more flexible, and sometimes easier to use, therefore we’re gonna use one.

Bonus note number two: originally, i was going to show how to use Premake and CMake, but due to some pretty bad issues with Premake i’ve decided to stay with CMake. I’ll probably make a Premake guide in the future.

Okay, how do i use it?⌗

Well, let’s start with installation. You can either install it from your package manager, just like VSCode, or download from official site. Make sure to add CMake to your PATH variable if you’re using an official installer!.

Important note: if you’re using your package manager, check the CMake version after installation ( cmake —version command). I’m gonna use some stuff that was added in CMake 3.12, but from what i can see, some older Linux distributions (like Ubuntu 18.04) still have CMake 3.10 in their repositories, so if that’s the case i strongly recommend installing newer version manually. If that’s not possible, i’ll tell what things come from CMake 3.12 and how to make a workaround.

Done? Great. Now a little bit of theory.

How does CMake work?⌗

CMake is a meta-build system. As i’ve mentioned earlier, it means that when we run it, it should give us a project for a build system of our choice, which we can use to build our application. To tell CMake how it should generate the project, a CMakeLists.txt file is used. This file includes the project configuration, written in CMake’s scripting language.

Some toolchains — like GCC, MinGW or Visual C++ — come with their own build systems. In case of GCC/MinGW, it’s GNU Make. In case of Visual C++, it’s MSBuild. CMake can generate the necessary files for these build systems, and then we can use them to build the whole project with a single command. Pretty convenient.

Creating a simple project⌗

Let’s open VSCode (or restart, if you had it opened while installing CMake) and add some extensions.

These two plugins will enable CMakeLists.txt syntax highlighting and CMake integration for VSCode. And this integration is a very powerful and helpful tool, as we’ll see in a bit. You can also install a cmake-format extension, if you have Python installed and follow the plugin’s installation guide

Now, make a folder for our new project and create a simple main.cpp (or main.c , if you want to code in C):

You can check if your toolchain works correctly by building the app manually. If you’re using GCC or MinGW, open up integrated VSCode terminal with Ctrl+` command (or Ctrl+Shift+` to create a new one), and run:

C++: g++ main.cpp -o main

C: gcc main.c -o main

And then run the app with ./main command. You should see your Hello World printed in terminal.

If that doesn’t work, make sure you have correctly added your toolchain to PATH variable.

Now, we can proceed with CMake. Delete the compiled program main you just created and tested, and create a CMakeLists.txt file in the same directory as your code file. We’ll start with bare-bones template and then we’ll expand it a little.

Put this code into CMakeLists.txt :

And then open up the VSCode command list with Ctrl+Shift+P shortcut, and look for CMake: Configure option. Run it.

Next, you should see a list of detected toolchains installed in your system. Pick one.

After that, VSCode will run CMake and configure the project for the first time. You should see similar output in your VSCode output window:

From now on, VSCode will automatically run CMake every time you change CMakeLists.txt to re-generate the project files. You should also see a new menu on left-side toolbar

Building your program⌗

So, we have a project now. How do we build it, and how do we run our program?

Thankfully, CMake plugin for VSCode got us covered. To build the program, either use F7 shortcut, look for the CMake: Build command in command list, or press the Build button either on VSCode bottom bar, or in CMake menu.

You should see similar output in VSCode output window:

Running your program⌗

Now, let’s run it. Press the Run button on the bottom VSCode bar:

And the app should run without any issues. The output should be in terminal window.

Is that it?⌗

Of course not — there’s always more!

But yeah, we just created a very simple project with CMake + VSCode, built it and ran it. Now, let’s talk what actually happened and how can we expand our project.

CMake 101 — how does it work?⌗

CMake, as i’ve mentioned multiple times, is a tool that generates the project files used to build it. However, it can also be used for some other things — like application packaging, managing tests, configuring the project, and so on. At the moment CMake is an industry standard, which means that most of the C and C++ projects have CMake support, therefore it’s a very versatile tool. Not the best, but versatile.

You may notice that after configuring the project a new directory appeared in your project folder, called build . Let’s peek into it.

You are usually not supposed to touch and modify these files, as CMake manages them, but i’ll still explain the function of some of the more important ones:

  • CMakeCache.txt — inside that file, you can find a list of CMake variables that are used in project generation process. You can find the toolchain paths, compiler flags, user and many different configuration variables there.
  • compile_commands.json — that file contains a list of commands used to build your program. This list can be used by some code analyzing tools (and i’ll describe one at the end of this guide).
  • HelloWorld.exe — hey, that’s our program!
  • Makefile — this file is used by GNU Make to build our program. Basically, that’s the final CMake output. If you’re using a different toochain with different build system, like Visual C++, you will get a different file (usually, a whole Visual Studio solution, so maybe even a whole directory).

CMakeLists — what’s inside?⌗

Let’s analyze our CMakeLists.txt

  • cmake_minimum_required defines the minimal version of CMake required to generate this project. We’ll use 3.12 because i’m gonna show you some stuff that was added in this version.
  • project defines our project. We can also add information about version, project description, homepage and used languages — which we do in that case.
  • add_executable tells CMake to generate a code that will build an executable file with specified name from specified source files. $ is a CMake variable containing the project name defined by project command.

It’s important that add_executable requires a full list of all the source files making up the program. So, in theory, you would have to add every single source file to the list manually, like that: add_executable($ main.cpp a.cpp b.cpp [. ]) , but fortunately that’s not necessary. We can use file command to generate that list for us.

Expanding our project — adding more files⌗

Let’s add some more files for our project. First, create two new directories — include and src in root project directory:

Now, move the main.cpp (or main.c ) to src directory, and make a new file called lib.cpp (or lib.c ) there. Put this code inside:

Then, add a lib.hpp (or lib.h ) file inside include directory. Put this inside:

The project should look like this now:

Let’s update the CMakeLists.txt .

We’ll use two new commands now: file and include_directories . file command will generate the list of source files, while include_directories will tell our toolchain where to look for header files.

  • file(GLOB PROJECT_SOURCE_FILES CONFIGURE_DEPENDS src/*.cpp) — this command generates the list of files from src dir with .cpp extension, and stores it in PROJECT_SOURCE_FILES variable. The CONFIGURE_DEPENDS flag was added in CMake 3.12, and thanks to it, the list of files will be automatically re-generated every time we add a new file to the project. The command will work without it, but then you would have to manually regenerate CMake project after adding new files.
  • include_directories tells the toolchain where to look for header files.

The PROJECT_SOURCE_FILES variable should have a list of all of our code files, and we’ll pass it to add_executable instead of adding a new file manually. Of course, this variable can be called anyhow you want — it’s not a special name or anything.

Now, let’s configure our project again (VSCode should do this automatically, but i wanna show you how to do it in case it doesn’t). Right-click on CMakeLists.txt and select “Configure All Projects”

Sometimes, when something goes wrong and CMake or VSCode starts behaving strange or getting buggy, it’s good to clean up and reconfigure the project (“Clean Reconfigure All Projects” and “Clean Rebuild All Projects”). This can sometimes happen when playing with CMakeLists.

Let’s add some code to our main.cpp (or main.c ) to test if additional files are added properly to our project:

Now, we should be able to build our program

At this point, everything should work automatically. You should be able to add new source files to src dir, and new headers to include , and CMake should handle them without having to touch CMakeLists.txt manually. Adding new directories with source/include files is done the same way — just file the source files, add include path with include_directories and voila.

Debugging our code⌗

Time for a last step in our setup — using a debugger. Fortunately, CMake integration does most of the work for us here.

Let’s add a breakpoint in the first line of our main function — click on the left of line number, you should see a red dot:

And start a debugging session by pressing a little bug icon on the bottom of VSCode window, or by using CMake: Debug command

VSCode should now switch into debugging perspective and program should stop at breakpoint.

And that’s basically it. Don’t worry about lack of configuration for run/debug in VSCode — CMake integration does everything for us, so there’s no need to make them. Just make sure you run/debug the program via CMake commands in VSCode, instead of it’s own. Setting up the run/debug configs manually can be pretty annoying at the times, so that’s a subject for another guide.

There’s one subject i haven’t touched yet, and it’s adding external libraries. Since this guide is already long enough, i’ll make another one for that. Now, it’s the time for some bonus content.

Bonus: clangd setup⌗

clangd is a language server for C++. It provides functionalities like code completion, code linting (showing warning and errors in real-time), simple refactoring, and so on. There is a C++ language server in VSCode already, as we installed C/C++ extension, but clangd is better in some ways, and it’s more multi-platform (default VSCode C++ language server doesn’t work on ARM yet, so if you wanna code on RaspberryPi via SSH — clangd is your best friend).

In order to work, clangd requires compile_commands.json file to know how your code is compiled and with what flags. Fortunately for us, CMake generates that file automatically, so no further configuration is required on our side!

Right after the plugin installation, you should see a popup like this one:

In order for clangd to work, you have to disable the default Intellisense server (press Disable IntelliSense ), and download clangd binary (which VSCode does for us). After it’s downloaded, you should see this popup:

Reload the window, open up a C/C++ source file, and check if clangd info is displayed on the bottom of the screen

If that’s the case, congratulations, it should work now. Check if there’s no include errors, and if the autocompletion works (you can manually trigger autocompletion with Ctrl+Space shortcut). There should also be a .cache directory in your project folder now, with clangd ’s cache files — make sure to add it to .gitignore before making a commit 😛

Full list of clangd features can be found here: https://clangd.llvm.org/features.html. I strongly recommend checking it out.

Clang-Format setup⌗

clangd embeds clang-format support, which is a code formatting tool — one of the best in C and C++ environment. clang-format allows you to manually or automatically format the code (for example, on-save, format-while-typing is not yet supported with clangd ) according to your preferences, which you can set by creating .clang-format file in your workspace root, with configuration options for clang-format .

The list of configuration options is pretty long and can be found here: https://clang.llvm.org/docs/ClangFormatStyleOptions.html. I’m not gonna describe them all of course, i’ll just show an setup example.

Let’s create a .clang-format file in our workspace root dir, and put this inside:

If clangd is the only formatter you have installed, it should be treated as default. If not, make sure it is by opening command list ( Ctrl+Shift+P ), looking for Format Document With. option, and setting default formatter to clangd .

Now, open a main file and either right-click and pick Format document option, or use a shortcut ( Shift+Alt+F on Windows by default). The code should now look like this:

If it had been formatted differently, check the clangd output in VSCode window. All the issues and errors with .clang-format file should be there.

You can set autoformatting in VSCode settings — open settings window with Ctrl+, or File -> Preferences -> Settings , and look for format on options

Summary⌗

And that would be it. I hope it’s not too long.

If there are any issues or questions about the guide itself or the setup process, feel free to contact me!

С/С++ на Linux в Visual Studio Code для начинающих

Давайте начистоту, мало кто использует отладчик GDB на Linux в консольном варианте. Но что, если добавить в него красивый интерфейс? Под катом вы найдёте пошаговую инструкцию отладки кода С/С++ на Linux в Visual Studio Code.

Передаю слово автору.

Относительно недавно я переехал на Linux. Разрабатывать на Windows, конечно, удобнее и приятнее, но и здесь я нашел эффективный способ легко и быстро отлаживать код на С/С++, не прибегая к таким методам как «printf-стайл отладки» и так далее.

Итак приступим. Писать в sublime (или gedit/kate/emacs ), а запускать в терминале — так себе решение, ошибку при работе с динамическим распределением памяти вряд ли найдёшь с первого раза. А если проект трудоёмкий? У меня есть более удобное решение. Да и ещё поддержка Git в редакторе, одни плюсы.

Сегодня мы поговорим про Visual Studio Code.

Установка

Ubuntu/Debian

  1. Качаем версию пакета VS Code с расширением .deb
  2. Переходим в папку, куда скачался пакет (cd

/Загрузки или cd

Расширения для С/С++

Чтобы VS Code полностью сопровождал нас при работе с файлами С/С++, нужно установить расширение «cpptools». Также полезным будет поставить один из наборов сниппетов.

Настоятельно рекомендую включить автосохранение редактируемых файлов, это поможет нам в дальнейшем.

Идём дальше. Открываем любую папку (новую или нет, неважно).

У меня в этой папке уже есть пара файлов для работы с C/C++. Вы можете скопировать одну из своих наработок сюда или создать новый файл.

Осталось всего ничего. Настроить компиляцию в одну клавишу и научиться отлаживать без printf .

Шаг 1. Открываем файл .c/.cpp, который (обязательно) лежит в вашей папке.

Шаг 2. Нажимаем Ctrl+Shift+B. VS Code вам мягко намекнет, что он не знает как собирать ваш проект.


Шаг 3. Поэтому дальше настраиваем задачу сборки: выбираем «Настроить задачу сборки» -> «Others».

Шаг 4. Прописываем конфигурацию в соответствии с образцом. По сути мы пишем скрипт для консоли, так что всем кто имел дело с ней будет понятно дальнейшее. Прошу заметить, что для сборки исходников в системе должен стоять сам компилятор (gcc или другой, отличаться будет только значение поля command ). Поэтому для компиляции .cpp, понадобится в поле command указать g++ или c++ , а для .c gcc .

Шаг 5. В args прописываем аргументы, которые будут переданы на вход вашему компилятору. Напоминаю, что порядок должен быть примерно таким: -g, <имя файла> .

Внимание: Если в вашей программе используется несколько файлов с исходным кодом, то укажите их в разных аргументах через запятую. Также обязательным является ключ -g (а лучше даже -g3 ). Иначе вы не сможете отладить программу.

Если в проекте для сборки вы используете makefile , то в поле command введите make , а в качестве аргумента передайте директиву для сборки.


Шаг 6. Далее возвращаемся обратно к нашему исходнику. И нажимаем F5 и выбираем C++.

Шаг 7. Осталось только написать путь к файлу программы. По умолчанию это $/a.out , но я в своем файле сборки указал флаг -o и переименовал файл скомпилированной программы, поэтому у меня путь до программы: $/main .


Шаг 8. Всё, больше нам не нужно ничего для начала использования всех благ VS Code. Переходим к основному проекту.

Отладка

Для начала скомпилируем программу (нет, нет, убери терминал, теперь это делается по нажатию Ctrl+Shift+B).

Как вы видите в проводнике появился main , значит все в порядке и сборка прошла без ошибок. У меня не слишком большая программа, но выполняется она моментально. Одним словом, провал чистой воды, потому что отладка идет в отдельном терминале, который закрывается после того, как программа дошла в main() до «return 0;» .


Пришло время для брейкпоинтов. Выберем строчку с «return 0;» и нажимаем F9.


Строчка, помеченная красной точкой слева — место, где остановится программа, при выполнении.

Далее нажимаем F5.

Как я и сказал, программа остановила выполнение. Обратите внимание на окно с локальными переменными.

Удобненько. Также при остановке можно наводить мышкой на переменные и структуры в коде и смотреть их значения.


Также, если на каком-то этапе выполнения вам нужно посмотреть пошаговое выполнение той или иной операции, например в цикле, то поставьте брейкпоинт перед ней и нажмите F10 для выполнения текущей строчки без захода в подпрограмму и F11 с заходом.

Также есть случаи, когда считать выражение очень муторно вручную, но для отладки вам нужно знать, например, значение суммы трех элементов массива, или значение большого логического выражения. Для этого существуют контрольные значения. Все это и многое другое могут показать вам Контрольные значения (или «watch»).

  1. Для каждой папки вам нужно отдельно настроить файлы сборки и путь к программе.
  2. VS Code не решит ваших проблем, но поможет быстрее с ними разобраться. Причем в разы.
  3. После каждого изменения программы, ее нужно компилировать заново, нажимая Ctrl+Shift+B.

Об авторе


Максимилиан Спиридонов — разработчик C#, студент МАИ, Microsoft Student Partner. В профессиональную разработку на .NET пришёл ещё в школе. Около года работал с реальными проектами на WPF(MVVM)+C#, MySQL, более 4-х лет разрабатывал на C#. Основная сфера интересов сейчас — это мобильная разработка на Xamarin. Также, по воле случая в сфере интересов оказались С/С++ и Linux.

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *