Внутренняя ошибка компилятора c clr

I have just upgraded Microsoft Visual Studio Enterprise 2015 from Update 2 to Update 3 and now I am getting the following error:

fatal error C1001: An internal error has occurred in the compiler.
(compiler file ‘f:ddvctoolscompilerutcsrcp2wvmmdmiscw.c’, line 2687)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++ Help menu, or open the Technical Support help file for more information

The location is the first line which includes a header. The project has settings

/FR»x64Debug» /GS /W3 /Zc:wchar_t /Zi /Od /Fd»x64Debugvc140.pdb»
/Zc:inline /fp:precise /D «WIN32» /D «_DEBUG» /D «_WINDLL» /D
«_UNICODE» /D «UNICODE» /errorReport:prompt /WX- /Zc:forScope /clr
[some /FU»…»] /MDd /Fa»x64Debug» /EHa /nologo /Fo»x64Debug»
/Fp»….pch»

How do I make my project build again?

Leo Chapiro's user avatar

Leo Chapiro

13.6k7 gold badges60 silver badges92 bronze badges

asked Jul 8, 2016 at 11:59

MciprianM's user avatar

4

C1001 basically indicates a compiler crash, i.e. you might have created valid C/C++ code that triggers a bug in the VC compiler. It would probably be a good idea to submit a bug report via https://connect.microsoft.com/VisualStudio/Feedback for further investigation by Microsoft.

I myself just ran into a C1001 while compiling OpenCV with Visual Studio Express 2015 Update 3. In my case, the C1001 error message also pointed me to the OpenCV core code line that triggers the compiler crash. After looking into the actual code semantics at that particular line, I suspected the compiler’s floating point handling to be the root cause of the issue. It was dealing with a big, hard-coded double array lookup table which might have caused rounding issues. (Just in case somebody googles for this, I am listing the reference here: opencv_core, mathfuncs_core.cpp, line 1261, macro-expansion of LOGTAB_TRANSLATE).

In my case, setting the compiler’s floating-point model from ‘precise’ to ‘strict’ resolved the C1001 issue. However, as you haven’t included a code fragment of the lines that cause the C1001 to raise, it’s difficult to say whether the above will fix your issue as well. If you want to give it a try, you can find the compiler switch in your project settings / C/C++ / Code Generation tab. Instead of Precise (/fp:precise), select Strict (/fp:strict) as Floating Point Model. This change may affect the performance of your code, but should not affect its precision. See https://msdn.microsoft.com/en-us/library/e7s85ffb.aspx for further information.

answered Jul 12, 2016 at 20:51

Andreas's user avatar

1

According to visual studio developers community,
this issue was fixed and closed (on July 2019) and should not appear at latest VS version. So upgrading to the latest version should solve the issue.

However, I’ve just now upgraded my VS to the latest version (16.7.1) and I still encounter this problem getting fatal error C1001: Internal compiler error.

An edit: See the comments below, people say the issue also appears at VS 2022 17.3.6 and at VS 2019 16.9.4

Finally, the following solution worked for me:
change the optimization option (project properties->C/C++->optimization) to ‘Custom’ and at (project properties->C/C++->command line’) add additional options of ‘/Ob2, /Oi, /Os, /Oy’.

taken from: Visual studio in stuck Generating code

answered Aug 16, 2020 at 10:21

Eliyahu Machluf's user avatar

2

I have just upgraded Microsoft Visual Studio Enterprise 2015 from Update 2 to Update 3 and now I am getting the following error:

fatal error C1001: An internal error has occurred in the compiler.
(compiler file ‘f:ddvctoolscompilerutcsrcp2wvmmdmiscw.c’, line 2687)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++ Help menu, or open the Technical Support help file for more information

The location is the first line which includes a header. The project has settings

/FR»x64Debug» /GS /W3 /Zc:wchar_t /Zi /Od /Fd»x64Debugvc140.pdb»
/Zc:inline /fp:precise /D «WIN32» /D «_DEBUG» /D «_WINDLL» /D
«_UNICODE» /D «UNICODE» /errorReport:prompt /WX- /Zc:forScope /clr
[some /FU»…»] /MDd /Fa»x64Debug» /EHa /nologo /Fo»x64Debug»
/Fp»….pch»

How do I make my project build again?

Leo Chapiro's user avatar

Leo Chapiro

13.6k7 gold badges60 silver badges92 bronze badges

asked Jul 8, 2016 at 11:59

MciprianM's user avatar

4

C1001 basically indicates a compiler crash, i.e. you might have created valid C/C++ code that triggers a bug in the VC compiler. It would probably be a good idea to submit a bug report via https://connect.microsoft.com/VisualStudio/Feedback for further investigation by Microsoft.

I myself just ran into a C1001 while compiling OpenCV with Visual Studio Express 2015 Update 3. In my case, the C1001 error message also pointed me to the OpenCV core code line that triggers the compiler crash. After looking into the actual code semantics at that particular line, I suspected the compiler’s floating point handling to be the root cause of the issue. It was dealing with a big, hard-coded double array lookup table which might have caused rounding issues. (Just in case somebody googles for this, I am listing the reference here: opencv_core, mathfuncs_core.cpp, line 1261, macro-expansion of LOGTAB_TRANSLATE).

In my case, setting the compiler’s floating-point model from ‘precise’ to ‘strict’ resolved the C1001 issue. However, as you haven’t included a code fragment of the lines that cause the C1001 to raise, it’s difficult to say whether the above will fix your issue as well. If you want to give it a try, you can find the compiler switch in your project settings / C/C++ / Code Generation tab. Instead of Precise (/fp:precise), select Strict (/fp:strict) as Floating Point Model. This change may affect the performance of your code, but should not affect its precision. See https://msdn.microsoft.com/en-us/library/e7s85ffb.aspx for further information.

answered Jul 12, 2016 at 20:51

Andreas's user avatar

1

According to visual studio developers community,
this issue was fixed and closed (on July 2019) and should not appear at latest VS version. So upgrading to the latest version should solve the issue.

However, I’ve just now upgraded my VS to the latest version (16.7.1) and I still encounter this problem getting fatal error C1001: Internal compiler error.

An edit: See the comments below, people say the issue also appears at VS 2022 17.3.6 and at VS 2019 16.9.4

Finally, the following solution worked for me:
change the optimization option (project properties->C/C++->optimization) to ‘Custom’ and at (project properties->C/C++->command line’) add additional options of ‘/Ob2, /Oi, /Os, /Oy’.

taken from: Visual studio in stuck Generating code

answered Aug 16, 2020 at 10:21

Eliyahu Machluf's user avatar

2

While compiling on x64 plattform I am getting following error:

c:codavs05hpsw-scovpacctoolscodaaccesstestcoda_access.cpp(1572): fatal error C1001: An internal error has occurred in the compiler.

(compiler file 'f:ddvctoolscompilerutcsrcp2sizeopt.c', line 55)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information

------ Build started: Project: asyncexample, Configuration: Release Win32 ------

If I change settings to preprocessor file (Yes) i am not getting any error.

About my environment: Upgrading Microsoft Visual Studio 2005 to 2010

Please help.

LuFFy's user avatar

LuFFy

8,33110 gold badges38 silver badges59 bronze badges

asked Aug 16, 2011 at 10:01

venkat's user avatar

4

I have had this problem with VS2015 while building locally in Windows.

In order to solve it, I deleted my build folder (Output Directory as seen in Properties/General) and rebuilt the project.

This always seems to help when strange things happen during the build.

answered Aug 2, 2017 at 8:36

Autex's user avatar

AutexAutex

1971 silver badge12 bronze badges

I’ve encountered this error many times in VC++. Do the following steps. They’ve sometimes helped me with this issue:

  1. Take a look at the exact location, pointed out by compiler error.
  2. Find any external types or classes used there at that location.
  3. Change the order of “include path” of those files found in step 2 and rebuild the solution.
  4. I hope that help !!!!

answered Aug 16, 2011 at 10:17

TonySalimi's user avatar

TonySalimiTonySalimi

8,1044 gold badges32 silver badges62 bronze badges

0

I am getting same error with VC2012. Setting up the project properties Optimization to Disabled (/Od) resolved the issue.

answered Feb 3, 2014 at 12:27

anil's user avatar

anilanil

9711 gold badge11 silver badges23 bronze badges

2

In my solution, i’ve removed output dll file of the project, and I’ve made project rebuild.

answered Apr 27, 2017 at 16:52

Paweł Iwaneczko's user avatar

Paweł IwaneczkoPaweł Iwaneczko

8131 gold badge10 silver badges13 bronze badges

I encountered the same error and spent quite a bit of time hunting for the problem. Finally I discovered that function that the error was pointing to had an infinite while loop. Fixed that and the error went away.

answered Mar 7, 2014 at 1:45

quitePro's user avatar

quiteProquitePro

5465 silver badges3 bronze badges

In my case was the use of a static lambda function with a QStringList argument. If I commented the regions where the QStringList was used the file compiled, otherwise the compiler reported the C1001 error. Changing the lambda function to non-static solved the problem (obviously other options could have been to use a global function within an anonymous namespace or a static private method of the class).

answered Jan 30, 2017 at 10:57

cbuchart's user avatar

cbuchartcbuchart

10.5k7 gold badges53 silver badges87 bronze badges

I got this error using boost library with VS2017. Cleaning the solution and rebuilding it, solved the problem.

answered Feb 27, 2018 at 16:06

Tides's user avatar

TidesTides

11111 bronze badges

I also had this problem while upgrading from VS2008 to VS2010.

To fix, I have to install a VS2008 patch (KB976656).

Maybe there is a similar patch for VS2005 ?

answered Jan 9, 2013 at 16:33

Philippe's user avatar

I got the same error, but with a different file referenced in the error message, on a VS 2015 / x64 / Win7 build. In my case the file was main.cpp. Fixing it for me was as easy as doing a rebuild all (and finding something else to do while the million plus lines of code got processed).

Update: it turns out the root cause is my hard drive is failing. After other symptoms prompted me to run chkdsk, I discovered that most of the bad sectors that were replaced were in .obj, .pdb, and other compiler-generated files.

answered Sep 6, 2016 at 22:54

hlongmore's user avatar

hlongmorehlongmore

1,53525 silver badges27 bronze badges

I got this one with code during refactoring with a lack of care (and with templates, it case that was what made an ICE rather than a normal compile time error)

Simplified code:

void myFunction() {
    using std::is_same_v;
    for (auto i ...) {
       myOtherFunction(..., i);
    }
}

void myOtherFunction(..., size_t idx) {
    // no statement using std::is_same_v;
    if constexpr (is_same_v<T, char>) {
        ...
    }
}

answered Nov 27, 2017 at 5:36

chrisb2244's user avatar

chrisb2244chrisb2244

2,91022 silver badges43 bronze badges

I had this error when I was compiling to a x64 target.
Changing to x86 let me compile the program.

answered Oct 17, 2017 at 14:38

Robert Andrzejuk's user avatar

Robert AndrzejukRobert Andrzejuk

4,9932 gold badges23 silver badges30 bronze badges

Sometimes helps reordering the code. I had once this error in Visual Studio 2013 and this was only solved by reordering the members of the class (I had an enum member, few strings members and some more enum members of the same enum class. It only compiled after I’ve put the enum members first).

answered Jun 12, 2019 at 13:51

Liviu Stancu's user avatar

In my case, this was causing the problem:

std::count_if(data.cbegin(), data.cend(), [](const auto& el) { return el.t == t; });

Changing auto to the explicit type fixed the problem.

answered Nov 13, 2019 at 15:06

The Quantum Physicist's user avatar

Had similar problem with Visual Studio 2017 after switching to C++17:

boost/mpl/aux_/preprocessed/plain/full_lambda.hpp(203): fatal error C1001: An internal error has occurred in the compiler.
1>(compiler file 'msc1.cpp', line 1518)
1> To work around this problem, try simplifying or changing the program near the locations listed above.

Solved by using Visual Studio 2019.

answered Jan 15, 2020 at 12:04

Dmytro's user avatar

DmytroDmytro

1,25216 silver badges21 bronze badges

I first encountered this problem when i was trying to allocate memory to a char* using new char['size']{'text'}, but removing the braces and the text between them solved my problem (just new char['size'];)

answered Jun 19, 2022 at 16:38

Vlad Hagimasuri's user avatar

Another fix on Windows 10 if you have WSL installed is to disable LxssManager service and reboot the PC.

answered Aug 21, 2022 at 19:10

Vaan's user avatar

При попытке скомпилировать код на языке c ++, включая библиотеки API sfml, возникает следующая ошибка:

Внутренняя ошибка компилятора в C: Program Files (x86) Microsoft Visual Studio 2017 Community VC Tools MSVC 14.10.25017 bin HostX86 x86 CL.exe ‘
Выберите команду технической поддержки в меню справки Visual C ++ или откройте файл справочной службы для получения дополнительной информации.
C: Program Files (x86) Microsoft Visual Studio 2017 Community Common7 IDE VC VCTargets Microsoft.CppCommon.targets (358,5): ошибка MSB6006: «CL.exe» завершен с кодом 2.

Я искал в Интернете решение для этого, но я не мог решить это …
Когда я попросил помощи на форуме visual studio, я получил единственный ответ:

«Спасибо за ваш отзыв! Эта проблема была исправлена, и она будет доступна в следующем обновлении Visual Studio 2017. Спасибо за помощь в создании лучшей Visual Studio! »

Вот код с ошибкой:

#include <SFMLGraphics.hpp>

int main() {

sf::RenderWindow window(sf::VideoMode(640, 480), "Bouncing Mushroom");

sf::Texture mushroomTexture;
mushroomTexture.loadFromFile("mushroom.png");
sf::Sprite mushroom(mushroomTexture);
sf::Vector2u size = mushroomTexture.getSize;
mushroom.setOrigin(size.x / 2, size.y / 2);
sf::Vector2f increment(0.4f, 0.4f);

while (window.isOpen())
{
sf::Event evnt;
while (window.pollEvent(evnt))
{
if (evnt.type == sf::Event::Closed)
window.close();
}

if ((mushroom.getPosition().x + (size.x / 2) > window.getSize().x && increment.x > 0) || (mushroom.getPosition().x - (size.x / 2) < 0 && increment.x < 0))
{
// Reverse the direction on X axis.
increment.x = -increment.x;
}

if ((mushroom.getPosition().y + (size.y / 2) > window.getSize().y && increment.y > 0) || (mushroom.getPosition().y - (size.y / 2) < 0 && increment.y < 0))
{
// Reverse the direction on Y axis.
increment.y = -increment.y;
}

mushroom.setPosition(mushroom.getPosition() + increment);
window.clear(sf::Color(16, 16, 16, 255)); // Dark gray.
window.draw(mushroom); // Drawing our sprite.
window.display();

}

0

Решение

Хорошо, если это буквально код, который вы пытаетесь скомпилировать, есть две синтаксические ошибки:

1.- В строке 10

mushroomTexture.getSize;

getSize — это метод из класса sf :: Texture, не являющийся членом, поэтому просто добавьте ();

mushroomTexture.getSize();

2.- В конце основной функции отсутствует «}». (Я думаю, что вы просто не скопировали это правильно, но все равно проверьте это.

    window.display();

}
} <---- end of main() missing

Если это не решило вашу проблему, возможно, у вас неправильные SFML-файлы для вашей версии VS, если вы используете VS 2017, загрузите Visual C ++ 14 (2015) — 32-разрядная версия версия https://www.sfml-dev.org/download/sfml/2.4.2/ это работает для VS 2015 & 2017 (я использовал его на VS 2017, чтобы проверить ваш пример, и он запустился без проблем).

0

Другие решения

Внутренние ошибки компилятора обычно означают, что с компилятором что-то не так, и, видя, что это VS 2017, я не удивлюсь, если это будет ошибка, так как это более новая версия VS. Тем временем вы можете попытаться найти строку кода, которая вызывает эту ошибку, и найти альтернативное решение или использовать более старую версию Visual Studio.

1

Я скачал Visual Studio 2015 и попытался запустить код в нем (все учебные пособия по sfml сделаны в версии 2015) и запустить код.

Я считаю, что проблема в том, что библиотеки sfml еще не совместимы с vs 2017, поэтому решение простое:

-использовать Visual Studio 2015 или

-перекомпилировать библиотеки для Visual Studio 2017 (я не знаю, как это сделать)

0

Version Used:
Microsoft Visual Studio Enterprise 2017
Version 15.0.26228.9 D15RTWSVC
Microsoft .NET Framework
Version 4.6.01586

Project target framework:
.NETCoreApp 1.1
.NET Framework 4.5.2

Steps to Reproduce:

  1. Paste the following methods:
    class Program
    {
        static void M(out int x) { x = 10; }

        static void Main(string[] args)
        {
        }
    }
  1. Run the program and put a break point in the start of method «Main»

  2. When break point hit, paste the following statement in Watch window or in the Immediate window:

new Func<int>(delegate { int x; var y = new Func<int>(() => { M(out x); return 1; }).Invoke(); return y; }).Invoke() 

Expected Behavior:
«1» will printed

Actual Behavior:
«Internal error in the C# compiler» printed

StackTrace:
«The given key was not present in the dictionary.»

>	mscorlib.dll!System.Collections.Generic.Dictionary<System.__Canon, System.__Canon>.this[System.__Canon].get(System.__Canon key)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.RecordVarRead(Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol local)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitLocal(Microsoft.CodeAnalysis.CSharp.BoundLocal node)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundLocal.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionCore(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpression(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitAssignmentOperator(Microsoft.CodeAnalysis.CSharp.BoundAssignmentOperator node)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundAssignmentOperator.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionCore(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionCoreWithStackGuard(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpression(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionStatement(Microsoft.CodeAnalysis.CSharp.BoundExpressionStatement node)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundExpressionStatement.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitStatement(Microsoft.CodeAnalysis.CSharp.BoundNode node)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.Visit(Microsoft.CodeAnalysis.CSharp.BoundNode node)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundTreeRewriter.DoVisitList<Microsoft.CodeAnalysis.CSharp.BoundStatement>(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CSharp.BoundStatement> list)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundTreeRewriter.VisitBlock(Microsoft.CodeAnalysis.CSharp.BoundBlock node)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitBlock(Microsoft.CodeAnalysis.CSharp.BoundBlock node)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundBlock.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitStatement(Microsoft.CodeAnalysis.CSharp.BoundNode node)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.Visit(Microsoft.CodeAnalysis.CSharp.BoundNode node)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.Analyze(Microsoft.CodeAnalysis.CSharp.BoundNode node, System.Collections.Generic.Dictionary<Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol, Microsoft.CodeAnalysis.CSharp.CodeGen.LocalDefUseInfo> locals, bool debugFriendly)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.Optimizer.Optimize(Microsoft.CodeAnalysis.CSharp.BoundStatement src, bool debugFriendly, out System.Collections.Generic.HashSet<Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol> stackLocals)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.CodeGenerator.CodeGenerator(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method, Microsoft.CodeAnalysis.CSharp.BoundStatement boundBody, Microsoft.CodeAnalysis.CodeGen.ILBuilder builder, Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder moduleBuilder, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, Microsoft.CodeAnalysis.OptimizationLevel optimizations, bool emittingPdb)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder moduleBuilder, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method, int methodOrdinal, Microsoft.CodeAnalysis.CSharp.BoundStatement block, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeGen.LambdaDebugInfo> lambdaDebugInfo, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeGen.ClosureDebugInfo> closureDebugInfo, Microsoft.CodeAnalysis.CSharp.StateMachineTypeSymbol stateMachineTypeOpt, Microsoft.CodeAnalysis.CodeGen.VariableSlotAllocator variableSlotAllocatorOpt, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, Microsoft.CodeAnalysis.CodeGen.DebugDocumentProvider debugDocumentProvider, Microsoft.CodeAnalysis.CSharp.ImportChain importChainOpt, bool emittingPdb, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeGen.SourceSpan> dynamicAnalysisSpans)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileSynthesizedMethods(Microsoft.CodeAnalysis.CSharp.TypeCompilationState compilationState)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileSynthesizedMethods(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol> additionalTypes, Microsoft.CodeAnalysis.DiagnosticBag diagnostics)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileMethodBodies(Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation, Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder moduleBeingBuiltOpt, bool generateDebugInfo, bool hasDeclarationErrors, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, System.Predicate<Microsoft.CodeAnalysis.CSharp.Symbol> filterOpt, System.Threading.CancellationToken cancellationToken)	Unknown
Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CSharpCompilation.CompileMethods(Microsoft.CodeAnalysis.Emit.CommonPEModuleBuilder moduleBuilder, bool emittingPdb, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, System.Predicate<Microsoft.CodeAnalysis.ISymbol> filterOpt, System.Threading.CancellationToken cancellationToken)	Unknown
Microsoft.CodeAnalysis.dll!Microsoft.CodeAnalysis.Compilation.Compile(Microsoft.CodeAnalysis.Emit.CommonPEModuleBuilder moduleBuilder, bool emittingPdb, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, System.Predicate<Microsoft.CodeAnalysis.ISymbol> filterOpt, System.Threading.CancellationToken cancellationToken)	Unknown
Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.CompilationContext.CompileExpression(string typeName, string methodName, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, out Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProperties resultProperties)	Unknown
Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.EvaluationContext.CompileExpression(string expr, Microsoft.VisualStudio.Debugger.Evaluation.DkmEvaluationFlags compilationFlags, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.Alias> aliases, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, out Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProperties resultProperties, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData)	Unknown
Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmClrExpressionCompiler.CompileExpression.AnonymousMethod__1(Microsoft.CodeAnalysis.ExpressionEvaluator.EvaluationContextBase context, Microsoft.CodeAnalysis.DiagnosticBag diagnostics)	Unknown
Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileWithRetry<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult>(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.MetadataBlock> metadataBlocks, Microsoft.CodeAnalysis.DiagnosticFormatter formatter, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CreateContextDelegate createContext, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileDelegate<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult> compile, Microsoft.CodeAnalysis.ExpressionEvaluator.DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage)	Unknown
Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileWithRetry<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult>(Microsoft.VisualStudio.Debugger.Clr.DkmClrModuleInstance moduleInstance, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.MetadataBlock> metadataBlocks, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CreateContextDelegate createContext, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileDelegate<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult> compile, out string errorMessage)	Unknown
Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmClrExpressionCompiler.CompileExpression(Microsoft.VisualStudio.Debugger.Evaluation.DkmLanguageExpression expression, Microsoft.VisualStudio.Debugger.Clr.DkmClrInstructionAddress instructionAddress, Microsoft.VisualStudio.Debugger.Evaluation.DkmInspectionContext inspectionContext, out string error, out Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation.DkmCompiledClrInspectionQuery result)	Unknown
Microsoft.VisualStudio.Debugger.Engine.dll!Microsoft.VisualStudio.Debugger.EntryPoint.IDkmClrExpressionCompiler_CompileExpression(System.IntPtr pvClassInfo, System.IntPtr Expression, System.IntPtr InstructionAddress, System.IntPtr InspectionContext, ref System.IntPtr Error, ref System.IntPtr Result)	Unknown
[Native to Managed Transition]	
[Managed to Native Transition]	
Microsoft.VisualStudio.Debugger.Engine.dll!Microsoft.VisualStudio.Debugger.Evaluation.DkmLanguageExpression.CompileExpression(Microsoft.VisualStudio.Debugger.Clr.DkmClrInstructionAddress InstructionAddress, Microsoft.VisualStudio.Debugger.Evaluation.DkmInspectionContext InspectionContext, out string Error, out Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation.DkmCompiledClrInspectionQuery Result)	Unknown
vsdebugeng.manimpl.dll!VSDebugEngine.ManagedEE.EntryPoint.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmLanguageExpressionEvaluator.EvaluateExpression(Microsoft.VisualStudio.Debugger.Evaluation.DkmInspectionContext inspectionContext, Microsoft.VisualStudio.Debugger.DkmWorkList workList, Microsoft.VisualStudio.Debugger.Evaluation.DkmLanguageExpression expression, Microsoft.VisualStudio.Debugger.CallStack.DkmStackWalkFrame stackFrame, Microsoft.VisualStudio.Debugger.DkmCompletionRoutine<Microsoft.VisualStudio.Debugger.Evaluation.DkmEvaluateExpressionAsyncResult> completionRoutine)	Unknown
Microsoft.VisualStudio.Debugger.Engine.dll!Microsoft.VisualStudio.Debugger.EntryPoint.IDkmLanguageExpressionEvaluator_EvaluateExpression(System.IntPtr pvClassInfo, System.IntPtr InspectionContext, System.IntPtr WorkList, System.IntPtr Expression, System.IntPtr StackFrame, System.IntPtr CompletionRoutine)	Unknown

Hi Folks,

I got some code that works fine in Debug-Mode but causes a compiler error in Release-Mode:

const

float fx = pfx<0?0:(pfx>width-1?width-1:pfx), fy = pfy<0?0:(pfy>height-1?height-1:pfy);

const unsigned int x = (unsigned int)fx;

const unsigned int px = (int)x-1>=0?x-1:0, nx = x+1<width?x+1:width-1, ax = nx+1<width?nx+1:width-1;

const unsigned int y = (unsigned int)fy, py = (int)y-1>=0?y-1:0, ny = y+1<height?y+1:height-1, ay = ny+1<height?ny+1:height-1;

const float dx = fx-x;

const float dy = fy-y;

const T& a = (*this)(px,py,z);

const T& b = (*this)(x,py,z);

const T& c = (*this)(nx,py,z);

const T& d = (*this)(ax,py,z);

const T& e = (*this)(px, y,z);

const T& f = (*this)(x, y,z);

const T& g = (*this)(nx, y,z);

const T& h = (*this)(ax, y,z);

const T& i = (*this)(px,ny,z);

const T& j = (*this)(x,ny,z);

const T& k = (*this)(nx,ny,z);

const T& l = (*this)(ax,ny,z);

const T& m = (*this)(px,ay,z);

const T& n = (*this)(x,ay,z);

const T& o = (*this)(nx,ay,z);

const T& p = (*this)(ax,ay,z);

>> This Line seems to cause the compiler error:

const

double A = dx*dx*dx*(2*(b-c)+0.5*(c-a+d-b)) + dx*dx*(2*c-2.5*b+a-0.5*d) + dx*0.5*(c-a) + b;

This is, what VS2005 has to say about the error:

fatal error C1001: An internal error has occurred in the compiler.

(compiler file ‘f:rtmvctoolscompilerutcsrcP2main.c[0xCCCCCCCC:0xCCCCCCCC]’, line 182)

To work around this problem, try simplifying or changing the program near the locations listed above.

Please choose the Technical Support command on the Visual C++

Help menu, or open the Technical Support help file for more information

LINK : fatal error LNK1000: Internal error during IMAGE::BuildImage

Version 8.00.50727.42

ExceptionCode = C0000005

ExceptionFlags = 00000000

ExceptionAddress = CCCCCCCC

NumberParameters = 00000002

ExceptionInformation[ 0] = 00000000

ExceptionInformation[ 1] = CCCCCCCC

CONTEXT:

Eax = 0000000C Esp = 0012EC50

Ebx = 0373ED0D Ebp = 00004004

Ecx = 037431F8 Esi = 037431F8

Edx = 00004004 Edi = 03743B08

Eip = CCCCCCCC EFlags = 00010206

SegCs = 0000001B SegDs = 00000023

SegSs = 00000023 SegEs = 00000023

SegFs = 0000003B SegGs = 00000000

Dr0 = 00000000 Dr3 = 00000000

Dr1 = 00000000 Dr6 = 00000000

Dr2 = 00000000 Dr7 = 00000000

I already tried to simplify my code (before there where several constant definitions per line), I already tried reordering my code and I already tried to turn off all possible optimizations. (although I need them badly) Could anybody please tell me, how to face an error like this?

Best Regards

LastFreeName

Hi Folks,

I got some code that works fine in Debug-Mode but causes a compiler error in Release-Mode:

const

float fx = pfx<0?0:(pfx>width-1?width-1:pfx), fy = pfy<0?0:(pfy>height-1?height-1:pfy);

const unsigned int x = (unsigned int)fx;

const unsigned int px = (int)x-1>=0?x-1:0, nx = x+1<width?x+1:width-1, ax = nx+1<width?nx+1:width-1;

const unsigned int y = (unsigned int)fy, py = (int)y-1>=0?y-1:0, ny = y+1<height?y+1:height-1, ay = ny+1<height?ny+1:height-1;

const float dx = fx-x;

const float dy = fy-y;

const T& a = (*this)(px,py,z);

const T& b = (*this)(x,py,z);

const T& c = (*this)(nx,py,z);

const T& d = (*this)(ax,py,z);

const T& e = (*this)(px, y,z);

const T& f = (*this)(x, y,z);

const T& g = (*this)(nx, y,z);

const T& h = (*this)(ax, y,z);

const T& i = (*this)(px,ny,z);

const T& j = (*this)(x,ny,z);

const T& k = (*this)(nx,ny,z);

const T& l = (*this)(ax,ny,z);

const T& m = (*this)(px,ay,z);

const T& n = (*this)(x,ay,z);

const T& o = (*this)(nx,ay,z);

const T& p = (*this)(ax,ay,z);

>> This Line seems to cause the compiler error:

const

double A = dx*dx*dx*(2*(b-c)+0.5*(c-a+d-b)) + dx*dx*(2*c-2.5*b+a-0.5*d) + dx*0.5*(c-a) + b;

This is, what VS2005 has to say about the error:

fatal error C1001: An internal error has occurred in the compiler.

(compiler file ‘f:rtmvctoolscompilerutcsrcP2main.c[0xCCCCCCCC:0xCCCCCCCC]’, line 182)

To work around this problem, try simplifying or changing the program near the locations listed above.

Please choose the Technical Support command on the Visual C++

Help menu, or open the Technical Support help file for more information

LINK : fatal error LNK1000: Internal error during IMAGE::BuildImage

Version 8.00.50727.42

ExceptionCode = C0000005

ExceptionFlags = 00000000

ExceptionAddress = CCCCCCCC

NumberParameters = 00000002

ExceptionInformation[ 0] = 00000000

ExceptionInformation[ 1] = CCCCCCCC

CONTEXT:

Eax = 0000000C Esp = 0012EC50

Ebx = 0373ED0D Ebp = 00004004

Ecx = 037431F8 Esi = 037431F8

Edx = 00004004 Edi = 03743B08

Eip = CCCCCCCC EFlags = 00010206

SegCs = 0000001B SegDs = 00000023

SegSs = 00000023 SegEs = 00000023

SegFs = 0000003B SegGs = 00000000

Dr0 = 00000000 Dr3 = 00000000

Dr1 = 00000000 Dr6 = 00000000

Dr2 = 00000000 Dr7 = 00000000

I already tried to simplify my code (before there where several constant definitions per line), I already tried reordering my code and I already tried to turn off all possible optimizations. (although I need them badly) Could anybody please tell me, how to face an error like this?

Best Regards

LastFreeName

Вопрос:

Я обновился до версии Visual Studio 2015 Update 1, но теперь я получаю следующую ошибку, когда когда-либо компилирую конфигурацию выпуска для 64-битного, все работает для 32-битных и/или отладочных сборников.

fatal error C1001: An internal error has occurred in the compiler.
(compiler file 'f:ddvctoolscompilerutcsrcp2main.c', line 246)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
link!InvokeCompilerPass()+0x2d4bd
link!DllGetC2Telemetry()+0xae663

Ошибка возникает не для каждого из моих проектов, а для некоторых.

Упрощение указанного местоположения на самом деле невозможно, место, где происходит сбой компилятора, обычно является просто простой функцией одной строки, также изменение этого кода приводит к той же ошибке в другом месте. Насколько я могу предположить, он должен что-то сделать с оптимизацией и вложением. Но изменение параметров оптимизации тоже не помогло.

Может ли кто-нибудь указать мне, как найти реальный проблемный код или некоторые параметры компилятора, чтобы избежать этой ошибки?

Я не хотел бы думать, что обновление не работает.

Лучший ответ:

Мы столкнулись с C1001 в одном из наших проектов после обновления до обновления MSVC 2015.

Через пробную ошибку мы идентифицировали свойство ClCompile/AssemblerOutput как виновника в нашем случае. Удаление этого свойства больше не вызвало C1001

Источник: https://trac.osgeo.org/mapguide/ticket/2580

Обновление 6 апреля 2016 года: я попытался создать этот же проект с обновлением MSVC 2015 Update 2 без свойства ClCompile/AssemblerOutput, и я больше не получаю C1001 при создании этого проекта. Я думаю, что обновление 2 исправлено.

Ответ №1

Попробуйте настроить при оптимизации проекта на Disabled (/Od), это может решить проблему.

Чтобы установить этот параметр компилятора в Visual Studio среда

  • Откройте диалоговое окно “Страницы свойств проекта”.
  • Щелкните папку C/С++.
  • Перейдите на страницу свойств оптимизации.
  • Измените свойство Оптимизация.

Источник: https://msdn.microsoft.com/en-us/library/aafb762y.aspx

Я надеюсь, что мой ответ будет поддерживать вашу проблему.

Ответ №2

Repro компилирует JSON lib в Release | x64. Конфигурация была установлена ​​на максимальной скорости (/O2), но General использовал “Нет оптимизации всей программы”.
Переход от “Нет оптимизации всей программы” для использования генерации кода времени ссылки (я считаю, что флаг является /LTCG ) успешно завершен.

Ответ №3

Я также столкнулся с этой проблемой, пока мы конвертировали нашу кодовую базу компании с VC10 на VC14. В нашем случае проблема возникла, когда таргетинг на x64 и SEH (/EHa) был включен одновременно с выходом Ассемблера. Ошибка произошла в нашем случае, когда в скомпилированном коде был вызван оператор ввода потока (т.е. std::cout::operator<<).

В нашем случае динамическая привязка ЭЛТ вместо статической привязки (т.е. /MT вместо /MD), по-видимому, обойти проблему без отключения выхода ассемблера. Это не первая проблема, которую я нашел со статически связанным CRT (например, это также вызвало отсутствующие курсоры при изменении размеров окон CPane в MFC).

Об этом сообщили Microsoft (https://connect.microsoft.com/VisualStudio/feedback/details/2216490/compiler-crashes-at-string-stream-insertion-operator), но через два с половиной месяца оказалось, что они даже не выглядели на нем…

Изменить: VS2015 Update 2, согласно Micrsoft, исправил эту проблему. Он протестирован как исправленный на нашей кодовой базе.

I have just upgraded Microsoft Visual Studio Enterprise 2015 from Update 2 to Update 3 and now I am getting the following error:

fatal error C1001: An internal error has occurred in the compiler.
(compiler file ‘f:ddvctoolscompilerutcsrcp2wvmmdmiscw.c’, line 2687)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++ Help menu, or open the Technical Support help file for more information

The location is the first line which includes a header. The project has settings

/FR»x64Debug» /GS /W3 /Zc:wchar_t /Zi /Od /Fd»x64Debugvc140.pdb»
/Zc:inline /fp:precise /D «WIN32» /D «_DEBUG» /D «_WINDLL» /D
«_UNICODE» /D «UNICODE» /errorReport:prompt /WX- /Zc:forScope /clr
[some /FU»…»] /MDd /Fa»x64Debug» /EHa /nologo /Fo»x64Debug»
/Fp»….pch»

How do I make my project build again?

Leo Chapiro's user avatar

Leo Chapiro

13.5k7 gold badges60 silver badges91 bronze badges

asked Jul 8, 2016 at 11:59

MciprianM's user avatar

4

C1001 basically indicates a compiler crash, i.e. you might have created valid C/C++ code that triggers a bug in the VC compiler. It would probably be a good idea to submit a bug report via https://connect.microsoft.com/VisualStudio/Feedback for further investigation by Microsoft.

I myself just ran into a C1001 while compiling OpenCV with Visual Studio Express 2015 Update 3. In my case, the C1001 error message also pointed me to the OpenCV core code line that triggers the compiler crash. After looking into the actual code semantics at that particular line, I suspected the compiler’s floating point handling to be the root cause of the issue. It was dealing with a big, hard-coded double array lookup table which might have caused rounding issues. (Just in case somebody googles for this, I am listing the reference here: opencv_core, mathfuncs_core.cpp, line 1261, macro-expansion of LOGTAB_TRANSLATE).

In my case, setting the compiler’s floating-point model from ‘precise’ to ‘strict’ resolved the C1001 issue. However, as you haven’t included a code fragment of the lines that cause the C1001 to raise, it’s difficult to say whether the above will fix your issue as well. If you want to give it a try, you can find the compiler switch in your project settings / C/C++ / Code Generation tab. Instead of Precise (/fp:precise), select Strict (/fp:strict) as Floating Point Model. This change may affect the performance of your code, but should not affect its precision. See https://msdn.microsoft.com/en-us/library/e7s85ffb.aspx for further information.

answered Jul 12, 2016 at 20:51

Andreas's user avatar

1

According to visual studio developers community,
this issue was fixed and closed (on July 2019) and should not appear at latest VS version. So upgrading to the latest version should solve the issue.

However, I’ve just now upgraded my VS to the latest version (16.7.1) and I still encounter this problem getting fatal error C1001: Internal compiler error.

An edit: See the comments below, people say the issue also appears at VS 2022 17.3.6 and at VS 2019 16.9.4

Finally, the following solution worked for me:
change the optimization option (project properties->C/C++->optimization) to ‘Custom’ and at (project properties->C/C++->command line’) add additional options of ‘/Ob2, /Oi, /Os, /Oy’.

taken from: Visual studio in stuck Generating code

answered Aug 16, 2020 at 10:21

Eliyahu Machluf's user avatar

2

I have just upgraded Microsoft Visual Studio Enterprise 2015 from Update 2 to Update 3 and now I am getting the following error:

fatal error C1001: An internal error has occurred in the compiler.
(compiler file ‘f:ddvctoolscompilerutcsrcp2wvmmdmiscw.c’, line 2687)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++ Help menu, or open the Technical Support help file for more information

The location is the first line which includes a header. The project has settings

/FR»x64Debug» /GS /W3 /Zc:wchar_t /Zi /Od /Fd»x64Debugvc140.pdb»
/Zc:inline /fp:precise /D «WIN32» /D «_DEBUG» /D «_WINDLL» /D
«_UNICODE» /D «UNICODE» /errorReport:prompt /WX- /Zc:forScope /clr
[some /FU»…»] /MDd /Fa»x64Debug» /EHa /nologo /Fo»x64Debug»
/Fp»….pch»

How do I make my project build again?

Leo Chapiro's user avatar

Leo Chapiro

13.5k7 gold badges60 silver badges91 bronze badges

asked Jul 8, 2016 at 11:59

MciprianM's user avatar

4

C1001 basically indicates a compiler crash, i.e. you might have created valid C/C++ code that triggers a bug in the VC compiler. It would probably be a good idea to submit a bug report via https://connect.microsoft.com/VisualStudio/Feedback for further investigation by Microsoft.

I myself just ran into a C1001 while compiling OpenCV with Visual Studio Express 2015 Update 3. In my case, the C1001 error message also pointed me to the OpenCV core code line that triggers the compiler crash. After looking into the actual code semantics at that particular line, I suspected the compiler’s floating point handling to be the root cause of the issue. It was dealing with a big, hard-coded double array lookup table which might have caused rounding issues. (Just in case somebody googles for this, I am listing the reference here: opencv_core, mathfuncs_core.cpp, line 1261, macro-expansion of LOGTAB_TRANSLATE).

In my case, setting the compiler’s floating-point model from ‘precise’ to ‘strict’ resolved the C1001 issue. However, as you haven’t included a code fragment of the lines that cause the C1001 to raise, it’s difficult to say whether the above will fix your issue as well. If you want to give it a try, you can find the compiler switch in your project settings / C/C++ / Code Generation tab. Instead of Precise (/fp:precise), select Strict (/fp:strict) as Floating Point Model. This change may affect the performance of your code, but should not affect its precision. See https://msdn.microsoft.com/en-us/library/e7s85ffb.aspx for further information.

answered Jul 12, 2016 at 20:51

Andreas's user avatar

1

According to visual studio developers community,
this issue was fixed and closed (on July 2019) and should not appear at latest VS version. So upgrading to the latest version should solve the issue.

However, I’ve just now upgraded my VS to the latest version (16.7.1) and I still encounter this problem getting fatal error C1001: Internal compiler error.

An edit: See the comments below, people say the issue also appears at VS 2022 17.3.6 and at VS 2019 16.9.4

Finally, the following solution worked for me:
change the optimization option (project properties->C/C++->optimization) to ‘Custom’ and at (project properties->C/C++->command line’) add additional options of ‘/Ob2, /Oi, /Os, /Oy’.

taken from: Visual studio in stuck Generating code

answered Aug 16, 2020 at 10:21

Eliyahu Machluf's user avatar

2

I recently switched our product over to VS2010 from VS2008. Our solution consists of several native C++ projects and some managed C++ projects that link to those native projects.

The managed C++ projects are compiled with the /clr flag, of course. However, when compiling for x64, one of the files that includes one of the boost mutex headers causes the compiler to spit out the following error:

boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(158): fatal error C1001: An internal error has occurred in the compiler

I’ve traced down the problem to the following piece of code in basic_timed_mutex.hpp:

void
unlock()
{
long
const
offset=lock_flag_value;
// If I comment out this line, compilation works
long
const
old_count=BOOST_INTERLOCKED_EXCHANGE_ADD(&active_count,lock_flag_value);
if
(!(old_count&event_set_flag_value) && (old_count>offset))
{
if
(!win32::interlocked_bit_test_and_set(&active_count,event_set_flag_bit))
{
win32::SetEvent(get_event());
}
}
}

When compiling for x86, I see the following warning but everything still compiles:

4>boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(160): warning C4793: ‘boost::detail::basic_timed_mutex::unlock’ : function compiled as native :
4>      Found an intrinsic not supported in managed code

It would see the BOOST_INTERLOCKED_EXCHANGE_ADD macro causes the compiler to barf. Does anybody have any ideas on why this is, or how to fix it?

Cheers,
Soren

При попытке скомпилировать код на языке c ++, включая библиотеки API sfml, возникает следующая ошибка:

Внутренняя ошибка компилятора в C: Program Files (x86) Microsoft Visual Studio 2017 Community VC Tools MSVC 14.10.25017 bin HostX86 x86 CL.exe ‘
Выберите команду технической поддержки в меню справки Visual C ++ или откройте файл справочной службы для получения дополнительной информации.
C: Program Files (x86) Microsoft Visual Studio 2017 Community Common7 IDE VC VCTargets Microsoft.CppCommon.targets (358,5): ошибка MSB6006: «CL.exe» завершен с кодом 2.

Я искал в Интернете решение для этого, но я не мог решить это …
Когда я попросил помощи на форуме visual studio, я получил единственный ответ:

«Спасибо за ваш отзыв! Эта проблема была исправлена, и она будет доступна в следующем обновлении Visual Studio 2017. Спасибо за помощь в создании лучшей Visual Studio! »

Вот код с ошибкой:

#include <SFMLGraphics.hpp>

int main() {

sf::RenderWindow window(sf::VideoMode(640, 480), "Bouncing Mushroom");

sf::Texture mushroomTexture;
mushroomTexture.loadFromFile("mushroom.png");
sf::Sprite mushroom(mushroomTexture);
sf::Vector2u size = mushroomTexture.getSize;
mushroom.setOrigin(size.x / 2, size.y / 2);
sf::Vector2f increment(0.4f, 0.4f);

while (window.isOpen())
{
sf::Event evnt;
while (window.pollEvent(evnt))
{
if (evnt.type == sf::Event::Closed)
window.close();
}

if ((mushroom.getPosition().x + (size.x / 2) > window.getSize().x && increment.x > 0) || (mushroom.getPosition().x - (size.x / 2) < 0 && increment.x < 0))
{
// Reverse the direction on X axis.
increment.x = -increment.x;
}

if ((mushroom.getPosition().y + (size.y / 2) > window.getSize().y && increment.y > 0) || (mushroom.getPosition().y - (size.y / 2) < 0 && increment.y < 0))
{
// Reverse the direction on Y axis.
increment.y = -increment.y;
}

mushroom.setPosition(mushroom.getPosition() + increment);
window.clear(sf::Color(16, 16, 16, 255)); // Dark gray.
window.draw(mushroom); // Drawing our sprite.
window.display();

}

0

Решение

Хорошо, если это буквально код, который вы пытаетесь скомпилировать, есть две синтаксические ошибки:

1.- В строке 10

mushroomTexture.getSize;

getSize — это метод из класса sf :: Texture, не являющийся членом, поэтому просто добавьте ();

mushroomTexture.getSize();

2.- В конце основной функции отсутствует «}». (Я думаю, что вы просто не скопировали это правильно, но все равно проверьте это.

    window.display();

}
} <---- end of main() missing

Если это не решило вашу проблему, возможно, у вас неправильные SFML-файлы для вашей версии VS, если вы используете VS 2017, загрузите Visual C ++ 14 (2015) — 32-разрядная версия версия https://www.sfml-dev.org/download/sfml/2.4.2/ это работает для VS 2015 & 2017 (я использовал его на VS 2017, чтобы проверить ваш пример, и он запустился без проблем).

0

Другие решения

Внутренние ошибки компилятора обычно означают, что с компилятором что-то не так, и, видя, что это VS 2017, я не удивлюсь, если это будет ошибка, так как это более новая версия VS. Тем временем вы можете попытаться найти строку кода, которая вызывает эту ошибку, и найти альтернативное решение или использовать более старую версию Visual Studio.

1

Я скачал Visual Studio 2015 и попытался запустить код в нем (все учебные пособия по sfml сделаны в версии 2015) и запустить код.

Я считаю, что проблема в том, что библиотеки sfml еще не совместимы с vs 2017, поэтому решение простое:

-использовать Visual Studio 2015 или

-перекомпилировать библиотеки для Visual Studio 2017 (я не знаю, как это сделать)

0

Содержание

  1. Неустранимая ошибка C1001
  2. Fatal Error C1001
  3. Fatal error c1001 внутренняя ошибка компилятора
  4. Asked by:
  5. Question
  6. визуальная фатальная ошибка C1001: в компиляторе произошла внутренняя ошибка
  7. Решение
  8. Другие решения
  9. Fatal error c1001 внутренняя ошибка компилятора
  10. Asked by:
  11. Question

Неустранимая ошибка C1001

ВНУТРЕННЯЯ ОШИБКА КОМПИЛЯТОРА ( файл компилятора, номер строки)

Компилятор не может создать правильный код для конструкции, часто из-за сочетания определенного выражения и параметра оптимизации или проблемы при анализе. Если указанный файл компилятора содержит сегмент пути в формате UTC или C2, вероятно, это ошибка оптимизации. Если файл содержит сегмент пути cxxfe или c1xx или msc1.cpp, вероятно, это ошибка средства синтаксического анализа. Если файл с именем cl.exe, другие сведения отсутствуют.

Часто можно устранить проблему оптимизации, удалив один или несколько вариантов оптимизации. Чтобы определить, какой вариант неисправен, удаляйте параметры по одному и перекомпилируйте, пока сообщение об ошибке не исчезнет. Чаще всего отвечают параметры /Og (глобальная оптимизация) и /Oi (создание встроенных функций). Определив, какой вариант оптимизации отвечает, вы можете отключить его вокруг функции, в которой возникает ошибка, с помощью директивы optimize pragma и продолжить использовать параметр для остальной части модуля. Дополнительные сведения о параметрах оптимизации см. в разделе Рекомендации по оптимизации.

Если оптимизация не несет ответственности за ошибку, попробуйте переписать строку, в которой сообщается ошибка, или несколько строк кода, окружающих ее. Чтобы просмотреть код так, как компилятор видит его после предварительной обработки, можно использовать параметр /P (Предварительная обработка к файлу).

Дополнительные сведения о том, как изолировать источник ошибки и как сообщить о внутренней ошибке компилятора в корпорацию Майкрософт, см. в статье Как сообщить о проблеме с набором инструментов Visual C++.

Источник

Fatal Error C1001

INTERNAL COMPILER ERROR(compiler file file, line number)

The compiler cannot generate correct code for a construct, often due to the combination of a particular expression and an optimization option, or an issue in parsing. If the compiler file listed has a utc or C2 path segment, it is probably an optimization error. If the file has a cxxfe or c1xx path segment, or is msc1.cpp, it is probably a parser error. If the file named is cl.exe, there is no other information available.

You can often fix an optimization problem by removing one or more optimization options. To determine which option is at fault, remove options one at a time and recompile until the error message goes away. The options most commonly responsible are /Og (Global optimizations) and /Oi (Generate Intrinsic Functions). Once you determine which optimization option is responsible, you can disable it around the function where the error occurs by using the optimize pragma, and continue to use the option for the rest of the module. For more information about optimization options, see Optimization best practices.

If optimizations are not responsible for the error, try rewriting the line where the error is reported, or several lines of code surrounding that line. To see the code the way the compiler sees it after preprocessing, you can use the /P (Preprocess to a file) option.

For more information about how to isolate the source of the error and how to report an internal compiler error to Microsoft, see How to Report a Problem with the Visual C++ Toolset.

Источник

Fatal error c1001 внутренняя ошибка компилятора

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

I recently switched our product over to VS2010 from VS2008. Our solution consists of several native C++ projects and some managed C++ projects that link to those native projects.

The managed C++ projects are compiled with the /clr flag, of course. However, when compiling for x64, one of the files that includes one of the boost mutex headers causes the compiler to spit out the following error:

boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(158): fatal error C1001: An internal error has occurred in the compiler

I’ve traced down the problem to the following piece of code in basic_timed_mutex.hpp:

When compiling for x86, I see the following warning but everything still compiles:

4>boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(160): warning C4793: ‘boost::detail::basic_timed_mutex::unlock’ : function compiled as native :
4> Found an intrinsic not supported in managed code

It would see the BOOST_INTERLOCKED_EXCHANGE_ADD macro causes the compiler to barf. Does anybody have any ideas on why this is, or how to fix it?

Источник

визуальная фатальная ошибка C1001: в компиляторе произошла внутренняя ошибка

При компиляции на платформе x64 я получаю следующую ошибку:

Если я изменяю настройки на файл препроцессора (Да), я не получаю никакой ошибки.

О моей среде: обновление Microsoft Visual Studio 2005 до 2010

Решение

Я встречал эту ошибку много раз в VC ++. Сделайте следующие шаги. Они всегда помогали мне с этим вопросом:

  1. Посмотрите на точное местоположение, на которое указывает ошибка компилятора.
  2. Найдите любые внешние типы или классы, используемые там в этом месте.
  3. Измените порядок «include path» этих файлов, найденных на шаге 2, и перестройте решение.
  4. Надеюсь что поможет .

Другие решения

Я получаю ту же ошибку с VC2012. Настройка свойств проекта Оптимизация на Отключено (/ Od) решила проблему.

У меня была эта проблема с VS2015 при сборке локально в Windows.

Чтобы решить эту проблему, я удалил свою папку сборки (выходной каталог, как показано в разделе «Свойства / Общие») и перестроил проект.

Это всегда помогает, когда во время сборки происходят странные вещи.

В моем решении я удалил выходной файл dll проекта, и я сделал пересборка проекта.

Я столкнулся с той же ошибкой и потратил немало времени на поиски этой проблемы. Наконец, я обнаружил, что та функция, на которую указывает ошибка, имеет бесконечный цикл while. Исправлено, и ошибка исчезла.

В моем случае было использование статической лямбда-функции с QStringList аргумент. Если бы я прокомментировал регионы, где QStringList был использован файл, скомпилированный, иначе компилятор сообщил об ошибке C1001. Изменение лямбда-функции на нестатическое решило проблему (очевидно, другие варианты могли бы использовать глобальную функцию в анонимном пространстве имен или статический закрытый метод класса).

Я получил эту ошибку с помощью библиотеки повышения с VS2017. Очистка решения и восстановление его, решили проблему.

У меня также была эта проблема при обновлении с VS2008 до VS2010.

Чтобы исправить, я должен установить патч VS2008 (KB976656).

Источник

Fatal error c1001 внутренняя ошибка компилятора

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

I recently switched our product over to VS2010 from VS2008. Our solution consists of several native C++ projects and some managed C++ projects that link to those native projects.

The managed C++ projects are compiled with the /clr flag, of course. However, when compiling for x64, one of the files that includes one of the boost mutex headers causes the compiler to spit out the following error:

boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(158): fatal error C1001: An internal error has occurred in the compiler

I’ve traced down the problem to the following piece of code in basic_timed_mutex.hpp:

When compiling for x86, I see the following warning but everything still compiles:

4>boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(160): warning C4793: ‘boost::detail::basic_timed_mutex::unlock’ : function compiled as native :
4> Found an intrinsic not supported in managed code

It would see the BOOST_INTERLOCKED_EXCHANGE_ADD macro causes the compiler to barf. Does anybody have any ideas on why this is, or how to fix it?

Источник

While compiling on x64 plattform I am getting following error:

c:codavs05hpsw-scovpacctoolscodaaccesstestcoda_access.cpp(1572): fatal error C1001: An internal error has occurred in the compiler.

(compiler file 'f:ddvctoolscompilerutcsrcp2sizeopt.c', line 55)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information

------ Build started: Project: asyncexample, Configuration: Release Win32 ------

If I change settings to preprocessor file (Yes) i am not getting any error.

About my environment: Upgrading Microsoft Visual Studio 2005 to 2010

Please help.

LuFFy's user avatar

LuFFy

8,31310 gold badges38 silver badges59 bronze badges

asked Aug 16, 2011 at 10:01

venkat's user avatar

4

I have had this problem with VS2015 while building locally in Windows.

In order to solve it, I deleted my build folder (Output Directory as seen in Properties/General) and rebuilt the project.

This always seems to help when strange things happen during the build.

answered Aug 2, 2017 at 8:36

Autex's user avatar

AutexAutex

1971 silver badge12 bronze badges

I’ve encountered this error many times in VC++. Do the following steps. They’ve sometimes helped me with this issue:

  1. Take a look at the exact location, pointed out by compiler error.
  2. Find any external types or classes used there at that location.
  3. Change the order of “include path” of those files found in step 2 and rebuild the solution.
  4. I hope that help !!!!

answered Aug 16, 2011 at 10:17

TonySalimi's user avatar

TonySalimiTonySalimi

8,0944 gold badges31 silver badges62 bronze badges

0

I am getting same error with VC2012. Setting up the project properties Optimization to Disabled (/Od) resolved the issue.

answered Feb 3, 2014 at 12:27

anil's user avatar

anilanil

9711 gold badge11 silver badges23 bronze badges

2

In my solution, i’ve removed output dll file of the project, and I’ve made project rebuild.

answered Apr 27, 2017 at 16:52

Paweł Iwaneczko's user avatar

Paweł IwaneczkoPaweł Iwaneczko

8131 gold badge10 silver badges13 bronze badges

I encountered the same error and spent quite a bit of time hunting for the problem. Finally I discovered that function that the error was pointing to had an infinite while loop. Fixed that and the error went away.

answered Mar 7, 2014 at 1:45

quitePro's user avatar

quiteProquitePro

5465 silver badges3 bronze badges

In my case was the use of a static lambda function with a QStringList argument. If I commented the regions where the QStringList was used the file compiled, otherwise the compiler reported the C1001 error. Changing the lambda function to non-static solved the problem (obviously other options could have been to use a global function within an anonymous namespace or a static private method of the class).

answered Jan 30, 2017 at 10:57

cbuchart's user avatar

cbuchartcbuchart

10.4k7 gold badges53 silver badges86 bronze badges

I got this error using boost library with VS2017. Cleaning the solution and rebuilding it, solved the problem.

answered Feb 27, 2018 at 16:06

Tides's user avatar

TidesTides

11111 bronze badges

I also had this problem while upgrading from VS2008 to VS2010.

To fix, I have to install a VS2008 patch (KB976656).

Maybe there is a similar patch for VS2005 ?

answered Jan 9, 2013 at 16:33

Philippe's user avatar

I got the same error, but with a different file referenced in the error message, on a VS 2015 / x64 / Win7 build. In my case the file was main.cpp. Fixing it for me was as easy as doing a rebuild all (and finding something else to do while the million plus lines of code got processed).

Update: it turns out the root cause is my hard drive is failing. After other symptoms prompted me to run chkdsk, I discovered that most of the bad sectors that were replaced were in .obj, .pdb, and other compiler-generated files.

answered Sep 6, 2016 at 22:54

hlongmore's user avatar

hlongmorehlongmore

1,52625 silver badges27 bronze badges

I got this one with code during refactoring with a lack of care (and with templates, it case that was what made an ICE rather than a normal compile time error)

Simplified code:

void myFunction() {
    using std::is_same_v;
    for (auto i ...) {
       myOtherFunction(..., i);
    }
}

void myOtherFunction(..., size_t idx) {
    // no statement using std::is_same_v;
    if constexpr (is_same_v<T, char>) {
        ...
    }
}

answered Nov 27, 2017 at 5:36

chrisb2244's user avatar

chrisb2244chrisb2244

2,91022 silver badges42 bronze badges

I had this error when I was compiling to a x64 target.
Changing to x86 let me compile the program.

answered Oct 17, 2017 at 14:38

Robert Andrzejuk's user avatar

Robert AndrzejukRobert Andrzejuk

4,9932 gold badges23 silver badges30 bronze badges

Sometimes helps reordering the code. I had once this error in Visual Studio 2013 and this was only solved by reordering the members of the class (I had an enum member, few strings members and some more enum members of the same enum class. It only compiled after I’ve put the enum members first).

answered Jun 12, 2019 at 13:51

Liviu Stancu's user avatar

In my case, this was causing the problem:

std::count_if(data.cbegin(), data.cend(), [](const auto& el) { return el.t == t; });

Changing auto to the explicit type fixed the problem.

answered Nov 13, 2019 at 15:06

The Quantum Physicist's user avatar

Had similar problem with Visual Studio 2017 after switching to C++17:

boost/mpl/aux_/preprocessed/plain/full_lambda.hpp(203): fatal error C1001: An internal error has occurred in the compiler.
1>(compiler file 'msc1.cpp', line 1518)
1> To work around this problem, try simplifying or changing the program near the locations listed above.

Solved by using Visual Studio 2019.

answered Jan 15, 2020 at 12:04

Dmytro's user avatar

DmytroDmytro

1,25216 silver badges21 bronze badges

I first encountered this problem when i was trying to allocate memory to a char* using new char['size']{'text'}, but removing the braces and the text between them solved my problem (just new char['size'];)

answered Jun 19, 2022 at 16:38

Vlad Hagimasuri's user avatar

Another fix on Windows 10 if you have WSL installed is to disable LxssManager service and reboot the PC.

answered Aug 21, 2022 at 19:10

Vaan's user avatar

Version Used:
Microsoft Visual Studio Enterprise 2017
Version 15.0.26228.9 D15RTWSVC
Microsoft .NET Framework
Version 4.6.01586

Project target framework:
.NETCoreApp 1.1
.NET Framework 4.5.2

Steps to Reproduce:

  1. Paste the following methods:
    class Program
    {
        static void M(out int x) { x = 10; }

        static void Main(string[] args)
        {
        }
    }
  1. Run the program and put a break point in the start of method «Main»

  2. When break point hit, paste the following statement in Watch window or in the Immediate window:

new Func<int>(delegate { int x; var y = new Func<int>(() => { M(out x); return 1; }).Invoke(); return y; }).Invoke() 

Expected Behavior:
«1» will printed

Actual Behavior:
«Internal error in the C# compiler» printed

StackTrace:
«The given key was not present in the dictionary.»

> mscorlib.dll!System.Collections.Generic.Dictionary<System.__Canon, System.__Canon>.this[System.__Canon].get(System.__Canon key) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.RecordVarRead(Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol local) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitLocal(Microsoft.CodeAnalysis.CSharp.BoundLocal node) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundLocal.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionCore(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpression(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitAssignmentOperator(Microsoft.CodeAnalysis.CSharp.BoundAssignmentOperator node) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundAssignmentOperator.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionCore(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionCoreWithStackGuard(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpression(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionStatement(Microsoft.CodeAnalysis.CSharp.BoundExpressionStatement node) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundExpressionStatement.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitStatement(Microsoft.CodeAnalysis.CSharp.BoundNode node) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.Visit(Microsoft.CodeAnalysis.CSharp.BoundNode node) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundTreeRewriter.DoVisitList<Microsoft.CodeAnalysis.CSharp.BoundStatement>(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CSharp.BoundStatement> list) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundTreeRewriter.VisitBlock(Microsoft.CodeAnalysis.CSharp.BoundBlock node) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitBlock(Microsoft.CodeAnalysis.CSharp.BoundBlock node) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundBlock.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitStatement(Microsoft.CodeAnalysis.CSharp.BoundNode node) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.Visit(Microsoft.CodeAnalysis.CSharp.BoundNode node) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.Analyze(Microsoft.CodeAnalysis.CSharp.BoundNode node, System.Collections.Generic.Dictionary<Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol, Microsoft.CodeAnalysis.CSharp.CodeGen.LocalDefUseInfo> locals, bool debugFriendly) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.Optimizer.Optimize(Microsoft.CodeAnalysis.CSharp.BoundStatement src, bool debugFriendly, out System.Collections.Generic.HashSet<Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol> stackLocals) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.CodeGenerator.CodeGenerator(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method, Microsoft.CodeAnalysis.CSharp.BoundStatement boundBody, Microsoft.CodeAnalysis.CodeGen.ILBuilder builder, Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder moduleBuilder, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, Microsoft.CodeAnalysis.OptimizationLevel optimizations, bool emittingPdb) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder moduleBuilder, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method, int methodOrdinal, Microsoft.CodeAnalysis.CSharp.BoundStatement block, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeGen.LambdaDebugInfo> lambdaDebugInfo, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeGen.ClosureDebugInfo> closureDebugInfo, Microsoft.CodeAnalysis.CSharp.StateMachineTypeSymbol stateMachineTypeOpt, Microsoft.CodeAnalysis.CodeGen.VariableSlotAllocator variableSlotAllocatorOpt, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, Microsoft.CodeAnalysis.CodeGen.DebugDocumentProvider debugDocumentProvider, Microsoft.CodeAnalysis.CSharp.ImportChain importChainOpt, bool emittingPdb, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeGen.SourceSpan> dynamicAnalysisSpans) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileSynthesizedMethods(Microsoft.CodeAnalysis.CSharp.TypeCompilationState compilationState) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileSynthesizedMethods(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol> additionalTypes, Microsoft.CodeAnalysis.DiagnosticBag diagnostics) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileMethodBodies(Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation, Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder moduleBeingBuiltOpt, bool generateDebugInfo, bool hasDeclarationErrors, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, System.Predicate<Microsoft.CodeAnalysis.CSharp.Symbol> filterOpt, System.Threading.CancellationToken cancellationToken) Unknown Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CSharpCompilation.CompileMethods(Microsoft.CodeAnalysis.Emit.CommonPEModuleBuilder moduleBuilder, bool emittingPdb, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, System.Predicate<Microsoft.CodeAnalysis.ISymbol> filterOpt, System.Threading.CancellationToken cancellationToken) Unknown Microsoft.CodeAnalysis.dll!Microsoft.CodeAnalysis.Compilation.Compile(Microsoft.CodeAnalysis.Emit.CommonPEModuleBuilder moduleBuilder, bool emittingPdb, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, System.Predicate<Microsoft.CodeAnalysis.ISymbol> filterOpt, System.Threading.CancellationToken cancellationToken) Unknown Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.CompilationContext.CompileExpression(string typeName, string methodName, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, out Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProperties resultProperties) Unknown Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.EvaluationContext.CompileExpression(string expr, Microsoft.VisualStudio.Debugger.Evaluation.DkmEvaluationFlags compilationFlags, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.Alias> aliases, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, out Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProperties resultProperties, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData) Unknown Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmClrExpressionCompiler.CompileExpression.AnonymousMethod__1(Microsoft.CodeAnalysis.ExpressionEvaluator.EvaluationContextBase context, Microsoft.CodeAnalysis.DiagnosticBag diagnostics) Unknown Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileWithRetry<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult>(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.MetadataBlock> metadataBlocks, Microsoft.CodeAnalysis.DiagnosticFormatter formatter, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CreateContextDelegate createContext, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileDelegate<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult> compile, Microsoft.CodeAnalysis.ExpressionEvaluator.DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage) Unknown Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileWithRetry<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult>(Microsoft.VisualStudio.Debugger.Clr.DkmClrModuleInstance moduleInstance, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.MetadataBlock> metadataBlocks, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CreateContextDelegate createContext, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileDelegate<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult> compile, out string errorMessage) Unknown Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmClrExpressionCompiler.CompileExpression(Microsoft.VisualStudio.Debugger.Evaluation.DkmLanguageExpression expression, Microsoft.VisualStudio.Debugger.Clr.DkmClrInstructionAddress instructionAddress, Microsoft.VisualStudio.Debugger.Evaluation.DkmInspectionContext inspectionContext, out string error, out Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation.DkmCompiledClrInspectionQuery result) Unknown Microsoft.VisualStudio.Debugger.Engine.dll!Microsoft.VisualStudio.Debugger.EntryPoint.IDkmClrExpressionCompiler_CompileExpression(System.IntPtr pvClassInfo, System.IntPtr Expression, System.IntPtr InstructionAddress, System.IntPtr InspectionContext, ref System.IntPtr Error, ref System.IntPtr Result) Unknown [Native to Managed Transition] [Managed to Native Transition] Microsoft.VisualStudio.Debugger.Engine.dll!Microsoft.VisualStudio.Debugger.Evaluation.DkmLanguageExpression.CompileExpression(Microsoft.VisualStudio.Debugger.Clr.DkmClrInstructionAddress InstructionAddress, Microsoft.VisualStudio.Debugger.Evaluation.DkmInspectionContext InspectionContext, out string Error, out Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation.DkmCompiledClrInspectionQuery Result) Unknown vsdebugeng.manimpl.dll!VSDebugEngine.ManagedEE.EntryPoint.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmLanguageExpressionEvaluator.EvaluateExpression(Microsoft.VisualStudio.Debugger.Evaluation.DkmInspectionContext inspectionContext, Microsoft.VisualStudio.Debugger.DkmWorkList workList, Microsoft.VisualStudio.Debugger.Evaluation.DkmLanguageExpression expression, Microsoft.VisualStudio.Debugger.CallStack.DkmStackWalkFrame stackFrame, Microsoft.VisualStudio.Debugger.DkmCompletionRoutine<Microsoft.VisualStudio.Debugger.Evaluation.DkmEvaluateExpressionAsyncResult> completionRoutine) Unknown Microsoft.VisualStudio.Debugger.Engine.dll!Microsoft.VisualStudio.Debugger.EntryPoint.IDkmLanguageExpressionEvaluator_EvaluateExpression(System.IntPtr pvClassInfo, System.IntPtr InspectionContext, System.IntPtr WorkList, System.IntPtr Expression, System.IntPtr StackFrame, System.IntPtr CompletionRoutine) Unknown 

Вопрос:

Я обновился до версии Visual Studio 2015 Update 1, но теперь я получаю следующую ошибку, когда когда-либо компилирую конфигурацию выпуска для 64-битного, все работает для 32-битных и/или отладочных сборников.

fatal error C1001: An internal error has occurred in the compiler. (compiler file 'f:ddvctoolscompilerutcsrcp2main.c', line 246) To work around this problem, try simplifying or changing the program near the locations listed above. Please choose the Technical Support command on the Visual C++ Help menu, or open the Technical Support help file for more information link!InvokeCompilerPass()+0x2d4bd link!DllGetC2Telemetry()+0xae663 

Ошибка возникает не для каждого из моих проектов, а для некоторых.

Упрощение указанного местоположения на самом деле невозможно, место, где происходит сбой компилятора, обычно является просто простой функцией одной строки, также изменение этого кода приводит к той же ошибке в другом месте. Насколько я могу предположить, он должен что-то сделать с оптимизацией и вложением. Но изменение параметров оптимизации тоже не помогло.

Может ли кто-нибудь указать мне, как найти реальный проблемный код или некоторые параметры компилятора, чтобы избежать этой ошибки?

Я не хотел бы думать, что обновление не работает.

Лучший ответ:

Мы столкнулись с C1001 в одном из наших проектов после обновления до обновления MSVC 2015.

Через пробную ошибку мы идентифицировали свойство ClCompile/AssemblerOutput как виновника в нашем случае. Удаление этого свойства больше не вызвало C1001

Источник: https://trac.osgeo.org/mapguide/ticket/2580

Обновление 6 апреля 2016 года: я попытался создать этот же проект с обновлением MSVC 2015 Update 2 без свойства ClCompile/AssemblerOutput, и я больше не получаю C1001 при создании этого проекта. Я думаю, что обновление 2 исправлено.

Ответ №1

Попробуйте настроить при оптимизации проекта на Disabled (/Od), это может решить проблему.

Чтобы установить этот параметр компилятора в Visual Studio среда

  • Откройте диалоговое окно “Страницы свойств проекта”.
  • Щелкните папку C/С++.
  • Перейдите на страницу свойств оптимизации.
  • Измените свойство Оптимизация.

Источник: https://msdn.microsoft.com/en-us/library/aafb762y.aspx

Я надеюсь, что мой ответ будет поддерживать вашу проблему.

Ответ №2

Repro компилирует JSON lib в Release | x64. Конфигурация была установлена ​​на максимальной скорости (/O2), но General использовал “Нет оптимизации всей программы”.
Переход от “Нет оптимизации всей программы” для использования генерации кода времени ссылки (я считаю, что флаг является /LTCG ) успешно завершен.

Ответ №3

Я также столкнулся с этой проблемой, пока мы конвертировали нашу кодовую базу компании с VC10 на VC14. В нашем случае проблема возникла, когда таргетинг на x64 и SEH (/EHa) был включен одновременно с выходом Ассемблера. Ошибка произошла в нашем случае, когда в скомпилированном коде был вызван оператор ввода потока (т.е. std::cout::operator<<).

В нашем случае динамическая привязка ЭЛТ вместо статической привязки (т.е. /MT вместо /MD), по-видимому, обойти проблему без отключения выхода ассемблера. Это не первая проблема, которую я нашел со статически связанным CRT (например, это также вызвало отсутствующие курсоры при изменении размеров окон CPane в MFC).

Об этом сообщили Microsoft (https://connect.microsoft.com/VisualStudio/feedback/details/2216490/compiler-crashes-at-string-stream-insertion-operator), но через два с половиной месяца оказалось, что они даже не выглядели на нем…

Изменить: VS2015 Update 2, согласно Micrsoft, исправил эту проблему. Он протестирован как исправленный на нашей кодовой базе.

Hi Folks,

I got some code that works fine in Debug-Mode but causes a compiler error in Release-Mode:

const

float fx = pfx<0?0:(pfx>width-1?width-1:pfx), fy = pfy<0?0:(pfy>height-1?height-1:pfy);

const unsigned int x = (unsigned int)fx;

const unsigned int px = (int)x-1>=0?x-1:0, nx = x+1<width?x+1:width-1, ax = nx+1<width?nx+1:width-1;

const unsigned int y = (unsigned int)fy, py = (int)y-1>=0?y-1:0, ny = y+1<height?y+1:height-1, ay = ny+1<height?ny+1:height-1;

const float dx = fx-x;

const float dy = fy-y;

const T& a = (*this)(px,py,z);

const T& b = (*this)(x,py,z);

const T& c = (*this)(nx,py,z);

const T& d = (*this)(ax,py,z);

const T& e = (*this)(px, y,z);

const T& f = (*this)(x, y,z);

const T& g = (*this)(nx, y,z);

const T& h = (*this)(ax, y,z);

const T& i = (*this)(px,ny,z);

const T& j = (*this)(x,ny,z);

const T& k = (*this)(nx,ny,z);

const T& l = (*this)(ax,ny,z);

const T& m = (*this)(px,ay,z);

const T& n = (*this)(x,ay,z);

const T& o = (*this)(nx,ay,z);

const T& p = (*this)(ax,ay,z);

>> This Line seems to cause the compiler error:

const

double A = dx*dx*dx*(2*(b-c)+0.5*(c-a+d-b)) + dx*dx*(2*c-2.5*b+a-0.5*d) + dx*0.5*(c-a) + b;

This is, what VS2005 has to say about the error:

fatal error C1001: An internal error has occurred in the compiler.

(compiler file ‘f:rtmvctoolscompilerutcsrcP2main.c[0xCCCCCCCC:0xCCCCCCCC]’, line 182)

To work around this problem, try simplifying or changing the program near the locations listed above.

Please choose the Technical Support command on the Visual C++

Help menu, or open the Technical Support help file for more information

LINK : fatal error LNK1000: Internal error during IMAGE::BuildImage

Version 8.00.50727.42

ExceptionCode = C0000005

ExceptionFlags = 00000000

ExceptionAddress = CCCCCCCC

NumberParameters = 00000002

ExceptionInformation[ 0] = 00000000

ExceptionInformation[ 1] = CCCCCCCC

CONTEXT:

Eax = 0000000C Esp = 0012EC50

Ebx = 0373ED0D Ebp = 00004004

Ecx = 037431F8 Esi = 037431F8

Edx = 00004004 Edi = 03743B08

Eip = CCCCCCCC EFlags = 00010206

SegCs = 0000001B SegDs = 00000023

SegSs = 00000023 SegEs = 00000023

SegFs = 0000003B SegGs = 00000000

Dr0 = 00000000 Dr3 = 00000000

Dr1 = 00000000 Dr6 = 00000000

Dr2 = 00000000 Dr7 = 00000000

I already tried to simplify my code (before there where several constant definitions per line), I already tried reordering my code and I already tried to turn off all possible optimizations. (although I need them badly) Could anybody please tell me, how to face an error like this?

Best Regards

LastFreeName

While compiling on x64 plattform I am getting following error:

c:codavs05hpsw-scovpacctoolscodaaccesstestcoda_access.cpp(1572): fatal error C1001: An internal error has occurred in the compiler.

(compiler file 'f:ddvctoolscompilerutcsrcp2sizeopt.c', line 55)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information

------ Build started: Project: asyncexample, Configuration: Release Win32 ------

If I change settings to preprocessor file (Yes) i am not getting any error.

About my environment: Upgrading Microsoft Visual Studio 2005 to 2010

Please help.

LuFFy's user avatar

LuFFy

8,67910 gold badges41 silver badges59 bronze badges

asked Aug 16, 2011 at 10:01

venkat's user avatar

4

I have had this problem with VS2015 while building locally in Windows.

In order to solve it, I deleted my build folder (Output Directory as seen in Properties/General) and rebuilt the project.

This always seems to help when strange things happen during the build.

answered Aug 2, 2017 at 8:36

Autex's user avatar

AutexAutex

3072 silver badges12 bronze badges

I’ve encountered this error many times in VC++. Do the following steps. They’ve sometimes helped me with this issue:

  1. Take a look at the exact location, pointed out by compiler error.
  2. Find any external types or classes used there at that location.
  3. Change the order of “include path” of those files found in step 2 and rebuild the solution.
  4. I hope that help !!!!

answered Aug 16, 2011 at 10:17

TonySalimi's user avatar

TonySalimiTonySalimi

8,1534 gold badges32 silver badges62 bronze badges

0

I am getting same error with VC2012. Setting up the project properties Optimization to Disabled (/Od) resolved the issue.

answered Feb 3, 2014 at 12:27

anil's user avatar

anilanil

9711 gold badge11 silver badges23 bronze badges

2

In my solution, i’ve removed output dll file of the project, and I’ve made project rebuild.

answered Apr 27, 2017 at 16:52

Paweł Iwaneczko's user avatar

Paweł IwaneczkoPaweł Iwaneczko

8431 gold badge10 silver badges13 bronze badges

I encountered the same error and spent quite a bit of time hunting for the problem. Finally I discovered that function that the error was pointing to had an infinite while loop. Fixed that and the error went away.

answered Mar 7, 2014 at 1:45

quitePro's user avatar

quiteProquitePro

5465 silver badges3 bronze badges

In my case was the use of a static lambda function with a QStringList argument. If I commented the regions where the QStringList was used the file compiled, otherwise the compiler reported the C1001 error. Changing the lambda function to non-static solved the problem (obviously other options could have been to use a global function within an anonymous namespace or a static private method of the class).

answered Jan 30, 2017 at 10:57

cbuchart's user avatar

cbuchartcbuchart

10.7k8 gold badges50 silver badges91 bronze badges

I got this error using boost library with VS2017. Cleaning the solution and rebuilding it, solved the problem.

answered Feb 27, 2018 at 16:06

Tides's user avatar

TidesTides

11111 bronze badges

I also had this problem while upgrading from VS2008 to VS2010.

To fix, I have to install a VS2008 patch (KB976656).

Maybe there is a similar patch for VS2005 ?

answered Jan 9, 2013 at 16:33

Philippe's user avatar

I got the same error, but with a different file referenced in the error message, on a VS 2015 / x64 / Win7 build. In my case the file was main.cpp. Fixing it for me was as easy as doing a rebuild all (and finding something else to do while the million plus lines of code got processed).

Update: it turns out the root cause is my hard drive is failing. After other symptoms prompted me to run chkdsk, I discovered that most of the bad sectors that were replaced were in .obj, .pdb, and other compiler-generated files.

answered Sep 6, 2016 at 22:54

hlongmore's user avatar

hlongmorehlongmore

1,59523 silver badges28 bronze badges

I got this one with code during refactoring with a lack of care (and with templates, it case that was what made an ICE rather than a normal compile time error)

Simplified code:

void myFunction() {
    using std::is_same_v;
    for (auto i ...) {
       myOtherFunction(..., i);
    }
}

void myOtherFunction(..., size_t idx) {
    // no statement using std::is_same_v;
    if constexpr (is_same_v<T, char>) {
        ...
    }
}

answered Nov 27, 2017 at 5:36

chrisb2244's user avatar

chrisb2244chrisb2244

2,93022 silver badges44 bronze badges

I had this error when I was compiling to a x64 target.
Changing to x86 let me compile the program.

answered Oct 17, 2017 at 14:38

Robert Andrzejuk's user avatar

Robert AndrzejukRobert Andrzejuk

5,0662 gold badges21 silver badges30 bronze badges

Sometimes helps reordering the code. I had once this error in Visual Studio 2013 and this was only solved by reordering the members of the class (I had an enum member, few strings members and some more enum members of the same enum class. It only compiled after I’ve put the enum members first).

answered Jun 12, 2019 at 13:51

Liviu Stancu's user avatar

In my case, this was causing the problem:

std::count_if(data.cbegin(), data.cend(), [](const auto& el) { return el.t == t; });

Changing auto to the explicit type fixed the problem.

answered Nov 13, 2019 at 15:06

The Quantum Physicist's user avatar

Had similar problem with Visual Studio 2017 after switching to C++17:

boost/mpl/aux_/preprocessed/plain/full_lambda.hpp(203): fatal error C1001: An internal error has occurred in the compiler.
1>(compiler file 'msc1.cpp', line 1518)
1> To work around this problem, try simplifying or changing the program near the locations listed above.

Solved by using Visual Studio 2019.

answered Jan 15, 2020 at 12:04

Dmytro's user avatar

DmytroDmytro

1,29217 silver badges21 bronze badges

I first encountered this problem when i was trying to allocate memory to a char* using new char['size']{'text'}, but removing the braces and the text between them solved my problem (just new char['size'];)

answered Jun 19, 2022 at 16:38

Vlad Hagimasuri's user avatar

Another fix on Windows 10 if you have WSL installed is to disable LxssManager service and reboot the PC.

answered Aug 21, 2022 at 19:10

Vaan's user avatar

При попытке скомпилировать код на языке c ++, включая библиотеки API sfml, возникает следующая ошибка:

Внутренняя ошибка компилятора в C: Program Files (x86) Microsoft Visual Studio 2017 Community VC Tools MSVC 14.10.25017 bin HostX86 x86 CL.exe ‘
Выберите команду технической поддержки в меню справки Visual C ++ или откройте файл справочной службы для получения дополнительной информации.
C: Program Files (x86) Microsoft Visual Studio 2017 Community Common7 IDE VC VCTargets Microsoft.CppCommon.targets (358,5): ошибка MSB6006: «CL.exe» завершен с кодом 2.

Я искал в Интернете решение для этого, но я не мог решить это …
Когда я попросил помощи на форуме visual studio, я получил единственный ответ:

«Спасибо за ваш отзыв! Эта проблема была исправлена, и она будет доступна в следующем обновлении Visual Studio 2017. Спасибо за помощь в создании лучшей Visual Studio! »

Вот код с ошибкой:

#include <SFMLGraphics.hpp>

int main() {

sf::RenderWindow window(sf::VideoMode(640, 480), "Bouncing Mushroom");

sf::Texture mushroomTexture;
mushroomTexture.loadFromFile("mushroom.png");
sf::Sprite mushroom(mushroomTexture);
sf::Vector2u size = mushroomTexture.getSize;
mushroom.setOrigin(size.x / 2, size.y / 2);
sf::Vector2f increment(0.4f, 0.4f);

while (window.isOpen())
{
sf::Event evnt;
while (window.pollEvent(evnt))
{
if (evnt.type == sf::Event::Closed)
window.close();
}

if ((mushroom.getPosition().x + (size.x / 2) > window.getSize().x && increment.x > 0) || (mushroom.getPosition().x - (size.x / 2) < 0 && increment.x < 0))
{
// Reverse the direction on X axis.
increment.x = -increment.x;
}

if ((mushroom.getPosition().y + (size.y / 2) > window.getSize().y && increment.y > 0) || (mushroom.getPosition().y - (size.y / 2) < 0 && increment.y < 0))
{
// Reverse the direction on Y axis.
increment.y = -increment.y;
}

mushroom.setPosition(mushroom.getPosition() + increment);
window.clear(sf::Color(16, 16, 16, 255)); // Dark gray.
window.draw(mushroom); // Drawing our sprite.
window.display();

}

0

Решение

Хорошо, если это буквально код, который вы пытаетесь скомпилировать, есть две синтаксические ошибки:

1.- В строке 10

mushroomTexture.getSize;

getSize — это метод из класса sf :: Texture, не являющийся членом, поэтому просто добавьте ();

mushroomTexture.getSize();

2.- В конце основной функции отсутствует «}». (Я думаю, что вы просто не скопировали это правильно, но все равно проверьте это.

    window.display();

}
} <---- end of main() missing

Если это не решило вашу проблему, возможно, у вас неправильные SFML-файлы для вашей версии VS, если вы используете VS 2017, загрузите Visual C ++ 14 (2015) — 32-разрядная версия версия https://www.sfml-dev.org/download/sfml/2.4.2/ это работает для VS 2015 & 2017 (я использовал его на VS 2017, чтобы проверить ваш пример, и он запустился без проблем).

0

Другие решения

Внутренние ошибки компилятора обычно означают, что с компилятором что-то не так, и, видя, что это VS 2017, я не удивлюсь, если это будет ошибка, так как это более новая версия VS. Тем временем вы можете попытаться найти строку кода, которая вызывает эту ошибку, и найти альтернативное решение или использовать более старую версию Visual Studio.

1

Я скачал Visual Studio 2015 и попытался запустить код в нем (все учебные пособия по sfml сделаны в версии 2015) и запустить код.

Я считаю, что проблема в том, что библиотеки sfml еще не совместимы с vs 2017, поэтому решение простое:

-использовать Visual Studio 2015 или

-перекомпилировать библиотеки для Visual Studio 2017 (я не знаю, как это сделать)

0

Version Used:
Microsoft Visual Studio Enterprise 2017
Version 15.0.26228.9 D15RTWSVC
Microsoft .NET Framework
Version 4.6.01586

Project target framework:
.NETCoreApp 1.1
.NET Framework 4.5.2

Steps to Reproduce:

  1. Paste the following methods:
    class Program
    {
        static void M(out int x) { x = 10; }

        static void Main(string[] args)
        {
        }
    }
  1. Run the program and put a break point in the start of method «Main»

  2. When break point hit, paste the following statement in Watch window or in the Immediate window:

new Func<int>(delegate { int x; var y = new Func<int>(() => { M(out x); return 1; }).Invoke(); return y; }).Invoke() 

Expected Behavior:
«1» will printed

Actual Behavior:
«Internal error in the C# compiler» printed

StackTrace:
«The given key was not present in the dictionary.»

>	mscorlib.dll!System.Collections.Generic.Dictionary<System.__Canon, System.__Canon>.this[System.__Canon].get(System.__Canon key)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.RecordVarRead(Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol local)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitLocal(Microsoft.CodeAnalysis.CSharp.BoundLocal node)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundLocal.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionCore(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpression(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitAssignmentOperator(Microsoft.CodeAnalysis.CSharp.BoundAssignmentOperator node)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundAssignmentOperator.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionCore(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionCoreWithStackGuard(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpression(Microsoft.CodeAnalysis.CSharp.BoundExpression node, Microsoft.CodeAnalysis.CSharp.CodeGen.ExprContext context)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitExpressionStatement(Microsoft.CodeAnalysis.CSharp.BoundExpressionStatement node)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundExpressionStatement.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitStatement(Microsoft.CodeAnalysis.CSharp.BoundNode node)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.Visit(Microsoft.CodeAnalysis.CSharp.BoundNode node)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundTreeRewriter.DoVisitList<Microsoft.CodeAnalysis.CSharp.BoundStatement>(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CSharp.BoundStatement> list)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundTreeRewriter.VisitBlock(Microsoft.CodeAnalysis.CSharp.BoundBlock node)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitBlock(Microsoft.CodeAnalysis.CSharp.BoundBlock node)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.BoundBlock.Accept(Microsoft.CodeAnalysis.CSharp.BoundTreeVisitor visitor)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.VisitStatement(Microsoft.CodeAnalysis.CSharp.BoundNode node)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.Visit(Microsoft.CodeAnalysis.CSharp.BoundNode node)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.StackOptimizerPass1.Analyze(Microsoft.CodeAnalysis.CSharp.BoundNode node, System.Collections.Generic.Dictionary<Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol, Microsoft.CodeAnalysis.CSharp.CodeGen.LocalDefUseInfo> locals, bool debugFriendly)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.Optimizer.Optimize(Microsoft.CodeAnalysis.CSharp.BoundStatement src, bool debugFriendly, out System.Collections.Generic.HashSet<Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol> stackLocals)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CodeGen.CodeGenerator.CodeGenerator(Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method, Microsoft.CodeAnalysis.CSharp.BoundStatement boundBody, Microsoft.CodeAnalysis.CodeGen.ILBuilder builder, Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder moduleBuilder, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, Microsoft.CodeAnalysis.OptimizationLevel optimizations, bool emittingPdb)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder moduleBuilder, Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol method, int methodOrdinal, Microsoft.CodeAnalysis.CSharp.BoundStatement block, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeGen.LambdaDebugInfo> lambdaDebugInfo, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeGen.ClosureDebugInfo> closureDebugInfo, Microsoft.CodeAnalysis.CSharp.StateMachineTypeSymbol stateMachineTypeOpt, Microsoft.CodeAnalysis.CodeGen.VariableSlotAllocator variableSlotAllocatorOpt, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, Microsoft.CodeAnalysis.CodeGen.DebugDocumentProvider debugDocumentProvider, Microsoft.CodeAnalysis.CSharp.ImportChain importChainOpt, bool emittingPdb, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeGen.SourceSpan> dynamicAnalysisSpans)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileSynthesizedMethods(Microsoft.CodeAnalysis.CSharp.TypeCompilationState compilationState)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileSynthesizedMethods(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol> additionalTypes, Microsoft.CodeAnalysis.DiagnosticBag diagnostics)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.MethodCompiler.CompileMethodBodies(Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation, Microsoft.CodeAnalysis.CSharp.Emit.PEModuleBuilder moduleBeingBuiltOpt, bool generateDebugInfo, bool hasDeclarationErrors, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, System.Predicate<Microsoft.CodeAnalysis.CSharp.Symbol> filterOpt, System.Threading.CancellationToken cancellationToken)	Unknown
 	Microsoft.CodeAnalysis.CSharp.dll!Microsoft.CodeAnalysis.CSharp.CSharpCompilation.CompileMethods(Microsoft.CodeAnalysis.Emit.CommonPEModuleBuilder moduleBuilder, bool emittingPdb, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, System.Predicate<Microsoft.CodeAnalysis.ISymbol> filterOpt, System.Threading.CancellationToken cancellationToken)	Unknown
 	Microsoft.CodeAnalysis.dll!Microsoft.CodeAnalysis.Compilation.Compile(Microsoft.CodeAnalysis.Emit.CommonPEModuleBuilder moduleBuilder, bool emittingPdb, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, System.Predicate<Microsoft.CodeAnalysis.ISymbol> filterOpt, System.Threading.CancellationToken cancellationToken)	Unknown
 	Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.CompilationContext.CompileExpression(string typeName, string methodName, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, out Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProperties resultProperties)	Unknown
 	Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.EvaluationContext.CompileExpression(string expr, Microsoft.VisualStudio.Debugger.Evaluation.DkmEvaluationFlags compilationFlags, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.Alias> aliases, Microsoft.CodeAnalysis.DiagnosticBag diagnostics, out Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProperties resultProperties, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData)	Unknown
 	Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmClrExpressionCompiler.CompileExpression.AnonymousMethod__1(Microsoft.CodeAnalysis.ExpressionEvaluator.EvaluationContextBase context, Microsoft.CodeAnalysis.DiagnosticBag diagnostics)	Unknown
 	Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileWithRetry<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult>(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.MetadataBlock> metadataBlocks, Microsoft.CodeAnalysis.DiagnosticFormatter formatter, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CreateContextDelegate createContext, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileDelegate<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult> compile, Microsoft.CodeAnalysis.ExpressionEvaluator.DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage)	Unknown
 	Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileWithRetry<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult>(Microsoft.VisualStudio.Debugger.Clr.DkmClrModuleInstance moduleInstance, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ExpressionEvaluator.MetadataBlock> metadataBlocks, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CreateContextDelegate createContext, Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileDelegate<Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.CompileExpressionResult> compile, out string errorMessage)	Unknown
 	Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll!Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmClrExpressionCompiler.CompileExpression(Microsoft.VisualStudio.Debugger.Evaluation.DkmLanguageExpression expression, Microsoft.VisualStudio.Debugger.Clr.DkmClrInstructionAddress instructionAddress, Microsoft.VisualStudio.Debugger.Evaluation.DkmInspectionContext inspectionContext, out string error, out Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation.DkmCompiledClrInspectionQuery result)	Unknown
 	Microsoft.VisualStudio.Debugger.Engine.dll!Microsoft.VisualStudio.Debugger.EntryPoint.IDkmClrExpressionCompiler_CompileExpression(System.IntPtr pvClassInfo, System.IntPtr Expression, System.IntPtr InstructionAddress, System.IntPtr InspectionContext, ref System.IntPtr Error, ref System.IntPtr Result)	Unknown
 	[Native to Managed Transition]	
 	[Managed to Native Transition]	
 	Microsoft.VisualStudio.Debugger.Engine.dll!Microsoft.VisualStudio.Debugger.Evaluation.DkmLanguageExpression.CompileExpression(Microsoft.VisualStudio.Debugger.Clr.DkmClrInstructionAddress InstructionAddress, Microsoft.VisualStudio.Debugger.Evaluation.DkmInspectionContext InspectionContext, out string Error, out Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation.DkmCompiledClrInspectionQuery Result)	Unknown
 	vsdebugeng.manimpl.dll!VSDebugEngine.ManagedEE.EntryPoint.Microsoft.VisualStudio.Debugger.ComponentInterfaces.IDkmLanguageExpressionEvaluator.EvaluateExpression(Microsoft.VisualStudio.Debugger.Evaluation.DkmInspectionContext inspectionContext, Microsoft.VisualStudio.Debugger.DkmWorkList workList, Microsoft.VisualStudio.Debugger.Evaluation.DkmLanguageExpression expression, Microsoft.VisualStudio.Debugger.CallStack.DkmStackWalkFrame stackFrame, Microsoft.VisualStudio.Debugger.DkmCompletionRoutine<Microsoft.VisualStudio.Debugger.Evaluation.DkmEvaluateExpressionAsyncResult> completionRoutine)	Unknown
 	Microsoft.VisualStudio.Debugger.Engine.dll!Microsoft.VisualStudio.Debugger.EntryPoint.IDkmLanguageExpressionEvaluator_EvaluateExpression(System.IntPtr pvClassInfo, System.IntPtr InspectionContext, System.IntPtr WorkList, System.IntPtr Expression, System.IntPtr StackFrame, System.IntPtr CompletionRoutine)	Unknown

При попытке скомпилировать код на языке c ++, включая библиотеки API sfml, возникает следующая ошибка:

Внутренняя ошибка компилятора в C: \ Program Files (x86) \ Microsoft Visual Studio \ 2017 \ Community \ VC \ Tools \ MSVC \ 14.10.25017 \ bin \ HostX86 \ x86 \ CL.exe ‘
Выберите команду технической поддержки в меню справки Visual C ++ или откройте файл справочной службы для получения дополнительной информации.
C: \ Program Files (x86) \ Microsoft Visual Studio \ 2017 \ Community \ Common7 \ IDE \ VC \ VCTargets \ Microsoft.CppCommon.targets (358,5): ошибка MSB6006: «CL.exe» завершен с кодом 2.

Я искал в Интернете решение для этого, но я не мог решить это …
Когда я попросил помощи на форуме visual studio, я получил единственный ответ:

«Спасибо за ваш отзыв! Эта проблема была исправлена, и она будет доступна в следующем обновлении Visual Studio 2017. Спасибо за помощь в создании лучшей Visual Studio! »

Вот код с ошибкой:

#include <SFML\Graphics.hpp>

int main() {

sf::RenderWindow window(sf::VideoMode(640, 480), "Bouncing Mushroom");

sf::Texture mushroomTexture;
mushroomTexture.loadFromFile("mushroom.png");
sf::Sprite mushroom(mushroomTexture);
sf::Vector2u size = mushroomTexture.getSize;
mushroom.setOrigin(size.x / 2, size.y / 2);
sf::Vector2f increment(0.4f, 0.4f);

while (window.isOpen())
{
sf::Event evnt;
while (window.pollEvent(evnt))
{
if (evnt.type == sf::Event::Closed)
window.close();
}

if ((mushroom.getPosition().x + (size.x / 2) > window.getSize().x && increment.x > 0) || (mushroom.getPosition().x - (size.x / 2) < 0 && increment.x < 0))
{
// Reverse the direction on X axis.
increment.x = -increment.x;
}

if ((mushroom.getPosition().y + (size.y / 2) > window.getSize().y && increment.y > 0) || (mushroom.getPosition().y - (size.y / 2) < 0 && increment.y < 0))
{
// Reverse the direction on Y axis.
increment.y = -increment.y;
}

mushroom.setPosition(mushroom.getPosition() + increment);
window.clear(sf::Color(16, 16, 16, 255)); // Dark gray.
window.draw(mushroom); // Drawing our sprite.
window.display();

}

0

Решение

Хорошо, если это буквально код, который вы пытаетесь скомпилировать, есть две синтаксические ошибки:

1.- В строке 10

mushroomTexture.getSize;

getSize — это метод из класса sf :: Texture, не являющийся членом, поэтому просто добавьте ();

mushroomTexture.getSize();

2.- В конце основной функции отсутствует «}». (Я думаю, что вы просто не скопировали это правильно, но все равно проверьте это.

    window.display();

}
} <---- end of main() missing

Если это не решило вашу проблему, возможно, у вас неправильные SFML-файлы для вашей версии VS, если вы используете VS 2017, загрузите Visual C ++ 14 (2015) — 32-разрядная версия версия https://www.sfml-dev.org/download/sfml/2.4.2/ это работает для VS 2015 & 2017 (я использовал его на VS 2017, чтобы проверить ваш пример, и он запустился без проблем).

0

Другие решения

Внутренние ошибки компилятора обычно означают, что с компилятором что-то не так, и, видя, что это VS 2017, я не удивлюсь, если это будет ошибка, так как это более новая версия VS. Тем временем вы можете попытаться найти строку кода, которая вызывает эту ошибку, и найти альтернативное решение или использовать более старую версию Visual Studio.

1

Я скачал Visual Studio 2015 и попытался запустить код в нем (все учебные пособия по sfml сделаны в версии 2015) и запустить код.

Я считаю, что проблема в том, что библиотеки sfml еще не совместимы с vs 2017, поэтому решение простое:

-использовать Visual Studio 2015 или

-перекомпилировать библиотеки для Visual Studio 2017 (я не знаю, как это сделать)

0

Создаю пустой проект CLR.Создаю форму UI и точку входа main.Но и MyForm.cpp и в MyForm.h в самом начале,около 1 символа инклюидов подчеркивание и пишет:

Ошибка(активно) E1696 ошибка в командной строке : не удается открыть метаданные файл «System.Runtime.dll» KeyGen C : \Users\Encryptme\Desktop\KeyGen\KeyGen\MyForm.cpp 1
введите сюда описание изображения

user7860670's user avatar

user7860670

29.5k3 золотых знака16 серебряных знаков36 бронзовых знаков

задан 22 апр 2020 в 15:35

Barracudach's user avatar

У вашей проблемы может быть множество причин:

  1. Проверьте, что при создании вы используете шаблон проекта .Net Framework, а не .Net Core

Интерфейс создания проекта

  1. Убедитесь, что установлена точка входа и целевая система в настройках проекта: Свойства конфигурации -> Компоновщик
  2. Так как ошибка E1696 часто связана с предварительно откомпилированными заголовками попробуйте отключить предварительно откомпилированные заголовки или установить их создание в настройках проекта: Свойства конфигурации -> C/C++ . Также можете добавить файл вручную. (следует отметить, что в современной версии VS 2019 используется автоматически создаваемый файл pch.h)
  3. Убедитесь, что установлен корректный набор инструментов платформы в настройках проекта: Свойства конфигурации -> Общие.
  4. Убедитесь что вставляете правильный код. Пример:
#include "Название заголовка формы.h"

using namespace System;
using namespace System::Windows::Forms;
[STAThreadAttribute]
void Main(array<String^>^ args) {
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    Название_проекта::Название_класса_формы form;
    Application::Run(% form);
}
  1. Если не находите решение, также попробуйте:
    • открыть и закрыть проект
    • удалить папку ipch и открыть проект
    • пересобрать проект
    • перепроверить решение (меню правой кнопки мыши)
    • переустановить Пакет инструментов C++
    • переустановить или обновить Visual studio

Надеюсь вам помогло!

Конфигурация проекта

ответ дан 26 апр 2020 в 21:15

Kir S's user avatar

Kir SKir S

591 золотой знак1 серебряный знак9 бронзовых знаков

3

Visual Studio Professional 2013 Visual Studio Professional 2013 Visual Studio Premium 2013 Visual Studio Premium 2013 Еще…Меньше

Симптомы

При построении проекта Visual C++ в Visual Studio 2013 Update 5, использующий определенные типы из сборки .NET, может появиться следующее сообщение об ошибке:

Неустранимая ошибка C1001: Внутренняя ошибка в компиляторе.
(файл компилятора «f:ddvctoolscompilercxxfeslp1cesu.c», строка 6378)

Решение

Исправление от корпорации Майкрософт доступно. Тем не менее оно предназначено только для устранения проблемы, указанной в данной статье. Предлагаемое исправление должно применяться исключительно в системах, в которых обнаружена эта специфическая неполадка.

Чтобы устранить эту проблему, установите это исправление здесь.

Временное решение

Чтобы обойти эту проблему, не используйте последний тип, указанный в сообщении об ошибке. При использовании этого типа в других языках .NET, таких как C#, не подвержены рассматриваемой проблеме. Таким образом сборки оболочки могут создаваться для предоставления непрямой доступ уязвимого типа.

Ссылки

Дополнительные сведения о Visual Studio 2013 Update 5 Описание из Visual Studio 2013 обновления 5см.

Нужна дополнительная помощь?

While compiling on x64 plattform I am getting following error:

c:codavs05hpsw-scovpacctoolscodaaccesstestcoda_access.cpp(1572): fatal error C1001: An internal error has occurred in the compiler.

(compiler file 'f:ddvctoolscompilerutcsrcp2sizeopt.c', line 55)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information

------ Build started: Project: asyncexample, Configuration: Release Win32 ------

If I change settings to preprocessor file (Yes) i am not getting any error.

About my environment: Upgrading Microsoft Visual Studio 2005 to 2010

Please help.

LuFFy's user avatar

LuFFy

8,31310 gold badges38 silver badges59 bronze badges

asked Aug 16, 2011 at 10:01

venkat's user avatar

4

I have had this problem with VS2015 while building locally in Windows.

In order to solve it, I deleted my build folder (Output Directory as seen in Properties/General) and rebuilt the project.

This always seems to help when strange things happen during the build.

answered Aug 2, 2017 at 8:36

Autex's user avatar

AutexAutex

1971 silver badge12 bronze badges

I’ve encountered this error many times in VC++. Do the following steps. They’ve sometimes helped me with this issue:

  1. Take a look at the exact location, pointed out by compiler error.
  2. Find any external types or classes used there at that location.
  3. Change the order of “include path” of those files found in step 2 and rebuild the solution.
  4. I hope that help !!!!

answered Aug 16, 2011 at 10:17

TonySalimi's user avatar

TonySalimiTonySalimi

8,0944 gold badges31 silver badges62 bronze badges

0

I am getting same error with VC2012. Setting up the project properties Optimization to Disabled (/Od) resolved the issue.

answered Feb 3, 2014 at 12:27

anil's user avatar

anilanil

9711 gold badge11 silver badges23 bronze badges

2

In my solution, i’ve removed output dll file of the project, and I’ve made project rebuild.

answered Apr 27, 2017 at 16:52

Paweł Iwaneczko's user avatar

Paweł IwaneczkoPaweł Iwaneczko

8131 gold badge10 silver badges13 bronze badges

I encountered the same error and spent quite a bit of time hunting for the problem. Finally I discovered that function that the error was pointing to had an infinite while loop. Fixed that and the error went away.

answered Mar 7, 2014 at 1:45

quitePro's user avatar

quiteProquitePro

5465 silver badges3 bronze badges

In my case was the use of a static lambda function with a QStringList argument. If I commented the regions where the QStringList was used the file compiled, otherwise the compiler reported the C1001 error. Changing the lambda function to non-static solved the problem (obviously other options could have been to use a global function within an anonymous namespace or a static private method of the class).

answered Jan 30, 2017 at 10:57

cbuchart's user avatar

cbuchartcbuchart

10.4k7 gold badges53 silver badges86 bronze badges

I got this error using boost library with VS2017. Cleaning the solution and rebuilding it, solved the problem.

answered Feb 27, 2018 at 16:06

Tides's user avatar

TidesTides

11111 bronze badges

I also had this problem while upgrading from VS2008 to VS2010.

To fix, I have to install a VS2008 patch (KB976656).

Maybe there is a similar patch for VS2005 ?

answered Jan 9, 2013 at 16:33

Philippe's user avatar

I got the same error, but with a different file referenced in the error message, on a VS 2015 / x64 / Win7 build. In my case the file was main.cpp. Fixing it for me was as easy as doing a rebuild all (and finding something else to do while the million plus lines of code got processed).

Update: it turns out the root cause is my hard drive is failing. After other symptoms prompted me to run chkdsk, I discovered that most of the bad sectors that were replaced were in .obj, .pdb, and other compiler-generated files.

answered Sep 6, 2016 at 22:54

hlongmore's user avatar

hlongmorehlongmore

1,52625 silver badges27 bronze badges

I got this one with code during refactoring with a lack of care (and with templates, it case that was what made an ICE rather than a normal compile time error)

Simplified code:

void myFunction() {
    using std::is_same_v;
    for (auto i ...) {
       myOtherFunction(..., i);
    }
}

void myOtherFunction(..., size_t idx) {
    // no statement using std::is_same_v;
    if constexpr (is_same_v<T, char>) {
        ...
    }
}

answered Nov 27, 2017 at 5:36

chrisb2244's user avatar

chrisb2244chrisb2244

2,91022 silver badges42 bronze badges

I had this error when I was compiling to a x64 target.
Changing to x86 let me compile the program.

answered Oct 17, 2017 at 14:38

Robert Andrzejuk's user avatar

Robert AndrzejukRobert Andrzejuk

4,9932 gold badges23 silver badges30 bronze badges

Sometimes helps reordering the code. I had once this error in Visual Studio 2013 and this was only solved by reordering the members of the class (I had an enum member, few strings members and some more enum members of the same enum class. It only compiled after I’ve put the enum members first).

answered Jun 12, 2019 at 13:51

Liviu Stancu's user avatar

In my case, this was causing the problem:

std::count_if(data.cbegin(), data.cend(), [](const auto& el) { return el.t == t; });

Changing auto to the explicit type fixed the problem.

answered Nov 13, 2019 at 15:06

The Quantum Physicist's user avatar

Had similar problem with Visual Studio 2017 after switching to C++17:

boost/mpl/aux_/preprocessed/plain/full_lambda.hpp(203): fatal error C1001: An internal error has occurred in the compiler.
1>(compiler file 'msc1.cpp', line 1518)
1> To work around this problem, try simplifying or changing the program near the locations listed above.

Solved by using Visual Studio 2019.

answered Jan 15, 2020 at 12:04

Dmytro's user avatar

DmytroDmytro

1,25216 silver badges21 bronze badges

I first encountered this problem when i was trying to allocate memory to a char* using new char['size']{'text'}, but removing the braces and the text between them solved my problem (just new char['size'];)

answered Jun 19, 2022 at 16:38

Vlad Hagimasuri's user avatar

Another fix on Windows 10 if you have WSL installed is to disable LxssManager service and reboot the PC.

answered Aug 21, 2022 at 19:10

Vaan's user avatar

Содержание

  1. Неустранимая ошибка C1001
  2. Fatal Error C1001
  3. Fatal error c1001 внутренняя ошибка компилятора
  4. Asked by:
  5. Question
  6. визуальная фатальная ошибка C1001: в компиляторе произошла внутренняя ошибка
  7. Решение
  8. Другие решения
  9. Fatal error c1001 внутренняя ошибка компилятора
  10. Asked by:
  11. Question

Неустранимая ошибка C1001

ВНУТРЕННЯЯ ОШИБКА КОМПИЛЯТОРА ( файл компилятора, номер строки)

Компилятор не может создать правильный код для конструкции, часто из-за сочетания определенного выражения и параметра оптимизации или проблемы при анализе. Если указанный файл компилятора содержит сегмент пути в формате UTC или C2, вероятно, это ошибка оптимизации. Если файл содержит сегмент пути cxxfe или c1xx или msc1.cpp, вероятно, это ошибка средства синтаксического анализа. Если файл с именем cl.exe, другие сведения отсутствуют.

Часто можно устранить проблему оптимизации, удалив один или несколько вариантов оптимизации. Чтобы определить, какой вариант неисправен, удаляйте параметры по одному и перекомпилируйте, пока сообщение об ошибке не исчезнет. Чаще всего отвечают параметры /Og (глобальная оптимизация) и /Oi (создание встроенных функций). Определив, какой вариант оптимизации отвечает, вы можете отключить его вокруг функции, в которой возникает ошибка, с помощью директивы optimize pragma и продолжить использовать параметр для остальной части модуля. Дополнительные сведения о параметрах оптимизации см. в разделе Рекомендации по оптимизации.

Если оптимизация не несет ответственности за ошибку, попробуйте переписать строку, в которой сообщается ошибка, или несколько строк кода, окружающих ее. Чтобы просмотреть код так, как компилятор видит его после предварительной обработки, можно использовать параметр /P (Предварительная обработка к файлу).

Дополнительные сведения о том, как изолировать источник ошибки и как сообщить о внутренней ошибке компилятора в корпорацию Майкрософт, см. в статье Как сообщить о проблеме с набором инструментов Visual C++.

Источник

Fatal Error C1001

INTERNAL COMPILER ERROR(compiler file file, line number)

The compiler cannot generate correct code for a construct, often due to the combination of a particular expression and an optimization option, or an issue in parsing. If the compiler file listed has a utc or C2 path segment, it is probably an optimization error. If the file has a cxxfe or c1xx path segment, or is msc1.cpp, it is probably a parser error. If the file named is cl.exe, there is no other information available.

You can often fix an optimization problem by removing one or more optimization options. To determine which option is at fault, remove options one at a time and recompile until the error message goes away. The options most commonly responsible are /Og (Global optimizations) and /Oi (Generate Intrinsic Functions). Once you determine which optimization option is responsible, you can disable it around the function where the error occurs by using the optimize pragma, and continue to use the option for the rest of the module. For more information about optimization options, see Optimization best practices.

If optimizations are not responsible for the error, try rewriting the line where the error is reported, or several lines of code surrounding that line. To see the code the way the compiler sees it after preprocessing, you can use the /P (Preprocess to a file) option.

For more information about how to isolate the source of the error and how to report an internal compiler error to Microsoft, see How to Report a Problem with the Visual C++ Toolset.

Источник

Fatal error c1001 внутренняя ошибка компилятора

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

I recently switched our product over to VS2010 from VS2008. Our solution consists of several native C++ projects and some managed C++ projects that link to those native projects.

The managed C++ projects are compiled with the /clr flag, of course. However, when compiling for x64, one of the files that includes one of the boost mutex headers causes the compiler to spit out the following error:

boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(158): fatal error C1001: An internal error has occurred in the compiler

I’ve traced down the problem to the following piece of code in basic_timed_mutex.hpp:

When compiling for x86, I see the following warning but everything still compiles:

4>boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(160): warning C4793: ‘boost::detail::basic_timed_mutex::unlock’ : function compiled as native :
4> Found an intrinsic not supported in managed code

It would see the BOOST_INTERLOCKED_EXCHANGE_ADD macro causes the compiler to barf. Does anybody have any ideas on why this is, or how to fix it?

Источник

визуальная фатальная ошибка C1001: в компиляторе произошла внутренняя ошибка

При компиляции на платформе x64 я получаю следующую ошибку:

Если я изменяю настройки на файл препроцессора (Да), я не получаю никакой ошибки.

О моей среде: обновление Microsoft Visual Studio 2005 до 2010

Решение

Я встречал эту ошибку много раз в VC ++. Сделайте следующие шаги. Они всегда помогали мне с этим вопросом:

  1. Посмотрите на точное местоположение, на которое указывает ошибка компилятора.
  2. Найдите любые внешние типы или классы, используемые там в этом месте.
  3. Измените порядок «include path» этих файлов, найденных на шаге 2, и перестройте решение.
  4. Надеюсь что поможет .

Другие решения

Я получаю ту же ошибку с VC2012. Настройка свойств проекта Оптимизация на Отключено (/ Od) решила проблему.

У меня была эта проблема с VS2015 при сборке локально в Windows.

Чтобы решить эту проблему, я удалил свою папку сборки (выходной каталог, как показано в разделе «Свойства / Общие») и перестроил проект.

Это всегда помогает, когда во время сборки происходят странные вещи.

В моем решении я удалил выходной файл dll проекта, и я сделал пересборка проекта.

Я столкнулся с той же ошибкой и потратил немало времени на поиски этой проблемы. Наконец, я обнаружил, что та функция, на которую указывает ошибка, имеет бесконечный цикл while. Исправлено, и ошибка исчезла.

В моем случае было использование статической лямбда-функции с QStringList аргумент. Если бы я прокомментировал регионы, где QStringList был использован файл, скомпилированный, иначе компилятор сообщил об ошибке C1001. Изменение лямбда-функции на нестатическое решило проблему (очевидно, другие варианты могли бы использовать глобальную функцию в анонимном пространстве имен или статический закрытый метод класса).

Я получил эту ошибку с помощью библиотеки повышения с VS2017. Очистка решения и восстановление его, решили проблему.

У меня также была эта проблема при обновлении с VS2008 до VS2010.

Чтобы исправить, я должен установить патч VS2008 (KB976656).

Источник

Fatal error c1001 внутренняя ошибка компилятора

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

I recently switched our product over to VS2010 from VS2008. Our solution consists of several native C++ projects and some managed C++ projects that link to those native projects.

The managed C++ projects are compiled with the /clr flag, of course. However, when compiling for x64, one of the files that includes one of the boost mutex headers causes the compiler to spit out the following error:

boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(158): fatal error C1001: An internal error has occurred in the compiler

I’ve traced down the problem to the following piece of code in basic_timed_mutex.hpp:

When compiling for x86, I see the following warning but everything still compiles:

4>boost_1_43_0_sdkincludeboostthreadwin32basic_timed_mutex.hpp(160): warning C4793: ‘boost::detail::basic_timed_mutex::unlock’ : function compiled as native :
4> Found an intrinsic not supported in managed code

It would see the BOOST_INTERLOCKED_EXCHANGE_ADD macro causes the compiler to barf. Does anybody have any ideas on why this is, or how to fix it?

Источник

При компиляции на платформе x64 я получаю следующую ошибку:

c:codavs05hpsw-scovpacctoolscodaaccesstestcoda_access.cpp(1572): fatal error C1001: An internal error has occurred in the compiler.

(compiler file 'f:ddvctoolscompilerutcsrcp2sizeopt.c', line 55)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information

------ Build started: Project: asyncexample, Configuration: Release Win32 ------

Если я изменяю настройки на файл препроцессора (Да), я не получаю никакой ошибки.

О моей среде: обновление Microsoft Visual Studio 2005 до 2010

Пожалуйста помоги.

13

Решение

Я встречал эту ошибку много раз в VC ++. Сделайте следующие шаги. Они всегда помогали мне с этим вопросом:

  1. Посмотрите на точное местоположение, на которое указывает ошибка компилятора.
  2. Найдите любые внешние типы или классы, используемые там в этом месте.
  3. Измените порядок «include path» этих файлов, найденных на шаге 2, и перестройте решение.
  4. Надеюсь что поможет !!!!

9

Другие решения

Я получаю ту же ошибку с VC2012. Настройка свойств проекта Оптимизация на Отключено (/ Od) решила проблему.

7

У меня была эта проблема с VS2015 при сборке локально в Windows.

Чтобы решить эту проблему, я удалил свою папку сборки (выходной каталог, как показано в разделе «Свойства / Общие») и перестроил проект.

Это всегда помогает, когда во время сборки происходят странные вещи.

4

В моем решении я удалил выходной файл dll проекта, и я сделал пересборка проекта.

3

Я столкнулся с той же ошибкой и потратил немало времени на поиски этой проблемы. Наконец, я обнаружил, что та функция, на которую указывает ошибка, имеет бесконечный цикл while. Исправлено, и ошибка исчезла.

2

В моем случае было использование статической лямбда-функции с QStringList аргумент. Если бы я прокомментировал регионы, где QStringList был использован файл, скомпилированный, иначе компилятор сообщил об ошибке C1001. Изменение лямбда-функции на нестатическое решило проблему (очевидно, другие варианты могли бы использовать глобальную функцию в анонимном пространстве имен или статический закрытый метод класса).

2

Я получил эту ошибку с помощью библиотеки повышения с VS2017. Очистка решения и восстановление его, решили проблему.

2

У меня также была эта проблема при обновлении с VS2008 до VS2010.

Чтобы исправить, я должен установить патч VS2008 (KB976656).

Может быть, есть похожий патч для VS2005?

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
#include "StdAfx.h"
#include ".gamemap.h"
 
namespace WorldBase
{
    GameMap::GameMap(void)
    {
        _tcscpy_s(m_szSkyBoxTopTex,sizeof(m_szSkyBoxTopTex)/sizeof(TCHAR), _T(""));
        _tcscpy_s(m_szSkyBoxFrontRightTex,sizeof(m_szSkyBoxFrontRightTex)/sizeof(TCHAR), _T(""));
        _tcscpy_s(m_szSkyBoxBackLeftTex,sizeof(m_szSkyBoxBackLeftTex)/sizeof(TCHAR), _T(""));
    }
 
    GameMap::~GameMap(void)
    {
        Destroy();
    }
 
    void GameMap::LoadFromFile(IFS* pFS,const TCHAR* szFileName,DWORD options)
    {
        m_staticMapObjs.clear();
        m_npcs.clear();
        m_waypoints.clear();
        m_triggers.clear();
        m_sounds.clear();
        m_PointLight.clear();
        m_MapRect.clear();
        m_PathPoint.clear();
        m_SpawnPoint.clear();
        m_DynamicBlock.clear();
        m_EventTriggers.clear();
        m_MapAreaEx.clear();
        m_MapTriggerEffect.clear();
        m_MapCloudLayer.clear();
        //load header
        DWORD hFile=pFS->Open(szFileName);
        THROW_NULLEX(hFile,_T("GameMap open file failed."),szFileName);
 
        tagMapHeader header;
        pFS->Read(&header,sizeof(tagMapHeader),hFile);
 
        ASSERT(sizeof(m_Fog)==sizeof(header.byDistFog));
        memcpy(&m_Fog,header.byDistFog,sizeof(m_Fog));
        ASSERT(sizeof(m_SunLight)==sizeof(header.bySunLight));
        memcpy(&m_SunLight,header.bySunLight,sizeof(m_SunLight));
 
        //方向光diffuse乘以强度
        m_SunLight.diffuse.R*=header.fSunModulus;
        m_SunLight.diffuse.G*=header.fSunModulus;
        m_SunLight.diffuse.B*=header.fSunModulus;
 
        _tcscpy_s(m_szSkyBoxTopTex, sizeof(m_szSkyBoxTopTex)/sizeof(TCHAR), header.szSkyBoxTopTex);
        _tcscpy_s(m_szSkyBoxFrontRightTex, sizeof(m_szSkyBoxFrontRightTex)/sizeof(TCHAR), header.szSkyBoxFrontRightTex);
        _tcscpy_s(m_szSkyBoxBackLeftTex, sizeof(m_szSkyBoxBackLeftTex)/sizeof(TCHAR), header.szSkyBoxBackLeftTex);
        m_fSkyBoxXsize = header.fSkyBoxXsize;
        m_fSkyBoxYsize = header.fSkyBoxYsize;
        m_fSkyBoxZsize = header.fSkyBoxZsize;
        m_fSkyBoxOffX = header.fSkyBoxOffX;
        m_fSkyBoxOffY = header.fSkyBoxOffY;
        m_fSkyBoxOffZ = header.fSkyBoxOffZ;
        m_fSunModulus = header.fSunModulus;
        m_fSkyYaw = header.fSkyYaw;
 
        ASSERT(sizeof(m_SkyCol) == sizeof(header.bySkyCol));
        memcpy(&m_SkyCol, header.bySkyCol, sizeof(m_SkyCol));
 
        m_bRenderSkyShade = ( 0 != header.byRenderSkyShade );
        m_dwSkyShadeCol = header.dwSkyShadeCol;
        m_dwDynamicDiffCol = header.dwDynamicDiffCol;
        m_dwDynamicAmbCol = header.dwDynamicAmbCol;
        m_dwDynamicSpecCol = header.dwDynamicSpecCol;
 
        int i;
 
        //--load npc
        if(options&ELO_Npc)
        {
            pFS->Seek(hFile,header.dwNpcOffset,FILE_BEGIN);
            for(i = 0; i < header.nNumNPC; i++)
            {
                tagMapNPC npc;
                pFS->Read(&npc, sizeof(npc),hFile);
 
                m_npcs[npc.dwObjID]=npc;
            }
        }
 
        //load static objs
        if(options&ELO_Static)
        {
            pFS->Seek(hFile,header.dwStaticObjOffset,FILE_BEGIN);
            for(i=0;i<header.nNumStaticObj;i++)
            {
                tagStaticMapObj staticObj;
                pFS->Read(&staticObj,sizeof(staticObj),hFile);
 
                m_staticMapObjs.push_back(staticObj);
            }
        }
 
        //load waypoint
        if(options&ELO_WayPoint)
        {
            pFS->Seek(hFile,header.dwWayPointOffset,FILE_BEGIN);
            for(i=0;i<header.nNumWayPoint;i++)
            {
                tagMapWayPoint waypoint;
                pFS->Read(&waypoint,sizeof(waypoint),hFile);
                m_waypoints.push_back(waypoint);
            }
        }
 
        //load triggers
        if(options&ELO_Trigger)
        {
            pFS->Seek(hFile,header.dwTriggerOffset,FILE_BEGIN);
            for(i=0;i<header.nNumTrigger;i++)
            {
                tagMapTrigger pTriggerObj;
                /*pFS->Read(&trigger,sizeof(trigger),hFile);*/
                tstring szTemp;
                FReadValue(pFS, hFile, pTriggerObj.dwObjID);
                FReadValue(pFS, hFile, pTriggerObj.eType);
                FReadValVector(pFS, hFile, pTriggerObj.region);
                FReadValue(pFS, hFile, pTriggerObj.box.max);
                FReadValue(pFS, hFile, pTriggerObj.box.min);
                FReadValue(pFS, hFile, pTriggerObj.fHeight);
 
                pFS->Read(pTriggerObj.szMapName, sizeof(pTriggerObj.szMapName), hFile);
                pFS->Read(pTriggerObj.szWayPoint, sizeof(pTriggerObj.szWayPoint), hFile);
                pFS->Read(pTriggerObj.szScriptName, sizeof(pTriggerObj.szScriptName), hFile);
 
                FReadValue(pFS, hFile, pTriggerObj.dwParam);
                FReadValue(pFS, hFile, pTriggerObj.bLock);
                FReadValue(pFS, hFile, pTriggerObj.bFlag);
                FReadValue(pFS, hFile, pTriggerObj.dwQuestSerial);
                pFS->Read(pTriggerObj.byReserve, sizeof(pTriggerObj.byReserve), hFile);
                m_triggers.push_back(pTriggerObj);
            }
        }
 
        //load sound
        if(options&ELO_Sound)
        {
            pFS->Seek(hFile,header.dwSoundOffset,FILE_BEGIN);
            for(i=0;i<header.nNumSound;i++)
            {
                tagMapSound sound;
                pFS->Read(&sound,sizeof(sound),hFile);
                m_sounds.push_back(sound);
            }
        }
 
        //load pointlight
        if(options&ELO_PointLight)
        {
            pFS->Seek(hFile,header.dwPointLightOffset,FILE_BEGIN);
            for(i=0;i<header.nNumPointLight;i++)
            {
                tagMapPointLight pointlight;
                pFS->Read(&pointlight,sizeof(pointlight),hFile);
                m_PointLight.push_back(pointlight);
            }   
        }
 
        //load maprect by add xtian 2008-5-13
        if(options&ELO_MapRect)
        {
            pFS->Seek(hFile, header.dwMapRectOffset, FILE_BEGIN);
            for(i=0; i<header.nNumMapRect; i++)
            {
                tagMapArea mapRect;
                /*pFS->Read(&maprect, sizeof(maprect), hFile);*/
                FReadValue(pFS, hFile, mapRect.dwObjID);
                FReadValue(pFS, hFile, mapRect.eType);
                FReadValVector(pFS, hFile, mapRect.region);
                FReadValue(pFS, hFile, mapRect.box.max);
                FReadValue(pFS, hFile, mapRect.box.min);
                FReadValue(pFS, hFile, mapRect.fHeight);
                FReadValue(pFS, hFile, mapRect.bLock);
                FReadValue(pFS, hFile, mapRect.bFlag);
                FReadValue(pFS, hFile, mapRect.dwMiniMapSize);
                FReadValue(pFS, hFile, mapRect.bDistFog);
                pFS->Read(mapRect.byDistFog, sizeof(mapRect.byDistFog), hFile);
                pFS->Read(mapRect.byReserve, sizeof(mapRect.byReserve), hFile);
                m_MapRect.push_back(mapRect);
            }
 
            //--额外信息
            XMLReader varAreaEx;
            Filename mbPath = szFileName;
            TCHAR szMapAreaExPath[256];
            _stprintf( szMapAreaExPath, _T("%smaparea.xml"), mbPath.GetPath().c_str() );
 
            list<tstring> ExFieldList;
            list<tstring>::iterator iter;
            if(varAreaEx.Load(pFS, szMapAreaExPath, "id", &ExFieldList))
            {
                for(iter = ExFieldList.begin(); iter != ExFieldList.end(); ++iter)
                {
                    tagMapAreaEx areaEx;
                    areaEx.dwObjID      = varAreaEx.GetDword(_T("id"), (*iter).c_str(), -1);
                    areaEx.strTitle     = varAreaEx.GetString(_T("title"), (*iter).c_str(), _T(""));
                    areaEx.wInterval    = (WORD)varAreaEx.GetDword(_T("interval"), (*iter).c_str(), 0);
                    areaEx.byVol        = (BYTE)varAreaEx.GetDword(_T("volume"), (*iter).c_str(), 100);
                    areaEx.byPriority   = (BYTE)varAreaEx.GetDword(_T("priority"), (*iter).c_str(), 1);
 
                    for( int musici=0; musici<3; ++musici )
                    {
                        TCHAR szBuff[32];
                        _stprintf( szBuff, _T("music%d"), musici );
                        areaEx.strMusic[musici] = varAreaEx.GetString(szBuff, (*iter).c_str(), _T(""));
                    }
 
                    m_MapAreaEx.insert(make_pair(areaEx.dwObjID,areaEx));
                }
            }
        }
 
        //load pathpoint by add xtian 2008-8-6
        if(options&ELO_PathPoint)
        {
            pFS->Seek(hFile, header.dwPathPointOffset, FILE_BEGIN);
            for(int i=0; i<header.nNumPathPoint; i++)
            {
                tagMapPathPoint pathpoint;
                pFS->Read(&pathpoint, sizeof(tagMapPathPoint), hFile);
                m_PathPoint.push_back(pathpoint);
            }
        }
 
        //load spawnpoint by add xtian 2008-8-11
        if(options&ELO_SpawnPoint)
        {
            pFS->Seek(hFile, header.dwSpawnPointOffset, FILE_BEGIN);
            for(int i=0; i<header.nNumSpawnPoint; i++)
            {
                tagMapSpawnPoint spawnpoint;
                pFS->Read(&spawnpoint, sizeof(tagMapSpawnPoint), hFile);
                m_SpawnPoint.push_back(spawnpoint);
            }
        }
 
        //load dynamicblock by add xtian 2008-8-11
        if(options&ELO_DynamicBlock)
        {
            pFS->Seek(hFile, header.dwDynamicBlockOffset, FILE_BEGIN);
            for(int i=0; i<header.nNumDynamicBlock; i++)
            {
                tagMapDynamicBlock dynaBlock;
                pFS->Read(&dynaBlock, sizeof(tagMapDynamicBlock), hFile);
                m_DynamicBlock.push_back(dynaBlock);
            }
        }
 
        if(options&ELO_EventTrigger)
        {
            pFS->Seek(hFile, header.dwEventTriggerOffset, FILE_BEGIN);
            for(int i=0; i<header.nNumEventTrigger; i++)
            {
                tagMapEventTrigger eventTrigger;
                pFS->Read(&eventTrigger, sizeof(tagMapEventTrigger), hFile);
                m_EventTriggers.push_back(eventTrigger);
            }
        }
 
        if(options&ELO_MapDoor)
        {
            pFS->Seek(hFile, header.dwMapDoorOffset, FILE_BEGIN);
            for(int i=0; i<header.nNumMapDoor; i++)
            {
                tagMapDoor door;
                pFS->Read(&door, sizeof(tagMapDoor), hFile);
                m_MapDoor.push_back(door);
            }
        }
 
        if(options&ELO_MapCarrier) 
        {
            pFS->Seek(hFile, header.dwMapCarrierOffset, FILE_BEGIN);
            for(int i=0; i<header.nNumMapCarrier; i++)
            {
                tagMapCarrier carrier;
                pFS->Read(&carrier, sizeof(tagMapCarrier), hFile);
                m_MapCarrier.push_back(carrier);
            }
        }
 
        if(options&ELO_MapTriggerEffect)
        {
            pFS->Seek(hFile,header.dwMapTriggerEffectOffset,FILE_BEGIN);
            for(i=0;i<header.nNumMapTriggerEffect;i++)
            {
                tagMapTriggerEffect obj;
                pFS->Read(&obj,sizeof(obj),hFile);
 
                m_MapTriggerEffect.push_back(obj);
            }
        }
        if(options&ELO_MapCloudLayer)
        {
            pFS->Seek(hFile,header.dwCloudLayerOffset, FILE_BEGIN);
            for(i = 0; i<header.nNumCloudLayer; ++i)
            {
                tagMapCloudLayer cld;
                pFS->Read(&cld, sizeof(cld), hFile);
                m_MapCloudLayer.push_back(cld);
            }
        }
        //--close file
        pFS->Close(hFile);
    }
 
    void GameMap::Destroy()
    {
        
    }
 
    /*const tagDynamicMapObj* GameMap:: FindDynamicMapObj(DWORD mapID)
    {
        map<DWORD, tagDynamicMapObj>::iterator pIter = m_dynamicMapObjs.find(mapID);
        if(pIter != m_dynamicMapObjs.end())
            return &pIter->second;
        return NULL;
            
    }*/
    const tagMapNPC* GameMap:: FindMapNpc(DWORD mapID)
    {
        map<DWORD, tagMapNPC>::iterator pIter = m_npcs.find(mapID);
        if(pIter != m_npcs.end())
            return &pIter->second;
        return NULL;
    }
 
    const tagStaticMapObj* GameMap::FindStaticMapObj(DWORD mapID)
    {
        vector<tagStaticMapObj>::iterator pIter = m_staticMapObjs.begin();
        for(; pIter != m_staticMapObjs.end(); ++pIter)
            if(mapID == (*pIter).dwMapID)
                return &(*pIter);
        return NULL;
    }
 
    const tagMapAreaEx* GameMap::FindMapAreaEx( DWORD areaID )
    {
        map<DWORD, tagMapAreaEx>::iterator pIter = m_MapAreaEx.find(areaID);
        if(pIter != m_MapAreaEx.end())
            return &pIter->second;
        return NULL;
    }
 
    bool GameMap::GetMapAreaFog( const int nAreaIndex, tagDistFog& fog )
    {
        ASSERT( nAreaIndex >=0 && nAreaIndex < (int)m_MapRect.size() );
        tagMapArea& area = m_MapRect[nAreaIndex];
        if( !area.bDistFog )
            return false;
 
        ASSERT( sizeof(fog) == sizeof(area.byDistFog) );
        memcpy( &fog, area.byDistFog, sizeof(fog) );
        return true;
    }
}//namespace WorldBase

Понравилась статья? Поделить с друзьями:
  • Внутренняя ошибка visio 2123 действие 1021 копировать
  • Внутренняя ошибка callspawnserver unexpected response so
  • Внутренняя ошибка 2755 касперский
  • Внутренняя ошибка код ошибки 0xe2003053 дальнобойщики 3
  • Внутренняя ошибка badoo