Windows compile c program files x86

Содержание
  1. Walkthrough: Compiling a Native C++ Program on the Command Line
  2. Prerequisites
  3. Open a developer command prompt
  4. Create a Visual C++ source file and compile it on the command line
  5. Next steps
  6. Использование набора инструментов Microsoft C++ из командной строки Use the Microsoft C++ toolset from the command line
  7. Скачивание и установка инструментов Download and install the tools
  8. Практическое руководство. Использование программ командной строки How to use the command-line tools
  9. Ярлыки командной строки разработчика Developer command prompt shortcuts
  10. Открытие окна «Командная строка разработчика» To open a developer command prompt window
  11. Расположение командных файлов разработчика Developer command file locations
  12. Использование средств разработчика в существующем окне командной строки Use the developer tools in an existing command window
  13. Синтаксис vcvarsall vcvarsall syntax
  14. Настройка среды сборки в существующем окне командной строки To set up the build environment in an existing command prompt window
  15. Создание собственных ярлыков командной строки Create your own command prompt shortcut
  16. Средства командной строки Command-line tools
  17. Средства управления проектами из командной строки Command-line project management tools
  18. Содержание раздела In this section
  19. Связанные разделы Related sections

Walkthrough: Compiling a Native C++ Program on the Command Line

Visual Studio includes a command-line C and C++ compiler. You can use it to create everything from basic console apps to Universal Windows Platform apps, Desktop apps, device drivers, and .NET components.

In this walkthrough, you create a basic, «Hello, World»-style C++ program by using a text editor, and then compile it on the command line. If you’d like to try the Visual Studio IDE instead of using the command line, see Walkthrough: Working with Projects and Solutions (C++) or Using the Visual Studio IDE for C++ Desktop Development.

In this walkthrough, you can use your own C++ program instead of typing the one that’s shown. Or, you can use a C++ code sample from another help article.

Prerequisites

To complete this walkthrough, you must have installed either Visual Studio and the optional Desktop development with C++ workload, or the command-line Build Tools for Visual Studio.

Visual Studio is an integrated development environment (IDE). It supports a full-featured editor, resource managers, debuggers, and compilers for many languages and platforms. Versions available include the free Visual Studio Community edition, and all can support C and C++ development. For information on how to download and install Visual Studio, see Install C++ support in Visual Studio.

The Build Tools for Visual Studio installs only the command-line compilers, tools, and libraries you need to build C and C++ programs. It’s perfect for build labs or classroom exercises and installs relatively quickly. To install only the command-line tools, look for Build Tools for Visual Studio on the Visual Studio Downloads page.

Before you can build a C or C++ program on the command line, verify that the tools are installed, and you can access them from the command line. Visual C++ has complex requirements for the command-line environment to find the tools, headers, and libraries it uses. You can’t use Visual C++ in a plain command prompt window without doing some preparation. Fortunately, Visual C++ installs shortcuts for you to launch a developer command prompt that has the environment set up for command line builds. Unfortunately, the names of the developer command prompt shortcuts and where they’re located are different in almost every version of Visual C++ and on different versions of Windows. Your first walkthrough task is finding the right one to use.

A developer command prompt shortcut automatically sets the correct paths for the compiler and tools, and for any required headers and libraries. You must set these environment values yourself if you use a regular Command Prompt window. For more information, see Set the Path and Environment Variables for Command-Line Builds. We recommend you use a developer command prompt shortcut instead of building your own.

Open a developer command prompt

If you have installed Visual Studio 2017 or later on Windows 10, open the Start menu and choose All apps. Scroll down and open the Visual Studio folder (not the Visual Studio application). Choose Developer Command Prompt for VS to open the command prompt window.

If you have installed Microsoft Visual C++ Build Tools 2015 on Windows 10, open the Start menu and choose All apps. Scroll down and open the Visual C++ Build Tools folder. Choose Visual C++ 2015 x86 Native Tools Command Prompt to open the command prompt window.

You can also use the Windows search function to search for «developer command prompt» and choose one that matches your installed version of Visual Studio. Use the shortcut to open the command prompt window.

Next, verify that the Visual C++ developer command prompt is set up correctly. In the command prompt window, enter cl and verify that the output looks something like this:

There may be differences in the current directory or version numbers. These values depend on the version of Visual C++ and any updates installed. If the above output is similar to what you see, then you’re ready to build C or C++ programs at the command line.

If you get an error such as «‘cl’ is not recognized as an internal or external command, operable program or batch file,» error C1034, or error LNK1104 when you run the cl command, then either you are not using a developer command prompt, or something is wrong with your installation of Visual C++. You must fix this issue before you can continue.

If you can’t find the developer command prompt shortcut, or if you get an error message when you enter cl , then your Visual C++ installation may have a problem. Try reinstalling the Visual C++ component in Visual Studio, or reinstall the Microsoft Visual C++ Build Tools. Don’t go on to the next section until the cl command works. For more information about installing and troubleshooting Visual C++, see Install Visual Studio.

Depending on the version of Windows on the computer and the system security configuration, you might have to right-click to open the shortcut menu for the developer command prompt shortcut and then choose Run as administrator to successfully build and run the program that you create by following this walkthrough.

Create a Visual C++ source file and compile it on the command line

In the developer command prompt window, enter md c:\hello to create a directory, and then enter cd c:\hello to change to that directory. This directory is where both your source file and the compiled program get created.

Enter notepad hello.cpp in the command prompt window.

Choose Yes when Notepad prompts you to create a new file. This step opens a blank Notepad window, ready for you to enter your code in a file named hello.cpp.

In Notepad, enter the following lines of code:

This code is a simple program that will write one line of text on the screen and then exit. To minimize errors, copy this code and paste it into Notepad.

