Visual studio разработка для linux

приступая к работе с Visual Studio Code с подсистема Windows для Linux

Visual Studio Code, вместе с расширением Remote-WSL, позволяет использовать WSL в качестве среды разработки для полной времени непосредственно из VS Code. Вы можете выполнить следующие действия:

  • Разработка в среде под управлением Linux
  • Использование цепочек инструментов и служебных программ для Linux
  • запускайте и отлаживать приложения Linux с помощью Windows и сохраняя доступ к средствам повышения производительности, таким как Outlook и Office
  • использование встроенного терминала VS Code для запуска дистрибутива Linux по выбору
  • воспользуйтесь преимуществами VS Code функций, таких как завершение кода Intellisense, linting, поддержка отладки, фрагменты кодаи модульное тестирование .
  • простота управления версиями с помощью встроенной поддержки Git VS Code
  • выполнение команд и VS Code расширений непосредственно в проектах WSL
  • изменение файлов в Linux или смонтированной Windows файловой системе (например,/мнт/к) без беспокойства о проблемах с путями, двоичной совместимости или других трудностей между операционными системами

установка VS Code и расширения Remote WSL

перейдите на страницу установки VS Code и выберите двоичный установщик 32 или 64. установите Visual Studio Code на Windows (а не в файловую систему WSL).

При появлении запроса на Выбор дополнительных задач во время установки обязательно установите флажок Добавить в путь , чтобы можно было легко открыть папку в WSL с помощью команды Code.

Установите Пакет расширений для удаленной разработки. Этот пакет расширений включает расширение Remote-WSL в дополнение к расширениям Remote-SSH и Remote-Container, что позволяет открывать любую папку в контейнере, на удаленном компьютере или в WSL.

Чтобы установить расширение Remote-WSL, потребуется версия 1,35 или более поздняя VS Code. не рекомендуется использовать WSL в VS Code без расширения Remote-WSL, так как будет потеряна поддержка автоматического завершения, отладки, linting и т. д. Забавный факт. это расширение WSL устанавливается в $HOME/.вскоде/екстенсионс (введите команду ls $HOME\.vscode\extensions\ в PowerShell).

Обновление дистрибутива Linux

в некоторых дистрибутивах WSL Linux отсутствуют библиотеки, необходимые для запуска сервера VS Code. Вы можете добавить дополнительные библиотеки в дистрибутив Linux с помощью диспетчера пакетов.

Например, чтобы обновить Debian или Ubuntu, используйте:

Чтобы добавить wget (для получения содержимого с веб-серверов) и CA-Certificates (чтобы разрешить приложениям на основе SSL проверять подлинность SSL-соединений), введите:

Откройте проект WSL в Visual Studio Code

Из командной строки

Чтобы открыть проект из дистрибутива WSL, откройте командную строку распространения и введите: code .

Из VS Code

кроме того, можно получить доступ к дополнительным VS Code удаленным параметрам с помощью ярлыка: CTRL+SHIFT+P в VS Code, чтобы открыть палитру команд. если затем ввести, Remote-WSL вы увидите список доступных VS Code удаленных параметров, что позволит повторно открыть папку в удаленном сеансе, указать, какое распространение следует открыть в, и многое другое.

расширения в VS Code Remote

расширение Remote-WSL разделяет VS Code в архитектуру «клиент-сервер» с помощью клиента (пользовательского интерфейса), работающего на компьютере Windows, и сервера (код, Git, подключаемые модули и т. д.), запускаемые удаленно.

при запуске VS Code удаленно на вкладке «расширения» отобразится список расширений, разделенных между локальным компьютером и дистрибутивом WSL.

Читайте также:  Что можно запустить как службу windows

Установка локального расширения, например темы, должна быть установлена только один раз.

Некоторые расширения, такие как расширение Python или все, что обрабатывает такие действия, как linting или Отладка, должны устанавливаться отдельно на каждом удаленном распределении WSL. VS Code отобразит значок предупреждения ⚠ , а также зеленую кнопку «установить в WSL», если установлено локальное расширение, которое не установлено на удаленном компьютере WSL.

дополнительные сведения см. в VS Code документах:

при запуске VS Code Remote в WSL сценарии запуска оболочки запускаться не будут. Дополнительные сведения о выполнении дополнительных команд или изменении среды см. в этой статье о сценариях расширенной настройки среды .

