How to install (v142) Build tools in Visual studio
As I am trying to build something in visual studio then visual studio show me some warning and then If i ignored it and build then error occurs.
It will also show me an Alternate option I also tried it but not works.
![]()
9 Answers 9
I had the same problem, but when trying to open a project made in VS2019 with VS2017, so I changed this in my project:
Go to: Project->Properties->General->Platform Toolset and change to the current version of your VS.
![]()
The bottom line is that you need to install Visual Studio 2019 to access the v142 tools.
Along with different versions of Visual Studio (VS2015, VS2017, VS2019), Microsoft also releases different build tool versions as they continue to improve the compiler and provide additional capabilities and to meet updated language standards (C++, C++11, C++17, etc.). See Visual Studio 2015 not detecting v141 (2017) Build tools
See as well this Microsoft blog posting about build tools for VS2017 and accessing the older v140 from VS2015, Visual Studio Build Tools now include the VS2017 and VS2015 MSVC Toolsets.
Many of you have told us that you still need the MSVC v140 toolset from Visual Studio 2015 to continue building older codebases. We’ve updated the Visual Studio Build Tools to include the v140 toolset from Visual Studio 2015 Update 3 including the most recent servicing release. You might notice that the compiler toolset build version may not match the version in a full VS 2015 install, even though they are the same compilers. That happens because we build the full Visual Studio and the Visual Studio Build Tools in separate branches that may be built on different days.
The Visual C++ build tools workload in the Visual Studio Build Tools will install the latest v141 toolset from VS2017 by default. The v140 toolset from VS2015 will install side-by-side with the v141 toolset. To install them just select the “VC++ 2015.3 v140 toolset for desktop (x86,x64)” at the bottom of the “Optional” section.
In your case, V142 build tools was released with VS2019. It does not appear that v142 is available for VS2017. The most recent build tools for VS2017 looks to be v141.
You can use the Visual Studio installer to modify the build tools available by adding or removing from the list. This SO posting describes a similar problem but with v140 missing in a VS2015 Visual Studio installation. MSbuild Error: The builds tools for v140 (Platform Toolset = 'v140') cannot be found
However if Microsoft has not released a particular Build Tools version for the Visual Studio you are using then it will not show in the list of available toolsets.
It looks like beginning with VS2015, Microsoft is providing a standard Visual Studio engine that is shared among VS 2015, VS2017, and VS2019 with build tools and various components being updated to provide new features and functionality and new language standards compliance. There are dependencies between the Visual Studio version and what build tools and components can be used with the Visual Studio version, e.g. v142 is not available for VS2017, most probably to provide an incentive for purchasing the newer product.
On installing VS2017 after installing VS2019
As a side note, while doing a bit of discovery on this question, I have found some articles that indicate that if you have a recent Visual Studio installed and then install an earlier version of Visual Studio, the default target build tools can also change to the build tools for the earlier install.
In other words, if you have VS2019 with a default target of v142 already installed and then install VS2017, the default target will change to v141 requiring you to actually set the build target to v142 when using VS2019.
Как в VisualStudio установить средства сборки v142?
Ошибка MSBuild MSB8020
Не удалось найти средства сборки для v142 (набор средств платформы = «v142»). Чтобы выполнить сборку с помощью версии v142 средств сборки, установите средства сборки v142. Также можно выполнить обновление до текущих средств Visual Studio, выбрав меню «Проект» или щелкнув правой кнопкой мыши решение, а затем выбрав «Изменить целевую платформу решения».
При нажатии на «Изменить целевую платформу решения» появляется это окно. Но при изменении версии пакета ничего не меняется. Ошибка остаётся.
Setup an Assembly Project on Visual Studio 2019
The Microsoft Visual Studio come with the built-in Macro Assembler and provide many debugging capabilities (Register & Memory View, Breakpoints and Step over). However there is no explicit assembly project template to choose from. In this article, I will describe the steps required to set up an assembly project on the Visual Studio 2019.
I had compiled the knowledge from many sources and do many trial and error.
The Sample Projects (for quick reference)
The sample projects of MASM (both 64-bit Assembly and 32-bit Assembly) can be downloaded from the Github links below:
In these samples, I also demonstrate how to call the Win32 “MessageBox” API from the Assembly codes.
1. Installing Visual Studio 2019
Visual Studio 2019 could be downloaded from the site: https://visualstudio.microsoft.com/vs/
The Community 2019 edition is free of charge.

When prompting to select an installed language, I choose C++. I’m not sure whether selecting other languages would work or not for assembly project.
2. Creating a C++ project as a base project
Create a C++ empty project.

Named the project: “MASM”. So that, in the later step, we can save this project as a project template for further use. Set the save location to any preferred folder (I have precreated the folder C:\VSProj). Select “Place solution and project in the same directory” to prevent two nested folders with the same name.
The Visual Studio will create the folder with the same project name automatically.