Save your work! In Notepad, on the File menu, choose Save.

Congratulations, you’ve created a C++ source file, hello.cpp, that is ready to compile.

Switch back to the developer command prompt window. Enter dir at the command prompt to list the contents of the c:\hello directory. You should see the source file hello.cpp in the directory listing, which looks something like:

The dates and other details will differ on your computer.

If you don’t see your source code file, hello.cpp , make sure the current working directory in your command prompt is the C:\hello directory you created. Also make sure that this is the directory where you saved your source file. And make sure that you saved the source code with a .cpp file name extension, not a .txt extension. Your source file gets saved in the current directory as a .cpp file automatically if you open Notepad at the command prompt by using the notepad hello.cpp command. Notepad’s behavior is different if you open it another way: By default, Notepad appends a .txt extension to new files when you save them. It also defaults to saving files in your Documents directory. To save your file with a .cpp extension in Notepad, choose File > Save As. In the Save As dialog, navigate to your C:\hello folder in the directory tree view control. Then use the Save as type dropdown control to select All Files (*.*). Enter hello.cpp in the File name edit control, and then choose Save to save the file.

At the developer command prompt, enter cl /EHsc hello.cpp to compile your program.

The cl.exe compiler generates an .obj file that contains the compiled code, and then runs the linker to create an executable program named hello.exe. This name appears in the lines of output information that the compiler displays. The output of the compiler should look something like:

If you get an error such as «‘cl’ is not recognized as an internal or external command, operable program or batch file,» error C1034, or error LNK1104, your developer command prompt is not set up correctly. For information on how to fix this issue, go back to the Open a developer command prompt section.

If you get a different compiler or linker error or warning, review your source code to correct any errors, then save it and run the compiler again. For information about specific errors, use the search box to look for the error number.

To run the hello.exe program, at the command prompt, enter hello .

The program displays this text and exits:

Congratulations, you’ve compiled and run a C++ program by using the command-line tools.

Next steps

This «Hello, World» example is about as simple as a C++ program can get. Real world programs usually have header files, more source files, and link to libraries.

You can use the steps in this walkthrough to build your own C++ code instead of typing the sample code shown. These steps also let you build many C++ code sample programs that you find elsewhere. You can put your source code and build your apps in any writeable directory. By default, the Visual Studio IDE creates projects in your user folder, in a source\repos subfolder. Older versions may put projects in a *Documents\Visual Studio \Projects folder.

To compile a program that has additional source code files, enter them all on the command line, like:

cl /EHsc file1.cpp file2.cpp file3.cpp

The /EHsc command-line option instructs the compiler to enable standard C++ exception handling behavior. Without it, thrown exceptions can result in undestroyed objects and resource leaks. For more information, see /EH (Exception Handling Model).

When you supply additional source files, the compiler uses the first input file to create the program name. In this case, it outputs a program called file1.exe. To change the name to program1.exe, add an /out linker option:

cl /EHsc file1.cpp file2.cpp file3.cpp /link /out:program1.exe

And to catch more programming mistakes automatically, we recommend you compile by using either the /W3 or /W4 warning level option:

cl /W4 /EHsc file1.cpp file2.cpp file3.cpp /link /out:program1.exe

The compiler, cl.exe, has many more options. You can apply them to build, optimize, debug, and analyze your code. For a quick list, enter cl /? at the developer command prompt. You can also compile and link separately and apply linker options in more complex build scenarios. For more information on compiler and linker options and usage, see C/C++ Building Reference.

You can use NMAKE and makefiles, MSBuild and project files, or CMake, to configure and build more complex projects on the command line. For more information on using these tools, see NMAKE Reference, MSBuild, and CMake projects in Visual Studio.

Читайте также:  Retail лицензия windows 10 pro

The C and C++ languages are similar, but not the same. The MSVC compiler uses a simple rule to determine which language to use when it compiles your code. By default, the MSVC compiler treats files that end in .c as C source code, and files that end in .cpp as C++ source code. To force the compiler to treat all files as C++ independent of file name extension, use the /TP compiler option.

The MSVC compiler includes a C Runtime Library (CRT) that conforms to the ISO C99 standard, with minor exceptions. Portable code generally compiles and runs as expected. Certain obsolete library functions, and several POSIX function names, are deprecated by the MSVC compiler. The functions are supported, but the preferred names have changed. For more information, see Security Features in the CRT and Compiler Warning (level 3) C4996.

Использование набора инструментов Microsoft C++ из командной строки Use the Microsoft C++ toolset from the command line

Вы можете выполнять сборку приложений на языках C и C++ из командной строки с помощью средств, включенных в Visual Studio. You can build C and C++ applications on the command line by using tools that are included in Visual Studio. Набор инструментов компилятора Microsoft C++ (MSVC) также можно скачать как отдельный пакет. The Microsoft C++ (MSVC) compiler toolset is also downloadable as a standalone package. Вам не нужно устанавливать интегрированную среду разработки Visual Studio, если она вам не нужна. You don’t need to install the Visual Studio IDE if you don’t plan to use it.

В этой статье описывается, как настроить среду для использования отдельных компиляторов, компоновщиков, библиотекарей и другие основные средства. This article is about how to set up an environment to use the individual compilers, linkers, librarian, and other basic tools. Собственная система сборки проекта MSBuild не использует среду, как описано в этой статье. The native project build system, MSBuild, does not use the environment as described in this article. Дополнительные сведения об использовании средства MSBuild из командной строки см. в справочнике по использованию MSBuild в командной строке для C++. For more information on how to use MSBuild from the command line, see MSBuild on the command line — C++.

Скачивание и установка инструментов Download and install the tools