возникли проблемы при запуске VS Code из командной строки WSL? В этом руководство по устранению неполадок содержатся советы по изменению переменных пути, устранению ошибок расширения, связанных с отсутствием зависимостей, устранению проблем с завершением строк Git, установке локального VSIX на удаленном компьютере, запуску окна браузера, порту localhost для блокировки, веб-сокеты не работают, ошибки при хранении данных расширения и многое другое.

Установка Git (необязательно)

Если вы планируете работать совместно с другими пользователями или размещать проект на сайте с открытым исходным кодом (например, GitHub), примите во внимание, что VS Code поддерживает управление версиями с помощью Git. Вкладка системы управления версиями в VS Code отслеживает все изменения и содержит общие команды Git (добавление, фиксация, принудительная отправка, извлечение) прямо в пользовательском интерфейсе.

Установка Терминала Windows (необязательно)

новая Терминал Windows включает несколько вкладок (быстро переключаться между дистрибутивами командной строки, PowerShell или несколькими установочными областями Linux), пользовательскими привязками клавиш (создайте собственные сочетания клавиш для открытия и закрытия вкладок, копирования и вставки и т. д.), эмодзи ☺ и пользовательских тем (цветовые схемы, стили и размеры шрифтов, фоновое изображение, размытие и прозрачность). дополнительные сведения см. в Терминал Windows документах.

Скачайте Терминал Windows из Microsoft Store: При установке через магазин обновления выполняются автоматически.

После установки откройте Терминал Windows и щелкните Параметры, чтобы настроить Терминал использовать файл profile.json .

Дополнительные ресурсы

К дополнительным рекомендуемым расширениям относятся следующие:

  • Раскладки клавиатуры других редакторов — эти расширения позволят использовать необходимую раскладку при переходе в другой текстовый редактор (например, Atom, Sublime, Vim, eMacs, Notepad++ и т. п.).
  • Расширение синхронизации параметров — позволяет синхронизировать параметры VS Code в разных установках, используя GitHub. Если вы работаете на разных компьютерах, это обеспечит согласованность среды между ними.
  • Отладчик для Chrome: после завершения разработки на стороне сервера с Linux необходимо разработать и протестировать клиентскую часть. Это расширение интегрирует редактор VS Code со службой отладки браузера Chrome, что увеличивает эффективность выполнения операций.

—>

Источник

Visual C++ for Linux Development

Visual Cpp Dev Labs

Get Started with Visual C++ for Linux Development

Setting up your project for Linux Development

With this extension you can author C++ code for Linux servers, desktops and devices. You can manage your connections to these machines from within VS. VS will automatically copy and remote build your sources and can launch your application with the debugger. Our project system supports targeting specific architectures, including ARM.

Support

You can reach us directly via email at vcpplinux-support@microsoft.com

As of November of 2016 the Extension Gallery does not have a comments section anymore. Please use our support email or our github page to start a discussion and report issues.

This extension is no longer supported in Visual Studio 2015. It can still be installed by won’t be updated further. This extension was integrated into Visual Studio 2017, which can be installed from https://www.visualstudio.com/downloads/. Once installed, you can install Visual C++ for Linux Development by selecting the «Linux development with C++» workload.

Читайте также:  Alcatel oxe install linux

Updates

  • This extension won’t receive further updates in Visual Studio 2015. We integrated all the capabilities of the extension into Visual Studio 2017, where we also made considerable updates, and added major new features. Linux will continue to be a considerable investment for us, with the development focused in Visual Studio 2017. See above for more details. If you have any concerns or questions, you can open an issue for us, to start a discussion, at https://github.com/Microsoft/VSLinux/issues, or you can write us at vcpplinux-support@microsoft.com.
  • Natvis
  • python pretty printing for gdb mode
  • source mapping to debug the right source file when debugging files with the same name
  • child process debugging
  • debug attach, to remote processes (using Attach to Process dialog)
  • ctrl+f5 run without debugging
  • required remote tools dependencies checks, makes sure gdb/gcc etc is installed
  • message reporting usability improvements from compiler/linker
  • fixing a bug with shellexec processes being orphaned and leaked in the system
  • fix a bug with connections being invalidated due to a date time bug
  • fix for a crash occuring sometimes when adding a connection in the Connection Manager
  • fix for a crash when a command timeouts
  • fix for a crash which occurs sometimes when errors occur from the shell when executing commands
  • pass the machine name to command line builds using /pp:RemoteTarget=name
  • Incremental linking
  • Incremental build output logging
  • Bug fix for file path issues when using multiple connections
  • Shared projects support bug fix
  • Updated the data collection policy to opt-out in the installer
  • Debugging error reporting improvements
  • Property Pages for timeout properties
  • Misc simplifications in the Property Pages, removed the Remote page
  • Improved Linux systems identification
  • Improved build cancellation support
  • Options for not copying object files and the build output files locally, from the remote system
  • Overall faster build times
  • Removed dependency block on Update 3
  • Major performance improvements with incremental copy and build, and considerably reducing the number of connections
  • Makefile project support for external build system support (make, CMake etc.)
  • Overridable C/C++ compiler path in Property Pages
  • Remote source copy management per file/project: no copy, and/or override destination path
  • Debug command override, useful for debugging external programs
  • Pre-build and Pre-link remote build events
  • Arbitrary file copy as part of the build events
  • Overridable timeouts through project for command execution, compile, link and archiver:
    • Add elements to project file under to override default value of 30 minutes. Values are: RemoteExecuteTimeout, RemoteCompileCommandTimeout, RemoteLdCommmandTimeout, or RemoteArCommmandTimeout
  • Debugging Property Page support for additional gdb commands for the debugger to run before starting debugging (debugger bootstrap commands)
  • Linux console hang during infinite loops bug fix
  • Default to IPv4 when using hostnames
  • Custom local/remote ports ignored bug fix
  • Linker error parsing updates
  • Fixed ««» escaping issue
  • uname -m machine arch parsing bug fix
  • Remote project directory is set to a system directory bug fix
  • MIEngine bits moved up to Update 3
  • Bug fix for new source files in empty projects
  • Added clean support
  • Fixes bugs in remote target changes not triggering new build required
  • Use first successful connection, instead of last successful, as the default connection
  • General performance improvements
  • Major IntelliSense fixes
  • New experimenal debugging mode, gdb over the shell, which offers greater compatibility
  • Added a console I/O Tool Window for interacting with remote process launched from VS
  • Added support for working directory and command line arguments for the debugged process
  • Added ability to use files outside the project directory
  • UI for system information (OS/architecture) in the Tools – Options
  • C++14 support IntelliSense bug fix
  • Connect to Linux dialog UI bug fixes
  • Linux Connections UI remove connection after add bug fix
  • Fixes an access denied bug when uploading read only files
  • Fixes -x c, -x c++ bug and compiling as C
  • FreeBSD, OSX partial support, including connections, compile and link. Debugging is not supported yet.
  • Performance improvements
  • Removed the dependency on Android NDK and Android MDD bits
  • Intel Edison support and bug fixes
  • Fix for login as root
  • Fixes the ocassional «4444 port in use»
  • Fixes the «no such file» bug
  • Local and remote ports in the Property Pages are not dependent on each other and each can be supplied individually
  • Fixes a bug with removing entries from Linux Connection Manager
  • Resource management (leaked sshd processes) fixes
  • General robustness fixes in the Connect dialog
  • Gdbserver cleanup at the end of debugging
  • Improved build diagnostics and linker errors parsing from build
  • Fix for empty output file name extension, now the output can have no file extension
  • Fixed crash during login
Читайте также:  Alienware on screen display windows 10

Create a Linux Project

After installing the extension to get started create a new project by going to Templates > Visual C++ > Cross Platform > Linux.

Connecting to Linux

Prerequisites

Today we only support building remotely on the Linux target machine. We are not limited by specific Linux distros but we do have dependencies on the presence of some tools. Specifically, we need openssh-server, g++, gdb and gdbserver. Use your favorite package manager to install them, e.g. on Debian based systems: sudo apt-get install openssh-server g++ gdb gdbserver

First connection

The first time you target a Linux machine you will be prompted for connection information. This is triggered by building the project.

Adding and removing connections

To add a new connection, go to Tools > Options and search for Linux. You can also search Linux in the qucik launch box. From here you can add and remove connections.

To change which connection a project is using go to the project properties remote settings and update the target machine.

Project Properties

All of the options necessary to control C++ compilation are exposed on the project properies pages. We’ll cover a few specific to how things work for Linux. First under remote settings, you will see the remote root is set to

/projects/ by default and that we are setting the remote project directory to match our project name in that location.

Looking at the General settings for the project, you can see how our output and intermediate directories are configured. By default a project configured as an application will result in an executable under bin/x64/Debug/ under the project directory location. Notice that for configuration types we also support static and dynamic libraries.

Add additional library dependencies on the Linker > Input property page.

You can pass additional pre launch commands to the debugger to do things like launch graphical apps on the remote linux machine.

You can also send post build events to control remote behavior, as in this example that exports a gpio pin for use without requiring the executable run as super user.

Источник

Оцените статью