Передача аргументов командной строки
Здравствуйте! Только начинаю изучать С++ и ещё не освоилась в Visual Studio. Хочу программе передать аргументы (строку, например), как это сделать в Visual Studio?
![]()

Спасибо всем:) ответ на мой вопрос на рисунке.
- Выбрав проект в Обозревателе решения, в меню Проект выберите команду Свойства.
- Перейдите на вкладку Отладка.
- В поле Аргументы командной строки введите аргументы командной строки, которые будут использоваться.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Как задать аргументы командной строки в visual studio
Visual Studio Code has a powerful command-line interface built-in that lets you control how you launch the editor. You can open files, install extensions, change the display language, and output diagnostics through command-line options (switches).

If you are looking for how to run command-line tools inside VS Code, see the Integrated Terminal.
Command line help
To get an overview of the VS Code command-line interface, open a terminal or command prompt and type code —help . You will see the version, usage example, and list of command line options.

Launching from command line
You can launch VS Code from the command line to quickly open a file, folder, or project. Typically, you open VS Code within the context of a folder. To do this, from an open terminal or command prompt, navigate to your project folder and type code . :

Note: Users on macOS must first run a command (Shell Command: Install ‘code’ command in PATH) to add VS Code executable to the PATH environment variable. Read the macOS setup guide for help.
Windows and Linux installations should add the VS Code binaries location to your system path. If this isn’t the case, you can manually add the location to the Path environment variable ( $PATH on Linux). For example, on Windows, VS Code is installed under AppData\Local\Programs\Microsoft VS Code\bin . To review platform-specific setup instructions, see Setup.
Insiders: If you are using the VS Code Insiders preview, you launch your Insiders build with code-insiders .
Core CLI options
Here are optional arguments you can use when starting VS Code at the command line via code :
| Argument | Description |
|---|---|
| -h or —help | Print usage |
| -v or —version | Print VS Code version (for example, 1.22.2), GitHub commit ID, and architecture (for example, x64). |
| -n or —new-window | Opens a new session of VS Code instead of restoring the previous session (default). |
| -r or —reuse-window | Forces opening a file or folder in the last active window. |
| -g or —goto | When used with file:line , opens a file at a specific line and optional character position. This argument is provided since some operating systems permit : in a file name. |
| -d or —diff | Open a file difference editor. Requires two file paths as arguments. |
| -w or —wait | Wait for the files to be closed before returning. |
| —locale <locale> | Set the display language (locale) for the VS Code session. (for example, en-US or zh-TW ) |

Opening Files and Folders
Sometimes you will want to open or create a file. If the specified file does not exist, VS Code will create them for you along with any new intermediate folders:
For both files and folders, you can use absolute or relative paths. Relative paths are relative to the current directory of the command prompt where you run code .
If you specify more than one file at the command line, VS Code will open only a single instance.
If you specify more than one folder at the command line, VS Code will create a Multi-root Workspace including each folder.
| Argument | Description |
|---|---|
| file | Name of a file to open. If the file doesn’t exist, it will be created and marked as edited. You can specify multiple files by separating each file name with a space. |
| file:line[:character] | Used with the -g argument. Name of a file to open at the specified line and optional character position. |
| folder | Name of a folder to open. You can specify multiple folders and a new Multi-root Workspace is created. |

Working with extensions
You can install and manage VS Code extensions from the command line.
| Argument | Description |
|---|---|
| —install-extension <ext> | Install an extension. Provide the full extension name publisher.extension as an argument. Use —force argument to avoid prompts. |
| —uninstall-extension <ext> | Uninstall an extension. Provide the full extension name publisher.extension as an argument. |
| —disable-extensions | Disable all installed extensions. Extensions will still be visible in the Disabled section of the Extensions view but they will never be activated. |
| —list-extensions | List the installed extensions. |
| —show-versions | Show versions of installed extensions, when using —list-extensions |
| —enable-proposed-api <ext> | Enables proposed api features for an extension. Provide the full extension name publisher.extension as an argument. |

