C3859 не удалось создать виртуальную память для pch
Но в настоящее время с этим есть две проблемы:
Почему это не происходит каждый раз , когда я выполняю перестройку? Если я правильно понимаю, компилятору не хватило памяти при компиляции моего проекта. Итак, если я сделаю перестройку, которая очистит всю предыдущую работу, не должна ли она исчерпать память в следующий раз, если я ничего не изменю?
Решение
Я знаю, что это старо, но я оказался здесь, так что я мог бы ответить.
Есть отличная статья о проблемах PCH Вот .
1) Почему это не происходит каждый раз, когда я делаю перестройку?
Это немного сложно, чтобы ответить наверняка. Так как это происходит не каждый раз, это может быть несколько проблем. Скорее всего, это связано с распределением памяти. Из статьи:
- фрагментация диапазонов адресов виртуальной памяти, требуемых
PCH перед CL.EXE может загрузить его в память. - Отказ ОС Windows при больших нагрузках увеличить размер файла подкачки за определенный промежуток времени.
c1xx: ошибка C3859: не удалось создать виртуальную память для PCH [… Project.vcxproj] c1xx: примечание: система вернула код 1455: файл подкачки слишком мал для выполнения этой операции
Это также может помочь установить PreferredToolArchtecture в x64:
Если вы используете MSBuild из командной строки, вы можете передать / p: PreferredToolArchtecture = x64 в MSBuild. Если вы строите с помощью MSBuild из Visual Studio, вы можете отредактировать файл .vcxproj, включив в него группу PropertyGroup, содержащую это свойство.
Эту проблему легко упустить из виду, но подобные проблемы возникают и тогда, когда предварительно скомпилированный заголовок слишком велик. Небольшая уборка также может быть хорошей идеей.
Все ответы
Virtual Memory/Page file can be edited by R.click my computer/properties/Advanced/Virtual Memory/Advanced/Change Button.With C: highlited set to Let System Manage,click set 2X,exit restart pc. This works for any storage device USB flash included.The default setting to enable,in cmd or run type: diskmgmt.msc in msc,L.click on the device,go up to Actions/All/Make Active/exit msc. This being the connection to a device is made,use the OS storage software,Intel uses Intel storage mgr
Thank you for posting here.
>> C3859: Failed to create virtual memory for PCH
I suggest you could try to use the /Zm compiler flag to specify a larger value for the precompiled header file. /Zm: Determines the amount of memory that the compiler allocates to construct precompiled headers.
factor is a scaling factor that determines the amount of memory that the compiler uses to construct precompiled headers.The factor can be 10, 100, 200, 1000, or 2000 to allocate 7.5MB, 75MB, 150MB, 750MB, or 1500MB, respectively.
To set the /Zm compiler option in the Visual Studio development environment:
1,Open the project's Property Pages dialog box.
2,In the navigation pane, select Configuration Properties > C/C++ > Command Line.
3,Enter the /Zm compiler option in the Additional Options box.
1 Answer 1
Actually, it is quite a headache issue for a couple of years. And the workaround which you found is the current solution and does help build your project successfully before VS2019 16.7 version. And upgrading VS to 16.7 , the issue still sometimes happens with all the workarounds you have used. This does have a certain relationship with the VS IDE version and your project. This is a problem caused by two aspects.
Since you don’t want to change the PCH file, I have reported the issue on our DC Forum.
You can vote it and add any comments if I did not describe the issue in detail so that it will get more Microsoft's attention.
If you are using VS Professional or Enterprise version and willing to accept the risk of reinstalling the previous version of VS, you can try this. And if you do not want it, you can just ignore it.
Refer to this document and uninstall the current VS version and install the related 16.6 version from that link.
Besides, you could share a minimal, reproducible sample with us if you like.
Спрашивающий
5 Answers 5
I know this is old but I ended up here so I might as well answer.
There is a great article about PCH problems here.
1) Why does it not occur every time I do a rebuild?
This is a bit complex to answer surely. Since it is not happening every time, it could be several issues. It is most likely due to memory allocation. From the article :
- Fragmentation of the virtual memory address range(s) required by the PCH before CL.EXE is able to load it into memory.
- Failure of the Windows OS under heavy loads to increase the pagefile size within a certain time threshold.
It could also be a Pagefile size problem (most likely on Virtual machines) but I believe you would have a message similar to this :
c1xx : error C3859: Failed to create virtual memory for PCH [. Project.vcxproj] c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete
2) Why do I get an error message with this lower value? (Zm114 instead of Zm120)
Make sure that the Zm120 modifications handle all the build configurations (Release|Debug) and Platform (x86|x64).
It could also help to set PreferredToolArchtecture to x64:
If you’re using MSBuild from the command line you can pass /p:PreferredToolArchtecture=x64 to MSBuild. If you’re building with MSBuild from within Visual Studio, you can edit your .vcxproj file to include a PropertyGroup containing this property.
This one is easily overlook, but those kind of problem also happen when the precompiled header is just too big. Doing a little cleanup might be a good idea as well.
A good read on PCH issues and recommendations can be found here.
After we've upgraded from VS2019 16.6 to VS2019 16.7.6, we're sometimes getting the infamous C3859 error when compiling our MSVC solutions.
The exact same source occasionally fails to compile with the errors
- Compiler Error C3859 "virtual memory range for PCH exceeded"
- System Code 1455 "The paging file is too small for this operation to complete."
- Fatal error C1076 "compiler limit : internal heap limit reached"s
sample compilation output:
The generated PCHs are up to 300MB in size. Passing the '/Zm' switch (with values up 1000) didn't make a difference.
We've had issues with this years ago, using VS2010 - back then setting '/Zm200' solved the problem for us (note the error codes back then explicitly told us to increase to '/Zm150' or higher).
'reducing the complexity and size of our PCH files' really is not what we want to do - as we're intentionally sacrificing on memory in order to speed up our builds.
I'm wondering if there is a way to figure out what the actual underlying problem is that generates these sporadic occuring errors - and most important: how to fix it .
There's a similar problem when using PCHs on GCC. The compiler crashes if the PCH size is greater than 128 MB (the default stack size for PCHs in the cc1plus.exe executable).
@AlanBirtles - I wish I could say so - still struggling to find the right place to put in a issue report :-/
@LostArrow - thanks for the note, yet we didn't have any Issues with large PCHs on the previous version of VS (16.6)
There's usually a smiley face button in visual studio, just click that and it'll guide you through creating a bug report
Другие решения
Просто согласиться с тем, что решение оказалось для меня. Кажется, что Visual Studio пыталась скомпилировать мою программу для нескольких архитектур, несмотря на то, что я думал, что удалил профили, в диспетчере конфигурации была куча поддельных записей для сборки в режиме x86. Это было бесполезно для меня, так как я хочу встроить только в x64. После удаления этих записей программа снова скомпилировалась, и эта ошибка исчезла. Надеюсь, это поможет кому-то.
But currently, there are two problems with this:
Why does it not occur every time I do a rebuild? If I understand correctly, the compiler ran out of memory while compiling my project. So if I do a rebuild, which cleans all prior work, shouldn't it run out of memory the next time too, if I don't change anything?
To be on the safe side, I already have specified a value of 120 for Zm (ie Zm120 ) in all configurations of this project. Why do I get an error message with this lower value? Or is the suggested value of 114 just a wild guess of VS?
A PCH file should be generated only once. If you run into this error then you changed a .h file that's included in the PCH, non-zero odds that such a change triggers the error again of course. Ultimately this is likely to be a bad practice and you should trim the PCH to only use headers that never change. Windows.h is good, a library like Boost is good. Something like string.h is too small to bother. That doesn't trigger C3859.
@HansPassant Yes, I understand the concept of precompiled headers. But a rebuild should also rebuild the precompiled headers. Thus, if I change nothing at all (no file, no compiler options) and just hit "rebuild" the error should occur again, shouldn't it?
As to the /Zm part of the question, according to here (search for Ignoring the /Zm flag), beginning with MSVS 2015 the Zm flag should not be used anymore (there are exceptions of course) and the value reported by fatal error C3859 should be ignored.
+1 on the don't use /Zm comment. we just fixed out of memory problems with our projects by removing these options. it seems this may not work well with
I enountered this error for the first time today when I decided to build my DEBUG x64 project with the new "Clang-tidy" code analysis setting.
4 ответа
Я знаю, что это старый, но я оказался здесь, так что могу ответить.
Есть отличная статья о проблемах PCH здесь.
1) Почему это не происходит каждый раз, когда я выполняю перестройку?
Конечно, на этот вопрос сложно ответить. Поскольку это происходит не каждый раз, может быть несколько проблем. Скорее всего, это связано с выделением памяти. Из статьи:
- Фрагментация диапазонов адресов виртуальной памяти, необходимых для PCH перед CL.EXE сможет загрузить его в память.
- Отказ ОС Windows при больших нагрузках увеличить размер файла подкачки в течение определенного порогового времени.
c1xx: ошибка C3859: не удалось создать виртуальную память для PCH [. Project.vcxproj] c1xx: примечание: система вернула код 1455: файл подкачки слишком мал для завершения этой операции
Также может помочь установить PreferredToolArchtecture на x64:
Если вы используете MSBuild из командной строки, вы можете передать / p: PreferredToolArchtecture = x64 в MSBuild. Если вы создаете с помощью MSBuild из Visual Studio, вы можете отредактировать файл .vcxproj, включив в него PropertyGroup, содержащую это свойство.
Это легко упустить из виду, но такие проблемы также возникают, когда предварительно скомпилированный заголовок слишком велик. Также неплохо было бы провести небольшую уборку.
Просто вмешиваюсь в то, чем оказалось решение для меня. Похоже, что Visual Studio пыталась скомпилировать мою программу для нескольких архитектур, хотя я думал, что удалил профили, в диспетчере конфигурации была куча фиктивных записей для сборки в режиме x86. Для меня это было бесполезно, так как я хочу собирать только x64. После удаления этих записей программа снова скомпилировалась, и эта ошибка исчезла. Надеюсь, это кому-то поможет.
Еще одна причина этой проблемы. Я не совсем понимаю, как проект попал в это состояние, но он пытался использовать файлы PCH, для параметра «Файл предварительно скомпилированного заголовка» было установлено значение pch.h , но параметр «Вывод предварительно скомпилированного заголовка» чуть ниже был пусто.
Неудивительно, но Visual Studio очень сильно разошлась по этому поводу, в частности, выдавая многочисленные ошибки C3859 во время сборки.
Сортировка конфигурации проекта до «Наследовать» это значение исправила его.
Я столкнулся с этим, собирая большую базу кода на локальной виртуальной машине. Пытался увеличить размер файла подкачки и т. Д., Но ничего не вышло. Единственное, что сработало в моем случае, - это отключить динамическую память в настройке виртуальной машины Hyper-V и дать виртуальной машине больше ОЗУ, 8 ГБ -> 16 ГБ.
По-видимому, VS выделяет память заранее, поэтому он использует только начальное значение, данное виртуальной машине, и не запускает никаких изменений динамической памяти.
Но в настоящее время есть две проблемы с этим:
Почему это не происходит каждый раз Я делаю перестройку? Если я правильно понимаю, компилятору не хватило памяти при компиляции моего проекта. Так что, если я сделаю перестройку, которая очищает всю предыдущую работу, разве в следующий раз ей не хватит памяти, если я ничего не изменю?
Вопрос
We have moved our VC++ projects to VS2019 and when tried to build the project we got the following errors after compiling some files.
3>c1xx: error C3859: Failed to create virtual memory for PCH
3>c1xx: note: PCH: Unable to get the requested block of memory
I have gone through the forums as mentioned by the ciompiler but still getting the same error
Can you please help in resolving these issues?
Читайте также: