- Microsoft C++ porting and upgrading guide
- Reasons to upgrade C++ code
- Multitargeting vs. upgrading
- Перенос в универсальную платформу Windows (C++) Porting to the Universal Windows Platform (C++)
- Перенос приложения для Магазина Windows 8.1 на UWP Porting a Windows 8.1 Store App to the UWP
- Перенос приложения для магазина Windows 8.1 на UWP To port a Windows 8.1 Store App to the UWP
- Перенос компонента среды выполнения Windows 8.1 в UWP Porting a Windows 8.1 Runtime Component to the UWP
- Перенос компонента среды выполнения Windows 8.1 в UWP To port a Windows 8.1 Runtime Component to the UWP
- Устранение неполадок Troubleshooting
- Проблемы с конфигурацией проекта Project Configuration Issues
Microsoft C++ porting and upgrading guide
This article provides a guide for upgrading Microsoft C++ code to the latest version of Visual Studio. For projects created in Visual Studio 2010 through 2017, just open the project in Visual Studio 2019. You can upgrade a Visual Studio 2008 or earlier project in two steps. Use Visual Studio 2010 to convert the project to MSBuild format first. Then open the project in Visual Studio 2019. For complete instructions, see Upgrading C++ projects from earlier versions of Visual Studio.
The toolsets in Visual Studio 2015, Visual Studio 2017, and Visual Studio 2019 are binary-compatible. Now you can upgrade to a more recent version of the compiler without having to upgrade your library dependencies. For more information, see C++ binary compatibility 2015-2019.
When upgrading projects that use open-source libraries or are meant to run on multiple platforms, we recommended migrating to a CMake-based project. For more information, see CMake projects in Visual Studio
Reasons to upgrade C++ code
If a legacy application is running satisfactorily, in a secure environment, and isn’t under active development, there might not be much incentive to upgrade it. However, consider an upgrade in these cases: Your application requires ongoing maintenance. Or, you’re doing new feature development, or making performance or security improvements. An upgrade brings these benefits:
The same code can run faster, because we’ve improved compiler optimizations.
Modern C++ features and programming practices eliminate many common causes of bugs, and produce code that’s far easier to maintain than older C-style idioms.
Build times are faster, because of performance improvements in the compiler and linker.
Better standards conformance. The /permissive- compiler option helps you identify code that doesn’t conform to the current C++ standard. The new preprocessor supports code conformance, too.
Better run-time security, including more secure C Runtime library features. And, compiler features such as guard checking and address sanitizers (new in Visual Studio 2019 version 16.4).
Multitargeting vs. upgrading
Perhaps upgrading your code base to a new toolset isn’t an option for you. You can still use the latest Visual Studio to build and edit projects that use older toolsets and libraries. In Visual Studio 2019, you can take advantage of features such as:
modern static analysis tools, including the C++ Core Guidelines checkers and Clang-Tidy, to help identify potential problems in your source code.
automatic formatting according to your choice of modern styles can help make legacy code much more readable.
Перенос в универсальную платформу Windows (C++) Porting to the Universal Windows Platform (C++)
В этом разделе приводятся сведения о переносе существующего кода C++ на платформу приложений Windows 10, которая называется универсальной платформой Windows. In this topic, you can find information on how to port existing C++ code to the Windows 10 app platform, the Universal Windows Platform. Термин универсальность означает, что код может работать на любом устройстве под управлением Windows 10. What is meant by the term universal is that your code can run on any of the devices that run Windows 10. Вы создаете один проект и один пользовательский интерфейс на XAML, который нормально работает на любом устройстве с ОС Windows 10. You create a single project and a single XAML-base user interface that works well on any device that runs Windows 10. Чтобы пользовательский интерфейс приложения мог адаптироваться к дисплеям разного размера, можно использовать средства динамического макета в XAML. You can use dynamic layout features in XAML to allow the app’s UI to adapt to different display sizes.
В состав документации центра разработчиков Windows входит руководство по переносу приложений Windows 8.1 в универсальную платформу Windows. The Windows Dev Center documentation contains a guide for porting Windows 8.1 apps to the Universal Windows Platform. См. раздел Перенос приложения из среды выполнения Windows 8 в UWP. See Move from Windows Runtime 8 to UWP. Хотя в этом руководстве основное внимание уделено коду на C#, большинство рекомендаций и инструкций применимо и к C++. Although the guide focuses mostly on C# code, most of the guidance is applicable to C++. Следующие процедуры содержат более подробные сведения. The following procedures contain more detailed information. См. также Перемещение от классического приложения к UWP. See also Move from a desktop application to UWP.
В этом разделе рассматриваются следующие процедуры переноса кода в UWP. This topic contains the following procedures for porting code to the UWP.
То же самое можно сделать при наличии классической DLL-библиотеки Win32, которую требуется вызывать из приложения UWP. If you have a classic desktop Win32 DLL and you want to call it from a UWP application, you can do that as well. С помощью таких процедур можно создать уровень пользовательского интерфейса UWP для существующего классического приложения Windows на языке C++ или кроссплатформенного стандартного кода C++. Using such procedures, you can create a UWP user interface layer for an existing classic Windows desktop C++ application, or your cross-platform standard C++ code. См. Практическое руководство. Использование существующего кода C++ в приложении универсальной платформы Windows. See How to: Use Existing C++ Code in a Universal Windows Platform App.
Перенос приложения для Магазина Windows 8.1 на UWP Porting a Windows 8.1 Store App to the UWP
Если у вас есть приложение для магазина Windows 8.1, эту процедуру можно использовать для того, чтобы оно могло работать на UWP и любом устройстве с ОС Windows 10. If you have a Windows 8.1 Store App, you can use this procedure to get it working on the UWP and any device that runs Windows 10. Рекомендуется сначала построить проект с помощью Visual Studio 2019 в качестве Windows 8.1 проекта, чтобы сначала устранить все проблемы, возникающие в результате изменений в компиляторе и библиотеках. It’s a good idea to first build the project with Visual Studio 2019 as a Windows 8.1 project, to first eliminate any issues that arise from changes in the compiler and libraries. После этого можно воспользоваться одним из двух способов преобразования проекта в проект UWP для Windows 10. Once you’ve done that, there are two ways to convert this to a Windows 10 UWP project. Самый простой способ (как поясняется в следующей процедуре) — создание универсального проекта Windows и копирование в него существующего кода. The easiest way (as explained in the following procedure) is to create a Universal Windows project, and copy your existing code into it. Если вы использовали универсальный проект для классического приложения Windows 8.1 и Windows Phone 8.1, то проект будет запускаться с двумя разными макетами в XAML. Однако на выходе вы получите один динамический макет, адаптирующийся под размер экрана. If you were using a Universal project for Windows 8.1 desktop and Windows 8.1 Phone, your project will start with two different layouts in XAML but end with a single dynamic layout that adjusts to the display size.
Перенос приложения для магазина Windows 8.1 на UWP To port a Windows 8.1 Store App to the UWP
Если вы еще не осуществили перенос, откройте свой проект приложения Windows 8.1 в Visual Studio 2017 и выполните процедуру обновления файла проекта. If you have not already done so, open your Windows 8.1 App project in Visual Studio 2017, and follow the instructions to upgrade the project file.
Необходимо установить средства Windows 8.1 в Visual Studio. You need to have installed the Windows 8.1 Tools in Visual Studio setup. Если эти средства не установлены, запустите программу установки Visual Studio в окне » программы и компоненты «, выберите Visual Studio 2017, а затем в окне программы установки выберите изменить. If you don’t have those tools installed, start Visual Studio setup from the Programs and Features window, choose Visual Studio 2017, and in the setup window, choose Modify. Выберите средства Windows 8.1, убедитесь, что оно выбрано, и нажмите кнопку ОК. Locate Windows 8.1 Tools, make sure it is selected, and choose OK.
Откройте окно Свойства проекта и в области C++ > Общие установите для набора инструментов платформы значение v141, указывающее набор инструментов для Visual Studio 2017. Open the Project Properties window, and under C++ > General, set the Platform Toolset to v141, the toolset for Visual Studio 2017.
Постройте проект как проект Windows 8.1, а затем исправьте все ошибки сборки. Build the project as a Windows 8.1 project, and address any build errors. Как правило, на этом этапе ошибки связаны с критическими изменениями в средствах сборки и библиотеках. Any errors at this stage are probably due to breaking changes in the build tools and libraries. Подробное описание изменений, которые могут повлиять на код, см. в статье Журнал изменений Visual C++ 2003–2015. See Visual C++ change history 2003 — 2015 for a detailed explanation of the changes that might affect your code.
После того, как проект будет построен без ошибок, можно приступить к переносу на универсальную платформу Windows (Windows 10). Once your project builds cleanly, you are ready to port to Universal Windows (Windows 10).
Создайте новый проект универсального приложения Windows с помощью пустого шаблона. Create a new Universal Windows App project using the Blank template. Ему можно присвоить имя, совпадающее с именем существующего проекта. Но в этом случае проекты должны находиться в разных каталогах. You might want to give it the same name as your existing project, although to do that the projects must be in different directories.
Закройте решение, а затем с помощью проводника Windows или командной строки скопируйте файлы кода (с расширениями. cpp,. h и. XAML) из проекта Windows 8.1 в ту же папку, что и файл проекта (VCXPROJ) для проекта, созданного на шаге 1. Close the solution, and then using Windows Explorer or the command line, copy the code files (with extensions .cpp, .h, and .xaml) from your Windows 8.1 project into the same folder as the project file (.vcxproj) for the project you created in step 1. Не копируйте файл Package.appxmanifest. Если у вас есть отдельный код для Windows 8.1 Desktop и Windows 8.1 Phone, выберите один из них для переноса в первую очередь (позже вам придется выполнить ряд действий, чтобы подготовить перенос другого кода). Do not copy the Package.appxmanifest file, and if you have separate code for Windows 8.1 desktop and phone, choose one of them to port first (you’ll have to do some work later to adapt to the other). Не забудьте скопировать все вложенные папки и их содержимое. Be sure to copy and subfolders and their contents. При появлении соответствующего запроса выберите вариант замены всех файлов с одинаковыми именами. If prompted, choose to replace any files with duplicate names.
Повторно откройте решение и выберите пункт Добавить > существующий элемент в контекстном меню узла проекта. Reopen the solution, and choose Add > Existing Item from the shortcut menu for the project node. Выберите все файлы, которые были скопированы, за исключением файлов, которые уже являются частью проекта. Select all the files you copied, except any that are already part of the project.
Проверьте все вложенные папки и убедитесь, что в них также добавлены файлы. Check any subfolders and make sure to add the files in them as well.
Если вы используете имя проекта, которое отличается от имени старого проекта, откройте файл Package.appxmanifest и обновите точку входа в соответствии с именем пространства имен для класса App . If you are not using the same project name as your old project, open the Package.appxmanifest file and update the Entry Point to reflect the namespace name for the App class.
Поле Точка входа в файле Package.appxmanifest содержит имя области для класса App , содержащего пространство имен, которое содержит класс App . The Entry Point field in the Package.appxmanifest file contains a scoped name for the App class, which includes the namespace that contains the App class. При создании универсального проекта Windows для пространства имен указывается имя проекта. When you create a Universal Windows project, the namespace is set to the name of the project. Если оно отличается от имени, указанного в файлах, скопированных из старого проекта, обновите одно из них, чтобы они соответствовали друг другу. If this is different from what’s in the files you copied in from your old project, you must update one or the other to make them match.
Постройте проект и устраните все ошибки сборки из-за критических изменений между различными версиями пакета Windows SDK. Build the project, and address any build errors due to breaking changes between the different versions of the Windows SDK.
Запустите проект на локальном компьютере. Run the project on the Local Desktop. Убедитесь, что отсутствуют ошибки развертывания, что макет приложения имеет приемлемый формат и что он корректно работает на настольном компьютере. Verify that there are no deployment errors, and that the layout of the app looks reasonable and that it functions correctly on the desktop.
Если у вас есть отдельные файлы кода .xaml для другого устройства, например, для Windows Phone 8.1, проанализируйте этот код и найдите в нем отличия от кода для стандартного устройства. If you had separate code files and .xaml for another device, such as Windows Phone 8.1, examine this code and identify where it differs from the standard device. Если разница размещается только в макете, вы можете использовать Диспетчер визуальных состояний в XAML для настройки отображения в зависимости от размера экрана. If the difference is only in the layout, you might be able to use a Visual State Manager in the xaml to customize the display depending on the size of the screen. Если имеются другие различия, можно использовать разделы условий в коде с помощью следующих операторов #if. For other differences, you can use conditions sections in your code using the following #if statements.
Эти операторы могут применяться соответственно к приложениям UWP, приложениям Магазина Windows Phone, к обоим видам приложений или ни к одному из них (то есть, только к классическим приложениям Win32). These statements respectively apply to UWP apps, Windows Phone Store apps, both, or neither (classic Win32 desktop only). Эти макросы доступны только в пакете SDK Windows 8.1 и более поздних версиях. Поэтому если код должен компилироваться в более ранних версиях пакета SDK Windows или для других платформ, помимо Windows, необходимо учитывать ситуацию, в которой не определена ни одна их этих возможностей. These macros are only available in Windows SDK 8.1 and later, so if your code needs to compile with earlier versions of the Windows SDK or for other platforms besides Windows, then you should also consider the case that none of them are defined.
Запустите приложение и выполните его отладку в эмуляторе или физическом устройстве для каждого типа устройств, поддерживаемого приложением. Run and debug the app on an emulator or physical device, for each type of device that your app supports. Чтобы запустить эмулятор, Visual Studio необходимо запустить на физическом компьютере, а не на виртуальной машине. To run an emulator, you need to run Visual Studio on a physical computer, not a virtual machine.
Перенос компонента среды выполнения Windows 8.1 в UWP Porting a Windows 8.1 Runtime Component to the UWP
Если у вас есть библиотека DLL или компонент среды выполнения Windows, которые уже работают с приложениями для магазина Windows 8.1, эту процедуру можно использовать для обеспечения работы компонента или библиотеки DLL с платформой UWP и Windows 10. If you have a DLL or a Windows Runtime Component that already works with Windows 8.1 Store apps, you can use this procedure to get the component or DLL working with the UWP and Windows 10. Процедура в целом заключается в создании нового проекта и копировании в него кода. The basic procedure is to create a new project and copy your code into it.
Перенос компонента среды выполнения Windows 8.1 в UWP To port a Windows 8.1 Runtime Component to the UWP
В диалоговом окне Новый проект в Visual Studio 2017 найдите узел Универсальное приложение для Windows . In the New Project dialog in Visual Studio 2017, locate the Windows Universal node. Если вы не видите этот узел, сначала установите пакет SDK для Windows 10. If you don’t see this node, install the Windows 10 SDK first. Выберите шаблон компонента среды выполнения Windows , присвойте компоненту имя и нажмите кнопку ОК . Choose the Windows Runtime Component template, give a name for your component, and choose the OK button. Имя компонента будет использоваться в качестве имени пространства имен, поэтому вы можете использовать имя пространства имен старого проекта. The component name will be used as the namespace name, so you might want to use the same name as your old projects’ namespace. Для этого потребуется создать проект в папке, которая отличается от папки старого проекта. This requires that you create the project in a different folder from the old one. Если выбрать другое имя, можно обновить имя пространства имен в созданных файлах кода. If you choose a different name, you can update the namespace name in the generated code files.
Закройте проект. Close the project.
Скопируйте все файлы кода (CPP, H, XAML и т. д.) из компонента Windows 8.1 в только что созданный проект. Copy all the code files (.cpp, .h, .xaml, etc.) from your Windows 8.1 component into your newly created project. Не копируйте файл Package.appxmanifest. Do not copy the Package.appxmanifest file.
Выполните сборку и устраните все ошибки, возникающие из-за критических изменений между разными версиями пакета SDK Windows. Build, and resolve any errors due to breaking changes between different versions of the Windows SDK.
Устранение неполадок Troubleshooting
В процессе портирования кода на платформу UWP могут возникать различные ошибки. You might encounter various errors during the process of porting code to the UWP. Могут возникать следующие проблемы. Here are some of the possible problems you might encounter.
Проблемы с конфигурацией проекта Project Configuration Issues
Может появиться такое сообщение об ошибке. You might receive the error:
Это означает, что проект не построен как универсальный проект Windows. If this happens, the project is not building as a Windows Universal project. Проверьте файл проекта и убедитесь, что он содержит правильные элементы XML, которые определяют проект как универсальный проект Windows. Check the project file and make sure it has the correct XML elements that identify a project as a Windows Universal Project. Должны присутствовать следующие элементы (номер версии целевой платформы может отличаться). The following elements should be present (the version number of the target platform might be different):
Если вы создали новый проект UWP в Visual Studio, эта ошибка не появится. If you created a new UWP project using Visual Studio, you should not see this error.