Advanced CLI options
There are several CLI options that help with reproducing errors and advanced setup.
| Argument | Description |
|---|---|
| —extensions-dir <dir> | Set the root path for extensions. Has no effect in Portable Mode. |
| —user-data-dir <dir> | Specifies the directory that user data is kept in, useful when running as root. Has no effect in Portable Mode. |
| -s, —status | Print process usage and diagnostics information. |
| -p, —performance | Start with the Developer: Startup Performance command enabled. |
| —disable-gpu | Disable GPU hardware acceleration. |
| —verbose | Print verbose output (implies —wait ). |
| —prof-startup | Run CPU profiler during startup. |
| —upload-logs | Uploads logs from current session to a secure endpoint. |
| Multi-root | |
| —add <dir> | Add folder(s) to the last active window for a multi-root workspace. |
Opening VS Code with URLs
You can also open projects and files using the platform’s URL handling mechanism. Use the following URL formats to:
Open a file to line and column
You can use the URL in applications such as browsers or file explorers that can parse and redirect the URL. For example, on Windows, you could pass a vscode:// URL directly to the Windows Explorer or to the command line as start vscode:// .

Note: If you are using VS Code Insiders builds, the URL prefix is vscode-insiders:// .
Next steps
Read on to find out about:
-
— Run command-line tools from inside VS Code. — Learn the basics of the VS Code editor. — VS Code lets you quickly understand and move through your source code.
Common questions
‘code’ is not recognized as an internal or external command
Your OS cannot find the VS Code binary code on its path. The VS Code Windows and Linux installations should have installed VS Code on your path. Try uninstalling and reinstalling VS Code. If code is still not found, consult the platform-specific setup topics for Windows and Linux.
On macOS, you need to manually run the Shell Command: Install ‘code’ command in PATH command (available through the Command Palette ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). Consult the macOS specific setup topic for details.
How do I get access to a command line (terminal) from within VS Code?
VS Code has an Integrated Terminal where you can run command-line tools from within VS Code.
Can I specify the settings location for VS Code in order to have a portable version?
Not directly through the command line, but VS Code has a Portable Mode, which lets you keep settings and data in the same location as your installation, for example, on a USB drive.
11.11 – Аргументы командной строки
Как вы узнали из урока «0.4 – Введение в разработку на C++», при компиляции и компоновке программы на выходе получается исполняемый файл. Когда программа запускается, выполнение начинается с функции main() . До этого момента мы объявляли main следующим образом:
Обратите внимание, что эта версия main() не принимает параметров. Однако для работы со многими программами требуются какие-то входные данные. Например, предположим, что вы пишете программу под названием Thumbnail , которая считывает файл изображения, а затем создает миниатюру (уменьшенную версию этого изображения). Как Thumbnail узнает, какое изображение прочитать и обработать? Пользователь должен каким-то образом указать программе, какой файл открыть. Для этого вы можете использовать следующий подход:
Однако при таком подходе есть потенциальная проблема. Каждый раз, когда программа запускается, она будет ждать, пока пользователь введет данные. Это может не быть проблемой, если вы запускаете эту программу один раз вручную из командной строки. Но это проблематично в других случаях, например, когда вы хотите запустить эту программу для многих файлов или запустить ее другой программой.
Давайте рассмотрим эти случаи подробнее.
Рассмотрим случай, когда вы хотите создать миниатюры для всех файлов изображений в заданном каталоге. Как бы вы это сделали? Вы можете запускать эту программу столько раз, сколько изображений в каталоге, печатая имя каждого файла вручную. Однако если бы изображений были сотни, это могло бы занять целый день! Хорошим решением здесь было бы написать программу, которая перебирает имя каждого файла в каталоге, вызывая Thumbnail один раз для каждого файла.
Теперь рассмотрим случай, когда вы запускаете веб-сайт и хотите, чтобы на вашем сайте создавался эскиз каждый раз, когда пользователь загружает изображение на ваш сайт. Эта программа не настроена для приема входных данных из Интернета, так как же человек, загружающий файл, будет вводить имя файла в этом случае? Хорошим решением здесь было бы, чтобы ваш веб-сервер автоматически вызывал Thumbnail после загрузки.
В обоих этих случаях нам нужен способ, чтобы внешняя программа могла передавать имя файла в качестве входных данных для нашей программы Thumbnail при ее запуске, а не заставлять Thumbnail ждать после запуска, пока пользователь введет имя файла.
Аргументы командной строки – это необязательные строковые аргументы, которые операционная система передает программе при ее запуске. Затем программа может использовать их в качестве входных данных (или игнорировать). Подобно параметрам функции, которые позволяют функции предоставлять входные данные для другой функции, аргументы командной строки позволяют людям или программам предоставлять входные данные программе.
Передача аргументов командной строки
Исполняемые программы можно запускать из командной строки, вызывая их по имени. Например, чтобы запустить исполняемый файл " WordCount ", который находится в корневом каталоге диска C: на компьютере с Windows, вы можете ввести:
Чтобы передать аргументы командной строки в WordCount , мы просто перечисляем их после имени исполняемого файла:
Теперь при выполнении WordCount Myfile.txt будет предоставлен в качестве аргумента командной строки. Программа может иметь несколько аргументов командной строки, разделенных пробелами:
Это также работает и в других операционных системах командной строки, таких как Linux (хотя приглашение и структура каталогов, несомненно, будут отличаться).
Если вы запускаете свою программу из среды IDE, в среде IDE должен быть предусмотрен способ ввода аргументов командной строки.
В Microsoft Visual Studio кликните правой кнопкой мыши на своем проекте в обозревателе решений и выберите «Свойства» (Properties). В открывшемся окне разверните дерево «Свойства конфигурации» (Configuration Properties) и выберите «Отладка» (Debugging). На правой панели есть строка с названием «Аргументы команды» (Command Arguments). Вы можете ввести туда аргументы командной строки для тестирования, и они будут автоматически переданы вашей программе при ее запуске.
Рисунок 1 – Задание аргументов командной строки в Microsoft Visual Studio
В Code::Blocks выберите «Project» (Проект) → «Set program’s arguments» (Установить аргументы программы).
Рисунок 2 – Задание аргументов командной строки в Code::Blocks
Использование аргументов командной строки
Теперь, когда вы знаете, как предоставить программе аргументы командной строки, следующим шагом будет доступ к ним из нашей программы на C++. Для этого мы используем другую форму main() . Эта новая форма main() принимает два аргумента (по соглашению названные argc и argv ) следующим образом:
Иногда вы также можете увидеть и такое:
Несмотря на то, что они обрабатываются одинаково, мы предпочитаем первое представление, потому что его интуитивно легче понять.
argc – это целочисленный параметр, содержащий счетчик числа аргументов, переданных программе ( argc = argument count, число аргументов). argc всегда будет не меньше 1 потому, что первым аргументом всегда является имя самой программы. Каждый аргумент командной строки, предоставляемый пользователем, приведет к увеличению argc на 1.
argv – это место, где хранятся фактические значения аргументов ( argv = argument values, значения аргументов, хотя на самом деле расшифровывается как «argument vectors»). Хотя объявление argv выглядит устрашающе, на самом деле argv представляет собой просто массив строк в стиле C. Длина этого массива – argc .
Давайте напишем короткую программу с именем MyArgs для вывода значений всех параметров командной строки:
Теперь, когда мы вызываем эту программу ( MyArgs ) с аргументами командной строки " Myfile.txt " и " 100 ", вывод будет следующим:
Аргумент 0 – это путь и имя текущей запущенной программы. Аргументы 1 и 2 в данном случае – это два параметра командной строки, которые мы передали.
Работа с числовыми аргументами
Аргументы командной строки всегда передаются в виде строк, даже если предоставленное значение является числовым. Чтобы использовать аргумент командной строки в качестве числа, вы должны преобразовать его из строки в число. К сожалению, C++ делает это немного сложнее, чем должно быть.
В C++ это можно сделать следующим образом:
При запуске с вводом " 567 " эта программа печатает:
std::stringstream работает так же, как std::cin . В этом случае мы инициализируем его значением argv[1] , и поэтому можем использовать operator>> для извлечения значения в целочисленную переменную (так же, как и с std::cin ).
Подробнее о std::stringstream мы поговорим в следующей главе.
Операционная система анализирует аргументы командной строки первой
Когда вы вводите что-то в командной строке (или запускаете свою программу из IDE), операционная система должна преобразовать и направить этот запрос соответствующим образом. Это не только включает в себя запуск исполняемого файла, но также включает анализ любых аргументов, чтобы определить, как они должны обрабатываться и передаваться приложению.
Как правило, в операционных системах действуют особые правила обработки специальных символов, таких как двойные кавычки и обратный слеш.
Обычно строки, переданные в двойных кавычках, считаются частью одной строки:
Если вы хотите включить двойную кавычку в состав строки, вам нужно поставить перед двойной кавычкой обратный слеш:
Заключение
Аргументы командной строки предоставляют пользователям и другим программам отличный способ передать входные данные в программу при запуске. Рассмотрите возможность использования любых входных данных, необходимых для работы программы при запуске, в качестве параметров командной строки. Если они не будут переданы через командную строку, вы всегда можете обнаружить это и попросить пользователя ввести данные. Таким образом, ваша программа сможет работать в любом случае.
Command Line Interface (CLI)
Visual Studio Code has a powerful command-line interface built-in that lets you control how you launch the editor. You can open files, install extensions, change the display language, and output diagnostics through command-line options (switches).