Если вы установили Visual Studio и рабочую нагрузку C++, у вас есть все программы командной строки. If you’ve installed Visual Studio and a C++ workload, you have all the command-line tools. Сведения об установке C++ и Visual Studio см. здесь. For information on how to install C++ and Visual Studio, see Install C++ support in Visual Studio. Если требуется только набор инструментов командной строки, скачайте Средства сборки для Visual Studio. If you only want the command-line toolset, download the Build Tools for Visual Studio. При запуске скачанного исполняемого файла будет обновлен и запущен Visual Studio Installer. When you run the downloaded executable, it updates and runs the Visual Studio Installer. Чтобы установить только необходимые средства разработки C++, выберите рабочую нагрузку Средства сборки C++ . To install only the tools you need for C++ development, select the C++ build tools workload. В разделе Сведения об установке можно выбрать дополнительные библиотеки и наборы инструментов, чтобы добавить их. You can select optional libraries and toolsets to include under Installation details. Чтобы создавать код с помощью наборов инструментов Visual Studio 2015 или 2017, выберите дополнительные средства сборки MSVC версии 140 или 141. To build code by using the Visual Studio 2015 or 2017 toolsets, select the optional MSVC v140 or MSVC v141 build tools. После проверки выбранных параметров щелкните Установить. When you’re satisfied with your selections, choose Install.

Практическое руководство. Использование программ командной строки How to use the command-line tools

Когда вы выбираете одну из рабочих нагрузок C++ в Visual Studio Installer, он устанавливает набор инструментов платформы Visual Studio. When you choose one of the C++ workloads in the Visual Studio Installer, it installs the Visual Studio platform toolset. Набор инструментов платформы содержит все средства C и C++ для конкретной версии Visual Studio. A platform toolset has all the C and C++ tools for a specific Visual Studio version. К этим средствам относятся компиляторы C/C++, компоновщики, ассемблеры, другие средства сборки и соответствующие библиотеки. The tools include the C/C++ compilers, linkers, assemblers, and other build tools, and matching libraries. Все эти средства можно использовать в командной строке. You can use all of these tools at the command line. Они также используются внутри интегрированной среды разработки Visual Studio. They’re also used internally by the Visual Studio IDE. Существуют отдельные компиляторы для архитектур x86 и x64 и средства для сборки кода для целевых платформ x86, x 64, ARM и ARM64. There are separate x86-hosted and x64-hosted compilers and tools to build code for x86, x64, ARM, and ARM64 targets. Каждый набор средств для конкретного узла и целевой архитектуры сборки хранится в собственном каталоге. Each set of tools for a particular host and target build architecture is stored in its own directory.

Для правильной работы инструментам требуется несколько переменных среды. To work correctly, the tools require several specific environment variables to be set. Они используются для добавления средств к пути и задания файла включения, файла библиотеки и расположений пакетов SDK. These variables are used to add the tools to the path, and to set include file, library file, and SDK locations. Чтобы упростить процесс задания этих переменных среды, программа установки создает настраиваемые командные файлы , или пакетные файлы, во время установки. To make it easy to set these environment variables, the installer creates customized command files , or batch files, during installation. Вы можете выполнить один из этих командных файлов, чтобы задать конкретный узел и целевую архитектуру сборки, версию Windows SDK и набор инструментов платформы. You can run one of these command files to set a specific host and target build architecture, Windows SDK version, and platform toolset. Для удобства установщик также создает ярлыки в меню «Пуск». For convenience, the installer also creates shortcuts in your Start menu. Ярлыки запускают окна командной строки разработчика, используя эти командные файлы для конкретных сочетаний узла и целевого объекта. The shortcuts start developer command prompt windows by using these command files for specific combinations of host and target. Эти ярлыки гарантируют, что все необходимые переменные среды установлены и готовы к использованию. These shortcuts ensure all the required environment variables are set and ready to use.

Необходимые переменные среды зависят от установки и выбранной архитектуры сборки. The required environment variables are specific to your installation and to the build architecture you choose. Они также могут изменяться при обновлении продукта. They also might be changed by product updates or upgrades. Поэтому рекомендуется использовать ярлык установленной командной строки или командный файл вместо самостоятельной настройки переменных среды. That’s why we recommend you use an installed command prompt shortcut or command file, instead of setting the environment variables yourself. Дополнительные сведения см. в статье Установка переменных пути и среды при сборке из командной строки. For more information, see Set the path and environment variables for command-line builds.

Устанавливаемые наборы инструментов, командные файлы и ярлыки зависят от процессора компьютера и параметров, выбранных во время установки. The toolsets, command files, and shortcuts installed depend on your computer processor and the options you selected during installation. Всегда устанавливаются средства, размещаемые на платформе x86, и кросс-компиляции x86 и x64 для сборки кода. The x86-hosted tools and cross tools that build x86 and x64 code are always installed. Если у вас 64-разрядная версия Windows, будут также установлены средства, размещаемые на платформе x64, и кросс-компиляции x86 и x64 для сборки кода. If you have 64-bit Windows, the x64-hosted tools and cross tools that build x86 and x64 code are also installed. Если выбрать необязательные средства универсальной платформы Windows для C++, также устанавливаются средства для платформ x86 и x64, которые собирают код ARM и ARM64. If you choose the optional C++ Universal Windows Platform tools, then the x86 and x64 tools that build ARM and ARM64 code also get installed. Другие рабочие нагрузки могут устанавливать дополнительные средства. Other workloads may install additional tools.

Ярлыки командной строки разработчика Developer command prompt shortcuts