3. Setup the Build Customization as Assembly Language
Right click at the project name > Build Dependencies > Build Customizations…

Select the “masm”, then OK.

Right click at the project name > properties > Linker > System > SubSystem : Windows
This will prevent the assembly program to show the console window ( the black text-mode window). Or if you want the console window you can leave it at the default: Console mode.
I prefer the Windows mode because it has look-and-feel of native windows app. For debugging, just use breakpoint and watch windows to look at register and memory values at real-time. However, if we want to test the text mode input/output, we should use the console mode.

4. Creating an Assembly Source File
Right click at the project name > Add > New Item…

Name the file: “Main.asm” . The selected item type is not important. Any type can be selected. But it is important to name it with the “.asm” file extension.

Write a test program. You can copy the code from below. I adapted the code from the wonderful book : Assembly Language for x86 Processors by Kip Irvine. I highly recommend this book for anyone start learning the Assembly language.
Firstly, We will create the 32-bit Assembly Code. And then at the appendix B, we will create the 64-bit Assembly Code.
The 32-bit Assembly Code :
To build the 32-bit Assembly, make sure that “x86” is selected in the “solution platform” drop down of the toolbar.

Press the green, play button: (run with) Local Windows Debugger.
The program will sum 7 with 8 and return the result 15 as shown in the debug output window.
5. (Optional) Setup Listing File
The listing file is useful for examining what the assembler has generated. To setup the listing file generation, right click the project name > Properties > Microsoft Macro Assembler > Listing File > Assembled Code Listing File : $(IntDir)$(ProjectName).lst
Note: The page “Microsoft Macro Assembler” will appear only when there are some assembly files in the project.

Build (and/or run) the project again. You will see the listing file generated at the project’s debug folder.

Drag the listing file into Visual Studio to view it. The listing file content will be like this:

6. (Optional) Setup for Release Mode Build
This section could be skip because it is quite complex. Do it when you need to use the release mode for release build. Or you could come to this section later when in need.
In Visual Studio, there is a separate release mode build configuration. The release mode configuration could be set differently from the debug mode configuration. For example, the release mode may have more optimizations and less debugging features.
If the release mode is needed, we should do the same as the step 3 and 5. Additionally, we need to customize the safe exception handler configurations.
6.1 Setup Subsystem (Windows or Console) and Listing File Generation
Go to the project properties > change the configuration mode to : Release.

Choosing your prefer subsystem (Windows or Console).

Setting up the listing file generation.

Changing the active configuration to Release.

Try building and running the program using the green play button. You will see the error message: “fatal error: LNK1281: Unable to generate SAFESEH image.”.
The next step 5.2 will solve this error.

6.2 Fully Enable or Disable the Safe Exception Handlers
In the release build mode, the default option of the linker is that every images (object files) should have safe exception handlers. However, the default option of the assembler (compiler) is not to use safe exception handlers. These conflicts cause the above error. Now, we have two choices to fix the error.
Way 1: Enable the safe exception handlers in the assembler (compiler).

Way 2: Or we could entirely disable the use of safe exception handler at the linker.
Linker > Advance > Image has Safe Exception Handlers : No
Choose one way but not both!
I preferred way 1 because it looks safer to have safe exception handlers. But, in fact, I am not 100% sure because I don’t have much knowledge about safe exception handlers.
After that we should be able to build and run the program in the release mode without any error.
Caution on switching between Debug and Release : When changing the active configuration in the toolbar and then open the project property pages, the property pages may not be conformed to the current active configuration. This could cause confusion when changing some project settings appear to not affect the current build. If this occur, please ensure the matching of active configuration and the property pages.
7. Save as a Project Template
After these long steps, we might not want to do them every time to create a new Assembly project. Fortunately, Visual Studio can save the project as a project template.
First, edit the Main.asm to contain only template code:
Try running it to make sure that the program works correctly.
If you still use release mode (from step 5), switch back to the debug mode.

Click: Project > Export Template …

Choose our “MASM” project from the drop down list.

Describe the template description.

After that when you create a new project, you could select MASM as a project template.

Appendix A: Debugging
Debugging is straightforward in Visual Studio. To set a breakpoint, just clicking the grey area in front of the line of the source code. When running, the program will pause before the execution of the breakpoint line.
To look at registers, select Debug > Windows > Registers
To look at variables, select Debug > Windows > Watch. Then type the variable name.
Or select Debug > Windows > Memory > Memory 1. Then type “&varname” at the address box.
An example of pausing at the breakpoint of the Visual Studio Debugger for Assembly Language
Also, we can debug step-by-step using “Step Into” and “Step Over”.