If you are looking for how to run command-line tools inside VS Code, see the Integrated Terminal.
Command line help
To get an overview of the VS Code command-line interface, open a terminal or command prompt and type code —help . You will see the version, usage example, and list of command line options.

Launching from command line
You can launch VS Code from the command line to quickly open a file, folder, or project. Typically, you open VS Code within the context of a folder. To do this, from an open terminal or command prompt, navigate to your project folder and type code . :

Note: Users on macOS must first run a command (Shell Command: Install ‘code’ command in PATH) to add VS Code executable to the PATH environment variable. Read the macOS setup guide for help.
Windows and Linux installations should add the VS Code binaries location to your system path. If this isn’t the case, you can manually add the location to the Path environment variable ( $PATH on Linux). For example, on Windows, VS Code is installed under AppData\Local\Programs\Microsoft VS Code\bin . To review platform-specific setup instructions, see Setup.
Insiders: If you are using the VS Code Insiders preview, you launch your Insiders build with code-insiders .
Core CLI options
Here are optional arguments you can use when starting VS Code at the command line via code :
| Argument | Description |
|---|---|
| -h or —help | Print usage |
| -v or —version | Print VS Code version (for example, 1.22.2), GitHub commit ID, and architecture (for example, x64). |
| -n or —new-window | Opens a new session of VS Code instead of restoring the previous session (default). |
| -r or —reuse-window | Forces opening a file or folder in the last active window. |
| -g or —goto | When used with file:line , opens a file at a specific line and optional character position. This argument is provided since some operating systems permit : in a file name. |
| -d or —diff <file1> <file2> | Open a file difference editor. Requires two file paths as arguments. |
| -m or —merge <path1> <path2> <base> <result> | Perform a three-way merge by providing paths for two modified versions of a file, the common origin of both modified versions, and the output file to save merge results. |
| -w or —wait | Wait for the files to be closed before returning. |
| —locale <locale> | Set the display language (locale) for the VS Code session. (for example, en-US or zh-TW ) |