Ярлыки командной строки устанавливаются в папке конкретной версии Visual Studio в меню «Пуск». The command prompt shortcuts are installed in a version-specific Visual Studio folder in your Start menu. Ниже приведен список основных ярлыков командной строки и архитектуры сборки, которые они поддерживают: Here’s a list of the base command prompt shortcuts and the build architectures they support:

  • Командная строка разработчика — указывает среде использовать 32-разрядные собственные инструменты x86 для сборки 32-разрядного машинного кода x86. Developer Command Prompt — Sets the environment to use 32-bit, x86-native tools to build 32-bit, x86-native code.
  • Командная строка Native Tools x86 — указывает среде использовать 32-разрядные собственные инструменты x86 для сборки 32-разрядного машинного кода x86. x86 Native Tools Command Prompt — Sets the environment to use 32-bit, x86-native tools to build 32-bit, x86-native code.
  • Командная строка Native Tools x64 — указывает среде использовать 64-разрядные собственные инструменты x64 для сборки 64-разрядного машинного кода x64. x64 Native Tools Command Prompt — Sets the environment to use 64-bit, x64-native tools to build 64-bit, x64-native code.
  • Командная строка Cross Tools x86_x64 — указывает среде использовать 32-разрядные собственные инструменты x86 для сборки 64-разрядного машинного кода x64. x86_x64 Cross Tools Command Prompt — Sets the environment to use 32-bit, x86-native tools to build 64-bit, x64-native code.
  • Командная строка Cross Tools x64_x86 — указывает среде использовать 64-разрядные собственные инструменты x64 для сборки 32-разрядного машинного кода x86. x64_x86 Cross Tools Command Prompt — Sets the environment to use 64-bit, x64-native tools to build 32-bit, x86-native code.

Имена ярлыков и папок в меню «Пуск» зависят от установленной версии Visual Studio. The Start menu folder and shortcut names vary depending on the installed version of Visual Studio. Они также зависят от Псевдонима установки, если вы его задали. If you set one, they also depend on the installation Nickname. Например, предположим, что вы установили Visual Studio 2019 и присвоили ей псевдоним Последняя версия. For example, suppose you installed Visual Studio 2019, and you gave it a nickname of Latest. Ярлык командной строки разработчика будет называться Командная строка разработчика для VS 2019 (последняя версия) в папке с именем Visual Studio 2019. The developer command prompt shortcut is named Developer Command Prompt for VS 2019 (Latest) , in a folder named Visual Studio 2019.

Имена ярлыков и папок в меню «Пуск» зависят от установленной версии Visual Studio. The Start menu folder and shortcut names vary depending on the installed version of Visual Studio. Они также зависят от Псевдонима установки, если вы его задали. If you set one, they also depend on the installation Nickname. Например, предположим, что вы установили Visual Studio 2017 и присвоили ей псевдоним Последняя версия. For example, suppose you installed Visual Studio 2017, and you gave it a nickname of Latest. Ярлык командной строки разработчика называется Командная строка разработчика для VS 2017 (последняя версия) в папке с именем Visual Studio 2017. The developer command prompt shortcut is named Developer Command Prompt for VS 2017 (Latest) , in a folder named Visual Studio 2017.

Имена ярлыков и папок в меню «Пуск» зависят от установленной версии Visual Studio. The Start menu folder and shortcut names vary depending on the installed version of Visual Studio. Например, предположим, что вы установили Visual Studio 2015. For example, suppose you installed Visual Studio 2015. Ярлык командной строки разработчика называется Командная строка разработчика для VS 2015. The developer command prompt shortcut is named Developer Command Prompt for VS 2015.

Открытие окна «Командная строка разработчика» To open a developer command prompt window

На рабочем столе откройте меню Пуск Windows, прокрутите вниз, чтобы найти и открыть папку вашей версии Visual Studio, например Visual Studio 2019. On the desktop, open the Windows Start menu, and then scroll to find and open the folder for your version of Visual Studio, for example, Visual Studio 2019.

Читайте также:  Windows 10 wifi слабо ловит

В папке выберите ярлык Командная строка разработчика для вашей версии Visual Studio. In the folder, choose the Developer Command Prompt for your version of Visual Studio. Этот ярлык запускает окно командной строки разработчика, которое использует архитектуру сборки по умолчанию: 32-разрядные собственные инструменты x86 для сборки 32-разрядного машинного кода x86. This shortcut starts a developer command prompt window that uses the default build architecture of 32-bit, x86-native tools to build 32-bit, x86-native code. Если вы предпочитаете архитектуру сборки не по умолчанию, выберите одну из собственных командных строк или командную строку инструментов кросс-компиляции, чтобы указать узел и целевую архитектуру. If you prefer a non-default build architecture, choose one of the native or cross tools command prompts to specify the host and target architecture.

Более быстрый способ открыть командную строку разработчика — ввести запрос командная строка разработчика в поле поиска на рабочем столе. For an even faster way to open a developer command prompt, enter developer command prompt in the desktop search box. Затем выберите нужный результат. Then choose the result you want.

Расположение командных файлов разработчика Developer command file locations

Если вам необходимо установить среду сборки в открытом окне командной строки, можно использовать один из командных файлов, созданных установщиком. If you prefer to set the build environment in an existing command prompt window, you can use one of the command files created by the installer. Рекомендуем задавать среду в новом окне командной строки. We recommend you set the environment in a new command prompt window. Не рекомендуется менять среды позднее в том же окне командной строки. We don’t recommend you later switch environments in the same command window.

Расположение командного файла зависит от установленной версии Visual Studio и расположения, выбранного во время установки. The command file location depends on the version of Visual Studio you installed, and on choices you made during installation. Visual Studio 2019 обычно устанавливается в 64-разрядной системе в папке \Program Files (x86)\Microsoft Visual Studio\2019\выпуск. For Visual Studio 2019, the typical installation location on a 64-bit system is in \Program Files (x86)\Microsoft Visual Studio\2019\edition. Выпуском может быть Community, Professional, Enterprise, Build Tools или другой введенный псевдоним. Edition may be Community, Professional, Enterprise, BuildTools, or another nickname you supplied.