Appendix B: Setup the 64-Bit Assembly Project
This section describes additional steps needed to setup a 64-bit assembly project. You should finish the prior steps before doing these steps.
1. Select the 64-bit platform
At the toolbar, set the Solution Platform to “x64”.

2. Creating the 64-bit Assembly Source Code
Copy the code below to replace the old code in main.asm:
The 64-Bit Assembly Code
Please note that the 32-bit and 64-bit assembly code are different in many ways.
In 64-bit Assembly Code:
- Some directives, such as “.386”, are not used.
- PROTO doesn’t have parameter list specified.
- END doesn’t have “main” start symbol specified.
- When calling Win32 API such as “ExitProcess”, parameters will be passed on registers (rcx, rdx, r8, r9). (see details in Appendix C)
3. Specifying the “main” start symbol (entry point)
When Build, you may get the error: unresolved external symbol mainCRTStartup.

To fix this error:
- Open the project properties page (see image below) by choosing Project > Properties.
- Then make sure that the “Active(Debug)” Configuration and “x64” Platform are selected.
- Set the Linker > Advance > Entry Point to “main“
If you also want to use the release mode build, do the same for the configuration: “Release”, platform: “x64”.

You can also choose the SubSystem: Console or Windows as you preferred.

Run the program. The return code from calling ExitProcess will be displayed on the output windows correctly.

Appendix C: Microsoft x64 calling convention
Microsoft had defined the way that the 64-bit assembly code should call the Win32 API. This specification is called “Microsoft x64 calling convention”. Some essential points are:
- The first four arguments are passed by registers (rcx, rdx, r8, r9).
- Some stack memory, called the shadow area, must be reserved (at least 4*8 bytes)
- 16-byte stack pointer alignment (rsp = stack pointer register) is needed before calling any win32 API.
That are the reasons of this line in the 64-bit assembly code:
We need to reserve at least 32 bytes (20h) as the shadow area. And main proc always start at the address ending 8h. So, to do 16-byte alignment, we need to add another (8h) bytes. That’s why we subtract rsp by (28h) bytes. (the stack grows down)
Consider the following code. This code calls the MessageBox Win32 API.
I have tried to depict the call stack memory layout in the following diagram. Notice that rsp-28h will align the stack pointer into 16-byte alignment beautifully, because the main() procedure is always start with the stack pointer having address ending with 8h. You can see this fact yourself by debugging the above code, running it step by step and observing register values in the register window.
Stack Area of x64 Calling Convention
To verify that the alignment requirement is needed, try changing the “sub rsp, 28h” into “sub rsp, 20h“. This will cause the Access Violation run-time error, when calling MessageBox():

Some Win32 APIs are not that strict. For example, the ExitProcess don’t cause the Access Violation Exception. But to respect the x64 calling convention, every 64-bit assembly code that call Win32 API should have some statement like “sub rsp, 28h” to reserve shadow area and adjust stack pointer alignment.
Please note that if use full x64 prolog/epilog code, the “sub rsp, 28h” must be changed to “sub rsp, 20h” because the prior “push” instruction has changed the rsp by 8h bytes. So, need to subtract only 20h.
H Двоичная совместимость C++ и безболезненное обновление до Visual Studio 2019 в черновиках Перевод

Visual Studio 2019 расширяет границы индивидуальной и командной производительности. Мы надеемся, что эти нововведения окажутся для вас привлекательными, и вы вскоре начнете обновление до Visual Studio 2019.
Visual Studio 2019 значительно упрощает перенос вашего кода из предыдущих версий Visual Studio. В этом посте описаны факторы, благодаря которым обновление до Visual Studio 2019 будет безболезненным.
- Вы можете установить последнюю версию IDE параллельно с любыми старыми версиями VS.
- Вы можете продолжить написание кода на C++ с помощью наборов инструментов MSVC v140 (VS 2015.3) или v141 (VS 2017).
- Вы можете выполнить обновление до последней версии MSVC v142 (VS 2019) и поддерживать двоичную совместимость с любыми сторонними библиотеками, которые еще не перенесены.
- Независимо от того, какой набор инструментов вы используете, вы получаете доступ ко всей коллекции библиотек OSS, доступных в Vcpkg.
Параллельная установка Visual Studio
Вы можете установить последнюю версию Visual Studio на компьютер, на котором уже установлена более ранняя версия, и продолжать использовать обе версии параллельно без помех. Это отличный способ попробовать Visual Studio 2019 или использовать его для некоторых своих проектов. Установщик Visual Studio позволит вам управлять версиями Visual Studio 2017 и 2019 из центрального пользовательского интерфейса.