Opening Files and Folders
Sometimes you will want to open or create a file. If the specified file does not exist, VS Code will create them for you along with any new intermediate folders:
For both files and folders, you can use absolute or relative paths. Relative paths are relative to the current directory of the command prompt where you run code .
If you specify more than one file at the command line, VS Code will open only a single instance.
If you specify more than one folder at the command line, VS Code will create a Multi-root Workspace including each folder.
| Argument | Description |
|---|---|
| file | Name of a file to open. If the file doesn’t exist, it will be created and marked as edited. You can specify multiple files by separating each file name with a space. |
| file:line[:character] | Used with the -g argument. Name of a file to open at the specified line and optional character position. |
| folder | Name of a folder to open. You can specify multiple folders and a new Multi-root Workspace is created. |

Select a profile
You can launch VS Code with a specific profile via the —profile command-line interface option. You pass the name of the profile after the —profile argument and open a folder or a workspace using that profile. The command line below opens the web-sample folder with the "Web Development" profile:
/projects/web-sample —profile "Web Development"
If the profile specified does not exist, a new empty profile with the given name is created.
Working with extensions
You can install and manage VS Code extensions from the command line.
| Argument | Description |
|---|---|
| —install-extension <ext> | Install an extension. Provide the full extension name publisher.extension as an argument. Use —force argument to avoid prompts. |
| —uninstall-extension <ext> | Uninstall an extension. Provide the full extension name publisher.extension as an argument. |
| —disable-extensions | Disable all installed extensions. Extensions will still be visible in the Disabled section of the Extensions view but they will never be activated. |
| —list-extensions | List the installed extensions. |
| —show-versions | Show versions of installed extensions, when using —list-extensions |
| —enable-proposed-api <ext> | Enables proposed api features for an extension. Provide the full extension name publisher.extension as an argument. |

