- Системы сборки и проекты C/C++ в Visual Studio C/C++ projects and build systems in Visual Studio
- Компиляция C++ C++ compilation
- Набор инструментов MSVC The MSVC toolset
- Системы сборки и проекты Build systems and projects
- Использование MSBuild из командной строки MSBuild from the command line
- В этом разделе In This Section
- C/C++ projects and build systems in Visual Studio
- C++ compilation
- The MSVC toolset
- Build systems and projects
- MSBuild from the command line
- In This Section
Системы сборки и проекты C/C++ в Visual Studio C/C++ projects and build systems in Visual Studio
Visual Studio можно использовать для изменения, компиляции и сборки любой базы кода C++ с полной поддержкой IntelliSense без преобразования этого кода в проект Visual Studio или компиляции с помощью набора инструментов MSVC. You can use Visual Studio to edit, compile, and build any C++ code base with full IntelliSense support without having to convert that code into a Visual Studio project or compile with the MSVC toolset. Например, можно изменить кроссплатформенный проект CMake в Visual Studio на компьютере Windows, а затем скомпилировать его для Linux с помощью g++ на удаленном компьютере Linux. For example, you can edit a cross-platform CMake project in Visual Studio on a Windows machine, then compile it for Linux using g++ on a remote Linux machine.
Компиляция C++ C++ compilation
Сборка программы C++ — это компиляция исходного кода из одного или нескольких файлов и последующее связывание этих файлов в исполняемый файл (EXE), библиотеку динамической загрузки (DLL) или статическую библиотеку (LIB). To build a C++ program means to compile source code from one or more files and then link those files into an executable file (.exe), a dynamic-load library (.dll) or a static library (.lib).
Процесс базовой компиляции C++ состоит из трех основных этапов. Basic C++ compilation involves three main steps:
- Препроцессор C++ преобразует все определения #директив и макросов в каждом исходном файле. The C++ preprocessor transforms all the #directives and macro definitions in each source file. При этом создается единица трансляции . This creates a translation unit .
- Компилятор C++ компилирует каждую единицу трансляции в объектные файлы (OBJ), применяя заданные параметры компилятора. The C++ compiler compiles each translation unit into object files (.obj), applying whatever compiler options have been set.
- Компоновщик объединяет объектные файлы в один исполняемый файл, применяя заданные параметры компоновщика. The linker merges the object files into a single executable, applying the linker options that have been set.
Набор инструментов MSVC The MSVC toolset
В набор инструментов компилятора MSVC (также называемого цепочкой инструментов или средствами сборки) входят компилятор, компоновщик, стандартные библиотеки и связанные служебные программы Microsoft C++. The Microsoft C++ compiler, linker, standard libraries, and related utilities make up the MSVC compiler toolset (also called a toolchain or «build tools»). Они включены в состав в Visual Studio. These are included in Visual Studio. Этот набор инструментов можно скачать со страницы средств сборки для Visual Studio 2019 и использовать в качестве бесплатного автономного пакета. You can also download and use the toolset as a free standalone package from Build Tools for Visual Studio 2019 download.
Вы можете создавать простые программы, вызывая компилятор MSVC (cl.exe) непосредственно из командной строки. You can build simple programs by invoking the MSVC compiler (cl.exe) directly from the command line. Следующая команда принимает один файл исходного кода и вызывает cl.exe для создания исполняемого файла с именем hello.exe : The following command accepts a single source code file, and invokes cl.exe to build an executable called hello.exe :
Здесь компилятор (cl.exe) автоматически вызывает препроцессор и компоновщик C++ для создания окончательного выходного файла. Here the compiler (cl.exe) automatically invokes the C++ preprocessor and the linker to produce the final output file. Дополнительные сведения см. в статье Сборка из командной строки. For more information, see Building on the command line.
Системы сборки и проекты Build systems and projects
Большинство реальных программ используют некую систему сборки для управления сложностями компиляции нескольких исходных файлов для нескольких конфигураций (для отладки и выпуска), нескольких платформ (x86, x64, ARM и т. д.), настраиваемых шагов сборки и даже нескольких исполняемых файлов, которые должны быть скомпилированы в определенном порядке. Most real-world programs use some kind of build system to manage complexities of compiling multiple source files for multiple configurations (debug vs. release), multiple platforms (x86, x64, ARM, and so on), custom build steps, and even multiple executables that must be compiled in a certain order. Вы выполняете настройки в файле конфигурации сборки, а система сборки принимает этот файл в качестве входных данных перед вызовом компилятора. You make settings in a build configuration file(s), and the build system accepts that file as input before it invoke the compiler. Набор файлов исходного кода и файлов конфигурации сборки, необходимых для создания исполняемого файла, называется проектом . The set of source code files and build configuration files needed to build an executable file is called a project .
Далее приведены различные варианты для проектов Visual Studio — C++. The following list shows various options for Visual Studio Projects — C++:
Создайте проект Visual Studio с помощью интегрированной среды разработки Visual Studio и настройте его, используя страницы свойств. create a Visual Studio project by using the Visual Studio IDE and configure it by using property pages. Проекты Visual Studio создают программы, работающие в Windows. Visual Studio projects produce programs that run on Windows. Общие сведения см. в статье Компиляция и сборка в документации по Visual Studio. For an overview, see Compiling and Building in the Visual Studio documentation.
Откройте папку, содержащую файл CMakeLists.txt. open a folder that contains a CMakeLists.txt file. Поддержка CMake интегрирована в Visual Studio. CMake support is integrated into Visual Studio. Интегрированную среду разработки можно использовать для редактирования, тестирования и отладки без изменения файлов CMake. You can use the IDE to edit, test, and debug without modifying the CMake files in any way. При этом вы можете работать в том же проекте CMake, что и другие пользователи, которые могут использовать другие редакторы. This enables you to work in the same CMake project as others who might be using different editors. Поэтому CMake является рекомендуемым вариантом для кроссплатформенной разработки. CMake is the recommended approach for cross-platform development. Дополнительные сведения см. в статье Проекты CMake. For more information, see CMake projects.
Откройте свободную папку исходных файлов, где нет файла проекта. open a loose folder of source files with no project file. Для создания файлов в Visual Studio будет использоваться эвристика. Visual Studio will use heuristics to build the files. Это простой способ компиляции и запуска небольших консольных приложений. This is an easy way to compile and run small console applications. Дополнительные сведения см. в статье Проекты «Открыть папку» для C++. For more information, see Open Folder projects.
Откройте папку, содержащую файл makefile или любой другой файл конфигурации системы сборки. open a folder that contains a makefile, or any other build system configuration file. Вы можете настроить Visual Studio для вызова любых произвольных команд сборки, добавив файлы JSON в папку. You can configure Visual Studio to invoke any arbitrary build commands by adding JSON files to the folder. Дополнительные сведения см. в статье Проекты «Открыть папку» для C++. For more information, see Open Folder projects.
Откройте файл makefile Windows в Visual Studio. Open a Windows makefile in Visual Studio. Дополнительные сведения см. в разделе Справочник по программе NMAKE. For more information, see NMAKE Reference.
Использование MSBuild из командной строки MSBuild from the command line
Вы можете вызвать систему MSBuild из командной строки, передав ей VCXPROJ-файл вместе с параметрами командной строки. You can invoke MSBuild from the command line by passing it a .vcxproj file along with command-line options. Для реализации этого подхода требуется хорошее понимание MSBuild, а использовать его рекомендуется только в случае необходимости. This approach requires a good understanding of MSBuild, and is recommended only when necessary. Дополнительные сведения см. в разделе MSBuild. For more information, see MSBuild.
В этом разделе In This Section
Проекты Visual Studio Visual Studio projects
Создание, настройка и сборка проектов C++ в Visual Studio с помощью собственной системы сборки (MSBuild). How to create, configure, and build C++ projects in Visual Studio using its native build system (MSBuild).
Проекты CMake CMake projects
Создание, сборка и развертывание проектов CMake в Visual Studio. How to code, build, and deploy CMake projects in Visual Studio.
Проекты в виде папок Open Folder projects
Создание, сборка и развертывание проектов C++ в Visual Studio с помощью любой произвольной системы сборки или без нее. How to use Visual Studio to code, build, and deploy C++ projects based on any arbitrary build system, or no build system at all.
Сборки выпуска Release builds
Создание и устранение неполадок оптимизированных сборок выпуска для развертывания в системах конечных пользователей. How to create and troubleshoot optimized release builds for deployment to end users.
Использование набора инструментов MSVC из командной строки Use the MSVC toolset from the command line
Описание использования компилятора C/C++ и средств сборки непосредственно из командной строки, а не с помощью интегрированной среды разработки Visual Studio. Discusses how to use the C/C++ compiler and build tools directly from the command line rather than using the Visual Studio IDE.
Создание библиотек DLL в Visual Studio Building DLLs in Visual Studio
Создание, отладка и развертывание библиотек DLL (общих библиотек) C/C++ в Visual Studio. How to create, debug, and deploy C/C++ DLLs (shared libraries) in Visual Studio.
Создание изолированных приложений и параллельных сборок C/C++ Building C/C++ Isolated Applications and Side-by-side Assemblies
Описывает модель развертывания для классических приложений Windows, основанную на концепции изолированных приложений и параллельных сборок. Describes the deployment model for Windows Desktop applications, based on the idea of isolated applications and side-by-side assemblies.
Настройка проектов C++ для 64-разрядных целевых объектов с архитектурой x64 Configure C++ projects for 64-bit, x64 targets
Нацеливание на 64-разрядное оборудование с архитектурой x64 с использованием средств сборки MSVC. How to target 64-bit x64 hardware with the MSVC build tools.
Настройка проектов C++ для процессоров ARM Configure C++ projects for ARM processors
Нацеливание на оборудование ARM с использованием средств сборки MSVC. How to use the MSVC build tools to target ARM hardware.
Оптимизация кода Optimizing Your Code
Оптимизация кода различными способами, включая программную оптимизацию. How to optimize your code in various ways including program guided optimizations.
Настройка программ для Windows XP Configuring Programs for Windows XP
Нацеливание на Windows XP с использованием средств сборки MSVC. How to target Windows XP with the MSVC build tools.
Справочные сведения о построении C/C++ C/C++ Building Reference
Содержит ссылки на справочные статьи о сборке программ на C++, о параметрах компилятора и компоновщика, а также о различных средствах сборки. Provides links to reference articles about program building in C++, compiler and linker options, and various build tools.
C/C++ projects and build systems in Visual Studio
You can use Visual Studio to edit, compile, and build any C++ code base with full IntelliSense support without having to convert that code into a Visual Studio project or compile with the MSVC toolset. For example, you can edit a cross-platform CMake project in Visual Studio on a Windows machine, then compile it for Linux using g++ on a remote Linux machine.
C++ compilation
To build a C++ program means to compile source code from one or more files and then link those files into an executable file (.exe), a dynamic-load library (.dll) or a static library (.lib).
Basic C++ compilation involves three main steps:
- The C++ preprocessor transforms all the #directives and macro definitions in each source file. This creates a translation unit.
- The C++ compiler compiles each translation unit into object files (.obj), applying whatever compiler options have been set.
- The linker merges the object files into a single executable, applying the linker options that have been set.
The MSVC toolset
The Microsoft C++ compiler, linker, standard libraries, and related utilities make up the MSVC compiler toolset (also called a toolchain or «build tools»). These are included in Visual Studio. You can also download and use the toolset as a free standalone package from Build Tools for Visual Studio 2019 download.
You can build simple programs by invoking the MSVC compiler (cl.exe) directly from the command line. The following command accepts a single source code file, and invokes cl.exe to build an executable called hello.exe:
Here the compiler (cl.exe) automatically invokes the C++ preprocessor and the linker to produce the final output file. For more information, see Building on the command line.
Build systems and projects
Most real-world programs use some kind of build system to manage complexities of compiling multiple source files for multiple configurations (debug vs. release), multiple platforms (x86, x64, ARM, and so on), custom build steps, and even multiple executables that must be compiled in a certain order. You make settings in a build configuration file(s), and the build system accepts that file as input before it invokes the compiler. The set of source code files and build configuration files needed to build an executable file is called a project.
The following list shows various options for Visual Studio Projects — C++:
create a Visual Studio project by using the Visual Studio IDE and configure it by using property pages. Visual Studio projects produce programs that run on Windows. For an overview, see Compiling and Building in the Visual Studio documentation.
open a folder that contains a CMakeLists.txt file. CMake support is integrated into Visual Studio. You can use the IDE to edit, test, and debug without modifying the CMake files in any way. This enables you to work in the same CMake project as others who might be using different editors. CMake is the recommended approach for cross-platform development. For more information, see CMake projects.
open a loose folder of source files with no project file. Visual Studio will use heuristics to build the files. This is an easy way to compile and run small console applications. For more information, see Open Folder projects.
open a folder that contains a makefile, or any other build system configuration file. You can configure Visual Studio to invoke any arbitrary build commands by adding JSON files to the folder. For more information, see Open Folder projects.
Open a Windows makefile in Visual Studio. For more information, see NMAKE Reference.
MSBuild from the command line
You can invoke MSBuild from the command line by passing it a .vcxproj file along with command-line options. This approach requires a good understanding of MSBuild, and is recommended only when necessary. For more information, see MSBuild.
In This Section
Visual Studio projects
How to create, configure, and build C++ projects in Visual Studio using its native build system (MSBuild).
CMake projects
How to code, build, and deploy CMake projects in Visual Studio.
Open Folder projects
How to use Visual Studio to code, build, and deploy C++ projects based on any arbitrary build system, or no build system at all.
Release builds
How to create and troubleshoot optimized release builds for deployment to end users.
Use the MSVC toolset from the command line
Discusses how to use the C/C++ compiler and build tools directly from the command line rather than using the Visual Studio IDE.
Building DLLs in Visual Studio
How to create, debug, and deploy C/C++ DLLs (shared libraries) in Visual Studio.
Building C/C++ Isolated Applications and Side-by-side Assemblies
Describes the deployment model for Windows Desktop applications, based on the idea of isolated applications and side-by-side assemblies.
Configure C++ projects for 64-bit, x64 targets
How to target 64-bit x64 hardware with the MSVC build tools.
Configure C++ projects for ARM processors
How to use the MSVC build tools to target ARM hardware.
Optimizing Your Code
How to optimize your code in various ways including program guided optimizations.
Configuring Programs for Windows XP
How to target Windows XP with the MSVC build tools.
C/C++ Building Reference
Provides links to reference articles about program building in C++, compiler and linker options, and various build tools.