Наборы инструментов MSVC v140 (VS 2015.3) и MSVC v141 (VS 2017) в IDE Visual Studio 2019
Даже если вы еще не готовы переместить проект в новейший набор инструментов (MSVC v142), вы все равно можете загрузить проект в среде IDE Visual Studio 2019 и продолжить использовать текущий, более старый набор инструментов.
Загрузка существующих проектов C++ в IDE не приведет к обновлению или изменению их файлов. Таким образом, ваши проекты также загрузятся в предыдущей версии IDE в той ситуации, когда вам нужно вернуться назад, или если у вас есть товарищи по команде, которые еще не обновились до VS 2019 (эта функция также известна как циклическое переключение проекта).
Наборы инструментов из более старых версий VS на вашем компьютере видны как наборы инструментов платформы в последней IDE. И если вы начнете работу только с версией VS 2019, установленной на вашем компьютере, получится очень просто получить старые наборы инструментов непосредственно из установщика Visual Studio, настроив рабочую нагрузку C++ Desktop (на вкладке «Individual Components» перечислены все параметры).
Теперь доступен новый набор инструментов v142
В рамках Visual Studio 2019 (Preview, общедоступной версии и будущих обновлений) мы планируем продолжить развитие наших C++ компиляторов и библиотек с:
- новыми фичами C++20,
- более быстрой сборкой ,
- еще лучшей оптимизацией кода.
Набор инструментов MSVC v142 уже доступен.
VC Runtime в последнем наборе инструментов MSVC v142 двоично совместим с v140 и v141
Мы хорошо поняли, что основной причиной, способствующей быстрому распространению MSVC v141, стала его двоичная совместимость с MSVC v140. Это позволило вам перенести свой собственный код в набор инструментов v141 в удобном для вас темпе, не дожидаясь переноса зависимостей сторонних библиотек.
Мы хотим добиться того же и с MSVC v142. Вот почему мы объявляем, что наша команда обеспечит двоичную совместимость для MSVC v142 с MSVC v141 и v140.
Это означает, что если вы скомпилируете весь свой код с помощью набора инструментов v142, но при этом у вас останется одна или несколько библиотек, созданных с использованием набора инструментов v140 или v141, то связывание всего это вместе (с последним линкером) будет работать как положено. Чтобы сделать это возможным, VC Runtime не меняет свою основную версию в VS 2019 и остается обратно совместимой с предыдущими версиями VC Runtime.
При смешивании двоичных файлов, созданных с различными поддерживаемыми версиями набора инструментов MSVC, существует требование к версии для VCRedist. В частности, VCRedist не может быть старше любой из версий набора инструментов, используемых для создания вашего приложения.
Сотни библиотек C++ на Vcpkg доступны независимо от используемого набора инструментов
Если вы используете Vcpkg с VS 2015 или VS 2017 для одной или нескольких ваших open-source зависимостей , вы будете рады узнать, что эти библиотеки (около 900 на момент написания этой статьи) теперь могут быть скомпилированы с помощью набора инструментов MSVC v142 и доступны для использования в проектах Visual Studio 2019.
Если вы только начинаете работать с Vcpkg, не беспокойтесь — Vcpkg — это open-source проект Microsoft, призванный упростить получение и создание open-source библиотек C++ в Windows, Linux и Mac.
Поскольку v142 двоично совместим с v141 и v140, все уже установленные пакеты также будут продолжать работать в VS 2019 без перекомпиляции; однако мы все же рекомендуем перекомпилировать, чтобы вы могли наслаждаться новыми оптимизациями компилятора, которые мы добавили в v142.
Если у вас установлен VS 2019 Preview параллельно со старой версией VS (например, VS 2017), Vcpkg предпочтет стабильный выпуск, поэтому вам потребуется установить для Vcpkg триплетную переменную VCPKG_PLATFORM_TOOLSET в v142, чтобы использовать последний набор инструментов MSVC.
Версия компилятора MSVC изменяется на 19.2 x (с 19.1 x в MSVC v141)
И последнее, но не менее важное: компиляторная часть набора инструментов MSVC v142 изменяет свою версию на 19.20 –незначительное увеличение версии по сравнению с MSVC v141.
Обратите внимание, что макросы feature-test поддерживаются в компиляторе MSVC и STL, начиная с MSVC v141, и они должны быть предпочтительным вариантом, позволяющим вашему коду поддерживать несколько версий MSVC.
Пожалуйста, загрузите Visual Studio 2019 и дайте фидбек. Наша цель — сделать ваш переход на VS 2019 максимально простым, поэтому мы всегда заинтересованы в ваших отзывах. С нами можно связаться по электронной почте (mailto:visualcpp@microsoft.com).
Если у вас возникли другие проблемы с Visual Studio или MSVC, или у вас есть предложение, сообщите нам об этом через Help > Send Feedback > Report A Problem / Provide a Suggestion в продукте или через Developer Community. Вы также можете найти нас в Твиттере @VisualC.