Advanced CLI options
There are several CLI options that help with reproducing errors and advanced setup.
| Argument | Description |
|---|---|
| —extensions-dir <dir> | Set the root path for extensions. Has no effect in Portable Mode. |
| —user-data-dir <dir> | Specifies the directory that user data is kept in, useful when running as root. Has no effect in Portable Mode. |
| -s, —status | Print process usage and diagnostics information. |
| -p, —performance | Start with the Developer: Startup Performance command enabled. |
| —disable-gpu | Disable GPU hardware acceleration. |
| —verbose | Print verbose output (implies —wait ). |
| —prof-startup | Run CPU profiler during startup. |
| —upload-logs | Uploads logs from current session to a secure endpoint. |
| Multi-root | |
| —add <dir> | Add folder(s) to the last active window for a multi-root workspace. |
Create remote tunnel
VS Code integrates with other remote environments to become even more powerful and flexible. Our goal is to provide a cohesive experience that allows you to manage both local and remote machines from one, unified CLI.
The Visual Studio Code Remote — Tunnels extension lets you connect to a remote machine, like a desktop PC or VM, via a secure tunnel. Tunneling securely transmits data from one network to another. You can then securely connect to that machine from anywhere, without the requirement of SSH.
We’ve built functionality into the code CLI that will initiate tunnels on remote machines. You can run:
to create a tunnel on your remote machine. You may connect to this machine through a web or desktop VS Code client.
You can review the other tunneling commands by running code tunnel -help :

As you may need to run the CLI on a remote machine that can’t install VS Code Desktop, the CLI is also available for standalone install on the VS Code download page.
For more information on Remote Tunnels, you can review the Remote Tunnels documentation.
Opening VS Code with URLs
You can also open projects and files using the platform’s URL handling mechanism. Use the following URL formats to:
Open a file to line and column
You can use the URL in applications such as browsers or file explorers that can parse and redirect the URL. For example, on Windows, you could pass a vscode:// URL directly to the Windows Explorer or to the command line as start vscode://

Note: If you are using VS Code Insiders builds, the URL prefix is vscode-insiders:// .
Next steps
Read on to find out about:
-
— Run command-line tools from inside VS Code. — Learn the basics of the VS Code editor. — VS Code lets you quickly understand and move through your source code.
Common questions
‘code’ is not recognized as an internal or external command
Your OS cannot find the VS Code binary code on its path. The VS Code Windows and Linux installations should have installed VS Code on your path. Try uninstalling and reinstalling VS Code. If code is still not found, consult the platform-specific setup topics for Windows and Linux.
On macOS, you need to manually run the Shell Command: Install ‘code’ command in PATH command (available through the Command Palette ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). Consult the macOS specific setup topic for details.
How do I get access to a command line (terminal) from within VS Code?
VS Code has an Integrated Terminal where you can run command-line tools from within VS Code.
Can I specify the settings location for VS Code in order to have a portable version?
Not directly through the command line, but VS Code has a Portable Mode, which lets you keep settings and data in the same location as your installation, for example, on a USB drive.