Расположение командного файла зависит от установленной версии Visual Studio и расположения, выбранного во время установки. The command file location depends on the version of Visual Studio you installed, and on choices you made during installation. Visual Studio 2017 обычно устанавливается в 64-разрядной системе в папке \Program Files (x86)\Microsoft Visual Studio\2017\выпуск. For Visual Studio 2017, the typical installation location on a 64-bit system is in \Program Files (x86)\Microsoft Visual Studio\2017\edition. Выпуском может быть Community, Professional, Enterprise, Build Tools или другой введенный псевдоним. Edition may be Community, Professional, Enterprise, BuildTools, or another nickname you supplied.

Расположение командного файла зависит от версии Visual Studio и каталога установки. The command file location depends on the Visual Studio version, and the installation directory. Visual Studio 2015 обычно устанавливается в папке \Program Files (x86)\Microsoft Visual Studio 14.0. For Visual Studio 2015, the typical installation location is in \Program Files (x86)\Microsoft Visual Studio 14.0.

Основной командный файл командной строки разработчика VsDevCmd.bat находится в подкаталоге Common7\Tools. The primary developer command prompt command file, VsDevCmd.bat, is located in the Common7\Tools subdirectory. Если параметры не указаны, он указывает среде использовать собственные инструменты x86 для создания 32-разрядного кода x86. When no parameters are specified, it sets the environment to use the x86-native tools to build 32-bit x86 code.

Для настройки конкретных архитектур сборки доступны дополнительные командные файлы. More command files are available to set up specific build architectures. Доступные командные файлы зависят от установленных рабочих нагрузок и параметров Visual Studio. The command files available depend on the Visual Studio workloads and options you’ve installed. Для Visual Studio 2017 и Visual Studio 2019 они будут находиться в подкаталоге VC\Auxiliary\Build. In Visual Studio 2017 and Visual Studio 2019, you’ll find them in the VC\Auxiliary\Build subdirectory.

Для настройки конкретных архитектур сборки доступны дополнительные командные файлы. More command files are available to set up specific build architectures. Доступные командные файлы зависят от установленных рабочих нагрузок и параметров Visual Studio. The command files available depend on the Visual Studio workloads and options you’ve installed. В Visual Studio 2015 они находятся в подкаталогах VC, VC\bin или VC\bin\архитектура , где архитектура — собственный вариант или кросс-компилятор. In Visual Studio 2015, they’re located in the VC, VC\bin, or VC\bin\architecture subdirectories, where architecture is one of the native or cross-compiler options.

Эти командные файлы устанавливают параметры по умолчанию и вызывают VsDevCmd.bat, чтобы настроить указанную среду архитектуры сборки. These command files set default parameters and call VsDevCmd.bat to set up the specified build architecture environment. Обычная установка может включать следующие командные файлы: A typical installation may include these command files:

Командный файл Command File Узел и целевые архитектуры Host and Target architectures
vcvars32.bat vcvars32.bat Использует 32-разрядные собственные инструменты x86 для сборки 32-разрядного машинного кода x86. Use the 32-bit x86-native tools to build 32-bit x86 code.
vcvars64.bat vcvars64.bat Использует 64-разрядные собственные инструменты x64 для сборки 64-разрядного кода x64. Use the 64-bit x64-native tools to build 64-bit x64 code.
vcvarsx86_amd64.bat vcvarsx86_amd64.bat Использует 32-разрядные собственные инструменты кросс-компиляции x86 для сборки 64-разрядного кода x64. Use the 32-bit x86-native cross tools to build 64-bit x64 code.
vcvarsamd64_x86.bat vcvarsamd64_x86.bat Использует 64-разрядные собственные инструменты кросс-компиляции x64 для сборки 32-разрядного кода x86. Use the 64-bit x64-native cross tools to build 32-bit x86 code.
vcvarsx86_arm.bat vcvarsx86_arm.bat Использует 32-разрядные собственные инструменты кросс-компиляции x86 для сборки кода ARM. Use the 32-bit x86-native cross tools to build ARM code.
vcvarsamd64_arm.bat vcvarsamd64_arm.bat Использует 64-разрядные собственные инструменты кросс-компиляции x64 для сборки кода ARM. Use the 64-bit x64-native cross tools to build ARM code.
vcvarsall.bat vcvarsall.bat Использует параметры для указания узла и целевой архитектуры, пакета Windows SDK и платформы. Use parameters to specify the host and target architectures, Windows SDK, and platform choices. Список поддерживаемых вариантов можно вызвать параметром /help. For a list of supported options, call by using a /help parameter.

Файл vcvarsall.bat и другие командные файлы Visual Studio могут различаться на разных компьютерах. The vcvarsall.bat file and other Visual Studio command files can vary from computer to computer. Не заменяйте отсутствующий или поврежденный файл vcvarsall.bat файлом с другого компьютера. Do not replace a missing or damaged vcvarsall.bat file by using a file from another computer. Перезапустите Visual Studio Installer, чтобы заменить отсутствующий файл. Rerun the Visual Studio installer to replace the missing file.

Файл vcvarsall.bat также может иметь отличия в разных версиях. The vcvarsall.bat file also varies from version to version. Если текущая версия Visual Studio установлена на компьютере, на котором также имеется более ранняя версия Visual Studio, не запускайте файл vcvarsall.bat или другой командный файл других версий в том же окне командной строки. If the current version of Visual Studio is installed on a computer that also has an earlier version of Visual Studio, do not run vcvarsall.bat or another Visual Studio command file from different versions in the same command prompt window.

Использование средств разработчика в существующем окне командной строки Use the developer tools in an existing command window

Самый простой способ указать конкретную архитектуру сборки в существующем окне команд — использовать файл vcvarsall.bat. The simplest way to specify a particular build architecture in an existing command window is to use the vcvarsall.bat file. Используйте файл vcvarsall.bat, чтобы задать переменные среды для настройки командной строки для собственной 32- или 64-разрядной компиляции. Use vcvarsall.bat to set environment variables to configure the command line for native 32-bit or 64-bit compilation. Аргументы позволяют указать кросс-компиляцию для процессоров x86, x64, ARM или ARM64. Arguments let you specify cross-compilation to x86, x64, ARM, or ARM64 processors. Вы можете указать в качестве целевой платформы Microsoft Store, универсальную платформу Windows или платформу классических приложений Windows. You can target Microsoft Store, Universal Windows Platform, or Windows Desktop platforms. Можно даже указать, какой пакет Windows SDK использовать, и выбрать версию набора инструментов платформы. You can even specify which Windows SDK to use, and select the platform toolset version.

Если аргументы не используются, файл vcvarsall.bat настраивает переменные среды для использования текущего собственного компилятора x86 для 32-разрядных целевых классических приложений Windows. When used with no arguments, vcvarsall.bat configures the environment variables to use the current x86-native compiler for 32-bit Windows Desktop targets. Можно добавить аргументы, чтобы настроить среду для использования собственных инструментов или инструментов кросс-компиляции. You can add arguments to configure the environment to use any of the native or cross compiler tools. Файл vcvarsall.bat выводит сообщение об ошибке, если указанная конфигурация не установлена или недоступна на компьютере. vcvarsall.bat displays an error message if you specify a configuration that’s not installed, or not available on your computer.

Синтаксис vcvarsall vcvarsall syntax

vcvarsall.bat [ architecture ] [ platform_type ] [ winsdk_version ] [ -vcvars_ver= vcversion ] vcvarsall.bat [ architecture ] [ platform_type ] [ winsdk_version ] [ -vcvars_ver=vcversion ]

architecture architecture
Этот необязательный аргумент указывает узел и целевую архитектуру для использования. This optional argument specifies the host and target architecture to use. Если параметр architecture не указан, используется среда сборки по умолчанию. If architecture isn’t specified, the default build environment is used. Поддерживаются следующие аргументы: These arguments are supported:

architecture architecture Компилятор Compiler Архитектура главного компьютера Host computer architecture Архитектура выходных данных сборки (целевая) Build output (target) architecture
x86 x86 собственный 32-разрядный x86 x86 32-bit native x86, x64 x86, x64 x86 x86
x86_amd64 или x86_x64 x86_amd64 or x86_x64 x64 для x86 (кросс-компилятор) x64 on x86 cross x86, x64 x86, x64 x64 x64
x86_arm x86_arm ARM для x86 (кросс-компилятор) ARM on x86 cross x86, x64 x86, x64 ARM ARM
x86_arm64 x86_arm64 ARM64 для x86 (кросс-компилятор) ARM64 on x86 cross x86, x64 x86, x64 ARM64 ARM64
amd64 или x64 amd64 or x64 Собственный 64-разрядный x64 x64 64-bit native X64 x64 x64 x64
amd64_x86 или x64_x86 amd64_x86 or x64_x86 x86 для x64 (кросс-компилятор) x86 on x64 cross X64 x64 x86 x86
amd64_arm или x64_arm amd64_arm or x64_arm ARM для x64 (кросс-компилятор) ARM on x64 cross X64 x64 ARM ARM
amd64_arm64 или x64_arm64 amd64_arm64 or x64_arm64 ARM64 для x64 (кросс-компилятор) ARM64 on x64 cross X64 x64 ARM64 ARM64

platform_type platform_type
Этот необязательный аргумент позволяет указать store или uwp в качестве типа платформы. This optional argument allows you to specify store or uwp as the platform type. По умолчанию среда настроена на сборку классических или консольных приложений. By default, the environment is set to build desktop or console apps.

winsdk_version winsdk_version
При необходимости указывает версию Windows SDK для использования. Optionally specifies the version of the Windows SDK to use. По умолчанию используется последняя установленная версия Windows SDK. By default, the latest installed Windows SDK is used. Чтобы указать версию Windows SDK, можно использовать полный номер пакета Windows 10 SDK, например 10.0.10240.0 , или указать 8.1 , чтобы использовать Windows 8.1 SDK. To specify the Windows SDK version, you can use a full Windows 10 SDK number such as 10.0.10240.0 , or specify 8.1 to use the Windows 8.1 SDK.

vcversion vcversion
При необходимости указывает набор инструментов компилятора Visual Studio для использования. Optionally specifies the Visual Studio compiler toolset to use. По умолчанию среда должна использовать текущий набор инструментов компилятора Visual Studio. By default, the environment is set to use the current Visual Studio compiler toolset.

Используйте -vcvars_ver=14.2x.yyyyy , чтобы указать конкретную версию набора инструментов компилятора Visual Studio 2019. Use -vcvars_ver=14.2x.yyyyy to specify a specific version of the Visual Studio 2019 compiler toolset.

Используйте -vcvars_ver=14.16 , чтобы указать последнюю версию набора инструментов компилятора Visual Studio 2017. Use -vcvars_ver=14.16 to specify the latest version of the Visual Studio 2017 compiler toolset.

Используйте -vcvars_ver=14.16 , чтобы указать последнюю версию набора инструментов компилятора Visual Studio 2017. Use -vcvars_ver=14.16 to specify the latest version of the Visual Studio 2017 compiler toolset.

Используйте -vcvars_ver=14.1x.yyyyy , чтобы указать конкретную версию набора инструментов компилятора Visual Studio 2017. Use -vcvars_ver=14.1x.yyyyy to specify a specific version of the Visual Studio 2017 compiler toolset.

Используйте -vcvars_ver=14.0 , чтобы указать набор инструментов компилятора Visual Studio 2015. Use -vcvars_ver=14.0 to specify the Visual Studio 2015 compiler toolset.

Настройка среды сборки в существующем окне командной строки To set up the build environment in an existing command prompt window

В командной строке выполните команду CD, чтобы перейти на каталог установки Visual Studio. At the command prompt, use the CD command to change to the Visual Studio installation directory. Затем снова используйте CD, чтобы перейти в подкаталог, который содержит зависящие от конфигурации командные файлы. Then, use CD again to change to the subdirectory that contains the configuration-specific command files. Для Visual Studio 2019 и Visual Studio 2017 используется подкаталог VC\Auxiliary\Build. For Visual Studio 2019 and Visual Studio 2017, use the VC\Auxiliary\Build subdirectory. Для Visual Studio 2015 используйте подкаталог VC. For Visual Studio 2015, use the VC subdirectory.

Введите команду для вашей среды разработки. Enter the command for your preferred developer environment. Например, для сборки кода ARM для универсальной платформы Windows на 64-разрядной платформе с последней версией Windows SDK и набором инструментов компилятора Visual Studio используйте эту командную строку: For example, to build ARM code for UWP on a 64-bit platform, using the latest Windows SDK and Visual Studio compiler toolset, use this command line:

vcvarsall.bat amd64_arm uwp

Создание собственных ярлыков командной строки Create your own command prompt shortcut

Откройте диалоговое окно свойств для ярлыка командной строки разработчика, чтобы увидеть использованный целевой объект команды. Open the Properties dialog for a developer command prompt shortcut to see the command target used. Например, целевой объект для ярлыка командной строки Native Tools x64 для VS 2019 выглядит примерно следующим образом: For example, the target for the x64 Native Tools Command Prompt for VS 2019 shortcut is something similar to:

%comspec% /k «C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat»

Откройте диалоговое окно свойств для ярлыка командной строки разработчика, чтобы увидеть использованный целевой объект команды. Open the Properties dialog for a developer command prompt shortcut to see the command target used. Например, целевой объект для ярлыка командной строки Native Tools x64 для VS 2017 выглядит примерно следующим образом: For example, the target for the x64 Native Tools Command Prompt for VS 2017 shortcut is something similar to:

%comspec% /k «C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat»

Откройте диалоговое окно свойств для ярлыка командной строки разработчика, чтобы увидеть использованный целевой объект команды. Open the Properties dialog for a developer command prompt shortcut to see the command target used. Например, целевой объект для ярлыка командной строки Native Tools x64 для VS 2015 выглядит примерно следующим образом: For example, the target for the VS2015 x64 Native Tools Command Prompt shortcut is something similar to:

%comspec% /k «C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat» amd64

Пакетные файлы конкретной архитектуры задают параметр architecture и вызывают vcvarsall.bat. The architecture-specific batch files set the architecture parameter and call vcvarsall.bat. Вы можете передать те же параметры в эти пакетные файлы, как вы бы передали их в файл vcvarsall.bat, или можно просто вызвать vcvarsall.bat напрямую. You can pass the same options to these batch files as you would pass to vcvarsall.bat, or you can just call vcvarsall.bat directly. Чтобы задать параметры для ярлыка своей командной строки, добавьте их в конец команды в двойных кавычках. To specify parameters for your own command shortcut, add them to the end of the command in double-quotes. Например, вот ярлык для сборки кода ARM для универсальной платформы Windows на 64-разрядной платформе с последней версией Windows SDK. For example, here’s a shortcut to build ARM code for UWP on a 64-bit platform, using the latest Windows SDK. Чтобы использовать более раннюю версию набора инструментов компилятора, укажите номер версии. To use an earlier compiler toolset, specify the version number. Используйте подобный целевой объект команды в ярлыке: Use something like this command target in your shortcut:

%comspec% /k «C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat» amd64_arm uwp -vcvars_ver=14.16

%comspec% /k «C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat» amd64_arm uwp -vcvars_ver=14.0

%comspec% /k «C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat» amd64 -vcvars_ver=12.0

Измените путь, чтобы указать каталог установки Visual Studio. Adjust the path to reflect your Visual Studio installation directory. Файл vcvarsall.bat содержит дополнительную информацию об определенных номерах версии. The vcvarsall.bat file has additional information about specific version numbers.

Средства командной строки Command-line tools

Для сборки проекта C/C++ из командной строки Visual Studio предоставляет следующие программы командной строки: To build a C/C++ project at a command prompt, Visual Studio provides these command-line tools:

CL CL
Используйте компилятор (cl.exe) для компиляции и компоновки файлов исходного кода в приложения, библиотеки и DLL. Use the compiler (cl.exe) to compile and link source code files into apps, libraries, and DLLs.

Ссылка Link
Используйте компоновщик (link.exe) для компоновки скомпилированных объектных файлов и библиотек в приложения и DLL. Use the linker (link.exe) to link compiled object files and libraries into apps and DLLs.

NMAKE NMAKE
Используйте NMAKE (nmake.exe) в Windows для создания проектов C++ на основе традиционного файла makefile. Use NMAKE (nmake.exe) on Windows to build C++ projects based on a traditional makefile.

При сборке в командной строке команда F1 для получения мгновенной справки недоступна. When you build on the command line, the F1 command isn’t available for instant help. Вместо этого используйте поисковую систему для получения сведений о предупреждениях, ошибках и сообщениях. Instead, you can use a search engine to get information about warnings, errors, and messages. Также можно скачать и применить автономные файлы справки. You can also download and use the offline help files. Чтобы использовать функцию поиска в docs.microsoft.com, введите строку поиска в поле поиска в верхней части любой статьи. To use the search in docs.microsoft.com, enter your query in the search box at the top of any article.

Средства управления проектами из командной строки Command-line project management tools

В интегрированной среде разработки Visual Studio используется собственная система сборки проектов на основе MSBuild. The Visual Studio IDE uses a native project build system based on MSBuild. Вы можете вызвать MSBuild напрямую или использовать собственную систему сборки проектов без интегрированной среды разработки: You can invoke MSBuild directly, or use the native project system without using the IDE:

MSBuild MSBuild
Используйте MSBuild (msbuild.exe) и файл проекта (VCXPROJ) для настройки сборки и косвенного вызова набора инструментов. Use MSBuild (msbuild.exe) and a project file (.vcxproj) to configure a build and invoke the toolset indirectly. Это аналогично выполнению команд Собрать проект или Собрать решение в интегрированной среде разработки Visual Studio. It’s equivalent to running the Build project or Build Solution command in the Visual Studio IDE. Запуск MSBuild из командной строки является усложненным сценарием и обычно не рекомендуется. Running MSBuild from the command line is an advanced scenario and not commonly recommended. Начиная с Visual Studio версии 16.5, MSBuild не использует среду командной строки для управления набором инструментов и используемыми библиотеками. Starting in Visual Studio version 16.5, MSBuild doesn’t use the command-line environment to control the toolset and libraries used.

DEVENV DEVENV
Используйте DEVENV (devenv.exe) вместе с параметром командной строки, например /Build или /Clean , для выполнения определенных команд сборки без отображения интегрированной среды разработки Visual Studio. Use DEVENV (devenv.exe) combined with a command-line switch such as /Build or /Clean to execute certain build commands without displaying the Visual Studio IDE. В целом это удобнее, чем использовать MSBuild напрямую, так как вы можете позволить Visual Studio обрабатывать сложные аспекты MSBuild. In general, DEVENV is preferred over using MSBuild directly, because you can let Visual Studio handle the complexities of MSBuild. Начиная с Visual Studio версии 16.5, DEVENV не использует среду командной строки для управления набором инструментов и используемыми библиотеками. Starting in Visual Studio version 16.5, DEVENV does not use the command-line environment to control the toolset and libraries used.

Содержание раздела In this section

В этих статьях показано, как создавать приложения в командной строке, а также описано, как настроить среду сборки из командной строки. These articles show how to build apps on the command line, and describe how to customize the command-line build environment. В некоторых из них показано, как использовать 64-разрядные наборы инструментов и целевые платформы x86, x64, ARM и ARM64. Some show how to use 64-bit toolsets, and target x86, x64, ARM, and ARM64 platforms. Они также описывают использование средств сборки из командной строки MSBuild и NMAKE. They also describe use of the command-line build tools MSBuild and NMAKE.

Пошаговое руководство: компиляция собственной программы на языке C++ из командной строки Walkthrough: Compiling a native C++ program on the command line
Содержит пример создания и компиляции программы на языке C++ из командной строки. Gives an example that shows how to create and compile a C++ program on the command line.

Пошаговое руководство: Компиляция программы на языке C из командной строки Walkthrough: Compile a C program on the command line
Описывается компиляция программы, написанной на языке программирования C. Describes how to compile a program written in the C programming language.

Пошаговое руководство: компиляция программы на языке C++/CLI из командной строки Walkthrough: Compiling a C++/CLI program on the command line
Описывается создание и компиляция программы C++/CLI, в которой используется платформа .NET Framework. Describes how to create and compile a C++/CLI program that uses the .NET Framework.

Пошаговое руководство: компиляция программы на языке C++/CX из командной строки Walkthrough: Compiling a C++/CX program on the command line
Описывается создание и компиляция программы C++/CX, в которой используется среда выполнения Windows. Describes how to create and compile a C++/CX program that uses the Windows Runtime.

Установка переменных пути и среды при сборке из командной строки Set the path and environment variables for command-line builds
Настройка переменных среды для использования 32- или 64-разрядного набора инструментов для целевых платформ x86, x64, ARM и ARM64. How to set environment variables to use a 32-bit or 64-bit toolset to target x86, x64, ARM, and ARM64 platforms.

NMAKE reference (Справочник по NMAKE) NMAKE reference
Содержит ссылки на статьи, в которых описывается служебная программа обслуживания программ Майкрософт (NMAKE.EXE). Provides links to articles that describe the Microsoft Program Maintenance Utility (NMAKE.EXE).

MSBuild в командной строке — C++ MSBuild on the command line — C++
Содержит ссылки на статьи, в которых рассматривается использование программы msbuild.exe из командной строки. Provides links to articles that discuss how to use msbuild.exe from the command line.

/MD, /MT, /LD (использование библиотеки времени выполнения) /MD, /MT, /LD (Use run-time library)
Описывается использование этих параметров компилятора для работы с библиотекой времени выполнения отладки или выпуска. Describes how to use these compiler options to use a Debug or Release run-time library.

Параметры компилятора C/C++ C/C++ compiler options
Содержит ссылки на статьи, посвященные параметрам компилятора C и C++, а также программе CL.exe. Provides links to articles that discuss the C and C++ compiler options and CL.exe.

Параметры компоновщика MSVC MSVC linker options
Содержит ссылки на статьи, посвященные параметрам компоновщика и программе LINK.exe. Provides links to articles that discuss the linker options and LINK.exe.

Дополнительные средства сборки MSVC Additional MSVC build tools
Содержит ссылки на средства сборки C/C++, включенные в состав Visual Studio. Provides links to the C/C++ build tools that are included in Visual Studio.

Читайте также:  Windows server 2012 нет интерфейса
Оцените статью