- Remove From My Forums
-
Question
-
VC++ 2010
Building almost empty prject began to receive the message of a builder:
1>LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt
Having seen a bit of advice to reinstall VS++ 2010 did so and got an error as in a title.
Actually, fewer items had been shown in an installation box (2 instead of 4 or 5).
Is it possible to make me know either what and where from it is necessary to add or what to do to install what is necessary in full.
Thanks.
Answers
-
MSVCRT.LIB is one of CRT libraries,you can look under «C:Program FilesMicrosoft Visual Studio 9VClib» (in case of vs2008)directory. just search this file under vclib directory, if the linker cannot find this file,
then most likely that this file is corrupted or LIBPATH environment variable was set incorrectly,http://msdn2.microsoft.com/en-us/library/ts7eyw4s(VS.80).aspx, if problem persist, please let me know.
Thanks
Rupesh Shukla
-
Edited by
Saturday, September 29, 2012 2:38 AM
-
Proposed as answer by
Renjith V Ramachandran
Saturday, September 29, 2012 7:08 AM -
Marked as answer by
VictorDrb
Saturday, September 29, 2012 10:13 AM
-
Edited by
-
Feeel free to ask your all question here . Everyone will be happy to assist you in resolving your problem.
Thanks
Rupesh Shukla
-
Marked as answer by
VictorDrb
Sunday, September 30, 2012 6:29 AM
-
Marked as answer by
-
Can you show your code here.And did you check the link given in my last post.And check file in the path of C:Program Files<Microsoft Visual Studio Version>VCinclude. May be file is deleted or something else . Check your Project setting whether
path is there or not. You should check that your command prompt environment is set up correctly. There should be an environment variable named
INCLUDE
that has a directory similar to the c following (among other directories) in it:Thanks
Rupesh Shukla
-
Edited by
Pintu Shukla
Sunday, September 30, 2012 3:21 PM -
Marked as answer by
VictorDrb
Sunday, September 30, 2012 3:28 PM
-
Edited by
-
Why not you just get VS2010 CD just buy it or get it from someone to remove all this issue .Seems you wasted a lots of time and in case of trail version you can install whatever you want .You don’t have to pay anything
Thanks
Rupesh Shukla
-
Marked as answer by
VictorDrb
Tuesday, October 2, 2012 3:19 PM
-
Marked as answer by
-
sir,
I am using vs2008 and in my vc/lib folder i am not finding » MSVCRTD.lib » .So please help me to fix it as soon as possible. Your every effort will be helpful for me.
Amit sharma
Please create a new thread for your question . Will try to solve your issue .Dont forget to mention your error in your post.
Thanks
Rupesh Shukla
-
Marked as answer by
VictorDrb
Saturday, December 15, 2012 10:22 AM
-
Marked as answer by
score:0
The above answer was not quite accurate for me. I have VS2010 Ultimate installed and the file in question is not in my Visual Studio 10.0VC folder. Rather I found it in the Visual Studio 9.0VC folder. So if that’s the case for anyone, follow the lead to change the Linker but use the Visual Studio 9.0VC folder instead. It worked for me.
score:0
For Visual Studio 2017
Go to your project properties, select Linker from left. Add this to «Additional Library Directories»:
C:Program Files (x86)Microsoft Visual StudioShared14.0VClib
score:0
I got a slightly different error
LNK1104 cannot open file ‘MSVCURTD.lib’
Note it is msvcUrtd (not msvcrtd), but the file is not found on my system.
Solved it by setting the following options:
Project Properties
General
Character Set: Not Set
Common Language Runtime Support: Common Language Runtime Support (/clr)
Hope that helps.
score:0
In VS2017 (Community/Enterprise/Ultimate/Professional):
Add the path(s) of the folder(s) which include your desired «.lib» file(s) in the following path in VS:
(Right Click)Project(in Solution Explorer)->Properties->Configuration Properties->Linker->General->Additional Library Directories
If there are more than one «.lib» file use ‘;’ to separate them otherwise click on the edit box corresponds to «Additional Library Directories» then click on «» in drop down menu and add all desired «.lib» files in newly opened window one by one and in a easy to handle manner.
score:0
I ran into this using Visual Studio 2017. I tried the solutions suggested here with explicitly adding paths to where the ‘MSVCRT.lib’ file was located. But I felt this probably wasn’t the correct approach because previously for the past several weeks this had not been a problem with my project.
After trial and error, I discovered that if I left an empty or blank value in the Linker —> Input section, it would give me the error about LNK1104: cannot open file ‘MSVCRT.lib’. Eventually I figured out that I should leave this value there instead.
On the Visual Studio project, right-Clicking on the project item in the Solution explorer panel (not the Solution itself, which is the topmost item), then select Properties. From there do the following:
Linker —> Input : %(AdditionalDependencies)
This additional information might be helpful, if you got into the situation the same way I did. I have discovered that I should not put any non-system library paths in the Linker —> Input section. With my project I was trying to compile with external .lib files. Previously I had a value in this input section like: $(ProjectDir)lib; %(AdditionalDependencies) but this lead to other problems. I discovered the correct place (it seems so far) to put paths for referencing external .lib files in a C/C++ project in Visual Studio 2017 is here:
VC++ Directories —> Library Directories : $(ProjectDir)lib; $(LibraryPath)
Note the $(LibraryPath) value will include extra values such as inherited from parents. My folder project contained a folder called ‘lib’ which is why I had the first value there before the semicolon.
score:0
I have included the following path
C:Program Files (x86)Microsoft Visual Studio2017CommunityVCToolsMSVC14.16.27023libx86
and
C:localboost_1_64_0lib64-msvc-14.1
To
project properties-> linker-> Additional Directories
Click here : Image shows linking of boost and MSVC2017
score:1
I solved the problem by adding #using <mscorlib.dll>
in the main file
score:1
This indicates that Visual Studio wasn’t able to find the lib
(Library) directory which contains msvcrtd.lib
.
IMPORTANT: This lib
directory also contains linkers required during the compilation process.
So, all you need to do is override the Library Directory location. You can do so with the help of Environment Variables.
I referred to this StackOverflow Post for help. As per the answer posted, the Environment Variable LIB
refers to the path where the Linker Libraries are located. Why is this method better? Because this will apply to all the projects instead of just a particular project. Also, you don’t need to download anything extra. It just works…
Follow the steps below to achieve this:
STEP-1: Search for «msvcrtd.lib» in the search bar.
STEP-2: Click «Open File Location» (available in context menu)
STEP-3: Copy the address of the directory from the address bar.
STEP-4: Search «Environment» in the taskbar and click on «Edit the system environment variables».
STEP-5: Click on «Environment Variables…» button.
STEP-6: Under «System variables» section, click on «New…» button. A dialog would pop up.
STEP-7: In the dialog box, enter the following:
- Variable name: LIB
- Variable value: [The directory you copied in «STEP-3»]
And press «OK»
Now, you are all done!
score:2
it is also worth checking that MSVCRTD.lib file is present in «C:Program FilesMicrosoft Visual Studio 10.0VClib» for x64 and in C:Program Files(x86)Microsoft Visual Studio 10.0VClib for 32 bit. Sometimes VS might not be installed properly OR these files might get deleted accidentally.
score:2
I just had this error, in my case rebuilding the project while doing nothing else worked for me.
Here’s my situation
Visual studio crashed and I had to re-install and my new installation path is different than the previous one. then I had this error
the error showed that the library is located at
D:programMicrosoft Visual Studio...
while it should be
D:program filesMicrosoft Visual Studio...
as I said I just rebuilt it and it worked for me and if you have a multi-solution project you have to rebuild the whole-solution
score:3
Scenario:
-
Windows 10 with Visual Studio 2017 (FRESH installation).
-
‘C’ project (LINK : fatal error LNK1104: cannot open file ‘MSVCRTD.lib‘).
Resolve:
-
Run ‘Visual Studio Installer‘.
-
Click button ‘Modify’.
-
Select ‘Desktop development with C++‘.
-
From «Installation details»(usually on the right-sidebar) select:
4.1. VC++ 2015.3 v14.00(v140) toolset for desktop.
- Version of ‘toolset’ in 4.1. is just for example.
- Click button ‘Modify’, to apply changes.
-
Right-click ‘SomeProject’ -> ‘Properties’ ->
‘Linker‘ ->
‘General‘ ->
‘Additional Library Directories‘: $(VCToolsInstallDir)libx86(!!! for x64 project: ‘Additional Library Directories’: $(VCToolsInstallDir)libx64 !!!)
score:4
I have solved this problem, you need install all spectre lib.
Vistual Studio Installer->Modify->Component->Any spectre lib.
This solution can be adapted to any project.
score:5
I ran into this issue. The file existed on my machine, it was in the search path. I was stumped as the error result is really unhelpful. In my case I had turned on Spectre mitigation, but had not downloaded the runtime libs for Spectre. Once I did the download all was right with the world. I had to get this installed on my CI build servers also, as these libs are not installed with VS by default.
score:7
For VS 2019, Spectre Mitigation is enabled by default.
So the right way to fix the issue would be to install VC++ Libs for Spectre.
But, to quickly resolve the issue, you may disable Spectre Mitigation
Project Properties -> C/C++ -> Code Generation -> Spectre Mitigation -> Disabled
https://devblogs.microsoft.com/cppblog/spectre-mitigations-in-msvc/
score:8
If you use VS2017, please read it. Or just ignore this answer…It may be invalid for other VS version.
Do not trust anyone who told you to add lib path.
Here’s suggestions:
- [BEST] You just need to install these via
VS_installer
(most of us just needx86/x64
version below)- VC++ 2017 version version_numbers Libs for Spectre [(x86 and x64) | (ARM) | (ARM64)]
- Visual C++ ATL for [(x86/x64) | ARM | ARM64] with Spectre Mitigations
- Visual C++ MFC for [x86/x64 | ARM | ARM64] with Spectre Mitigations
- [NAIVE] or disable
Spectre
Option for every Solution
(Why We are so hard to global disable it) - [LAUGH] Or never use VS2017
This is VisualStudioTeam’s fault and Microsoft is guilty.
Why?
You can’t make a global configuration to disable /QSpectre
, and IDK when and why VS2017 enable it in one day. So the best way is install Spectre
? ahhha?
score:15
There is a check box that says «Inherit from parent or project defaults» in some of the property dialogs in Project Properties. Make sure that check box is checked for your Include and Library directories property windows and of course for your Additional Dependencies window.
score:17
I came across this problem when compiling a sample app using VS2017
Hope this will help
score:22
Go to your project properties, select Linker from left. Add this to «Additional Library Directories«:
"(Your Visual Studio Path)VClib"
For example:
C:Program FilesMicrosoft Visual Studio 10.0VClib
score:26
For the poor souls out there who are struggling with this, after an hour of research I found a solution for my Visual Studio Enterprise 2017:
First, lets find where is your library file located:
With windows explorer, go to your directory where Visual Studio is installed, (default: C:Program Files (x86)Microsoft Visual Studio) and do a search for msvcrtd.lib
I found mine to be in here:
C:Program Files (x86)Microsoft Visual Studio2017EnterpriseVCToolsMSVC14.15.26726libonecorex86
Quick Fix (for one project only):
- Right click on your project, click on properties, navigate to Linker, add that path to Additional Library Directories
Permanent Fix (for all projects)
- Open a project
- navigate to View > Property Manager (it could be under Other Windows)
- Expand all folders and multi select all «Microsoft.cpp.Win32.user» & «Microsoft.cpp.64.user»
- Right click and go to properties
-
Navigate to VC++ Directories
-
Add the path to default Library Directories
Related Query
- LINK : fatal error LNK1104: cannot open file ‘libcpmt.lib’ after manually configuring the LIB environmental variable
- Visual Studio: LINK : fatal error LNK1181: cannot open input file
- LINK : fatal error LNK1104: cannot open file ‘MSVCRTD.lib’
- Visual Studio 2010 — LINK : fatal error LNK1181: cannot open input file » ■/.obj»
- LINK : fatal error LNK1181: cannot open input file ‘libclamav.lib’
- LINK : fatal error LNK1104: cannot open file ‘libboost_system-vc90-mt-1_45.lib’
- LINK : fatal error LNK1104: cannot open file ‘python37_d.lib’
- LINK : fatal error LNK1104: cannot open file ‘msmpi.lib’ visual studio 2010
- LINK : fatal error LNK1104: cannot open file ‘ucrtd.lib’ in VS2017 RC
- Cython: LINK : fatal error LNK1104: cannot open file ‘atls.lib’
- LINK : fatal error LNK1104: cannot open file «glut32.lib». how to fix this error?
- fatal error LNK1104: cannot open file ‘libboost_system-vc110-mt-gd-1_51.lib’
- Fatal error LNK1104: cannot open file ‘gdi32.lib’
- fatal error C1083: Cannot open include file: ‘xyz.h’: No such file or directory?
- fatal error LNK1104: cannot open file ‘libboost_system-vc90-mt-gd-1_43.lib’
- fatal error C1083: Cannot open include file: ‘boost/config.hpp’: No such file or directory
- LINK: fatal error LNK 1104: cannot open file ‘LIBCMT.lib’
- Visual Studio 2013: fatal error C1083: Cannot open include file: ‘winsock2.h’: No such file or directory
- Error LNK1104 cannot open file ‘;.obj’
- fatal error LNK1104: cannot open file ‘libboost_regex-vc90-mt-gd-1_42.lib’
- OpenCV error: «LINK : fatal error LNK1104: cannot open file ‘opencv_core231d.lib’ «
- Fatal error LNK1104: cannot open file ‘libboost_log-vc141-mt-gd-1_64.lib’
- When trying to include ‘#include <boost/regex.hpp>’ I get: 1>LINK : fatal error LNK1104: cannot open file ‘libboost_regex-vc100-mt-gd-1_39.lib’
- Boost c++ LNK1104 cannot open file ‘libboost_serialization-vc140-mt-gd-1_62.lib’ error
- fatal error LNK1104: cannot open file «Debug/
- fatal error C1083: Cannot open include file: ‘iostream’: No such file or directory
- OpenCV error: “LINK : fatal error LNK1104: cannot open file ‘opencv_core300d.lib’ ”
- fatal error LNK1104: cannot open file ‘MSVCRT.lib’
- Error : LNK1104 cannot open file ‘pthread.lib’
- fatal error C1083: Cannot open include file: ‘fstream.h’: No such file or directory
More Query from same tag
- How do I get models to animate using Assimp?
- ampersand ‘&’ operator at end of parameter
- Is constexpr the new inline?
- Is OpenGL ES suitable for performing skeletal animations?
- Mocking static functions declared and defined in .cpp without class file using GMOCK
- How do I run XPath queries in QT?
- Why would I want a .* operator in C++?
- declaration as condition — adding parentheses causes errors
- 2D white grid not displaying above background
- std::string constructor throws std::out_of_range exception
- How to cleanse (overwrite with random bytes) std::string internal buffer?
- Optimize Algorithm Required- Arrays
- Is there a way of passing macro names as arguments to nested macros without them being expanded when the outermost macro is expanded?
- Embedded Software Defect Rate
- Can I dynamically change the font size of a dialog window created with C++ in Visual Studio?
- no match for ‘operator+=’ (operand types are ‘std::basic_ostream<char>’ and ‘int’)
- How can I use a member function pointer in libcurl
- Lock Free Queue — Single Producer, Multiple Consumers
- What are the rules for virtual function lookup?
- OpenGL Output Window shrinks to 0 x 0 window immediately
- How can I find the depth of a recursive function in C++
- Is it always necessary for a notifying thread to lock the shared data during modification?
- Error «fatal error C1034: windows.h: no include path set»
- Error when using a member of a base class in a class nested within a template in C++
- overloading << with duplicate symbol linking error
- How to initialise a vector of pointers based on the vector of objects in c++ in the most elegant way?
- Error : the application was unable to start correctly
- OpenGL Renders texture with different color than original image?
- need a warning about overriding a function with const parameter
- Call C++ class methods or function from Java on android without recreating class/variable on every call
Topic: Linker error with Microsoft Visual C++ (Read 9690 times)
rem
I’m using code blocks with Microsoft Visual C++ Toolkit 2003 on WinXP. I successfully compiled the wxWidgets libriaries but anytime I want to compile the simplest wxWidgets application I got this linker error:
LINK : fatal error LNK1104: cannot open file ‘MSVCRTD.lib’
I have no problems on compiling the same example with gcc and libriaries compiled with gcc. But with visual c++ I always fail.
What is wrong? Thanks for any help. rem
Logged
« Last Edit: January 23, 2006, 08:06:53 pm by Michael »
Logged
Microsoft Visual C++ Toolkit 2003 does not contain the debug libraries.
‘MSVCRTD.lib’, from what I can understand, is the debug version of ‘MSVCRT.lib’ which obviously you don’t have…
Logged
Be patient!
This bug will be fixed soon…
Yes, Mandrav is right. I have had some troubles too in the past. grv575 answer could be useful for you.
Michael
Logged
rem
I’m using 1.0rc2 version of codeblocks. I have installed sdk and I have msvcrtd.lib but not for my machine X86, there is only library for amd64 and IA64. It is strange because I have this error even when I’m trying to compile this example without debugging symbols.
Logged
I’m using 1.0rc2 version of codeblocks.
Try a nightly build and see if it goes better for you.
I have installed sdk and I have msvcrtd.lib but not for my machine X86, there is only library for amd64 and IA64.
Then your library will probably not work on x86 (but I may be wrong). Did you try grv575 answer?
It is strange because I have this error even when I’m trying to compile this example without debugging symbols.
May be you have set to use debugging symbols in the global compiler options. And then even if you not select debugging symbols in project compiler options, it will be inherit from the global compiler options.
Michael
Logged
rem
I installed microsoft platform sdk and Microsoft.NET SDK v2.0 but I cannot find msvcrt.lib or msvcrtd.lib there.
May be you have set to use debugging symbols in the global compiler options. And then even if you not select debugging symbols in project compiler options, it will be inherit from the global compiler options.
I have set not to use debugging symbols in the global compiler options and project compiler options but still I the linker needs the msvcrtd.lib. And I have no idea why and where to get this library.
Logged
rem
In the article «Integrating Microsoft Visual Toolkit 2003 with Code::Blocks IDE» I found this note:
-H2: If the project you are compiling complains that it cannot find «msvcrt.lib» then download the .NET 1.1 SDK and add to the END of the Directories->Linker tab:
C:Program FilesMicrosoft Visual Studio .NET 2003Vc7lib
Both the VC++ Toolkit 2003 and the platform SDK omit this library.
But in the .NET 1.1 SDK I haven’t found this library or .NET 2.0 SDK either.
Logged
rem
I have a question to those who are using microsoft visual c++ toolkit 2003. Do you need msvcrtd.lib to link your project? Do you have this library? And where is it? Thanks for any advice, rem.
Logged
Do you need msvcrtd.lib to link your project?
you need it, if you want to build a debug version of your program.
Do you have this library?
yes
And where is it? Thanks for any advice, rem.
it is part of the Visual C (or Studio) but not part of the free toolkit — it is generally NOT freely available
« Last Edit: January 25, 2006, 04:37:38 pm by tiwag »
Logged
Do you have this library?
Yes.
And where is it?
I have both msvcrtd.lib and msvcrt.lib under:
Microsoft Platform SDKLibIA64
and
Microsoft Platform SDKLibAMD64
[EDIT] I have no tried those libraries until now. So, I am not sure if they work or not.
Michael
« Last Edit: January 25, 2006, 05:19:42 pm by Michael »
Logged
rem
I also have these libraries in the:
D:Microsoft Platform SDKLibAMD64
and
D:Microsoft Platform SDKLibIA64
directories. But I need for X86 not amd64 or ia64 machine, so for me these libraries are useless. I also unset produce debugging symbols in the compiler options and the linker stil show the same error:
LINK : fatal error LNK1104: cannot open file ‘MSVCRTD.lib’
So I really don’t know what is going on. Are there libs for X86?
Logged
Содержание
- Ошибка средств компоновщика LNK1104
- Не удается открыть приложение или PDB-файл
- Приложение запущено или загружено в отладчик.
- Ваше приложение заблокировано антивирусной проверкой
- Не удается открыть файл библиотеки Майкрософт
- Библиотеки Windows, такие как kernel32.lib
- Библиотеки vcruntime с версиями
- Библиотеки для розничной торговли, отладки или платформы
- Библиотека vccorlib.lib
- Библиотеки в проектах из интернета или других источников
- Обновленные библиотеки Windows SDK
- Не удается открыть сторонний файл библиотеки
- Не удается открыть файл, созданный проектом
- Не удается открыть файл C:Program.obj
- Другие распространенные проблемы
- Проблемы с путем или именем файла
- Параллельная синхронизация сборки
- Дополнительные зависимости, указанные в интегрированной среде разработки
- Слишком длинные пути
- Слишком большие файлы
- Неправильные разрешения на файл
- Недостаточно места на диске
- Проблемы в переменной среды TMP
- Помощь, моя проблема не указана здесь!
- Visual Studio C ++ / CLI Таинственная ошибка с шаблоном
- Решение
- Другие решения
Ошибка средств компоновщика LNK1104
Эта ошибка возникает, когда компоновщику не удается открыть файл для чтения или записи. Ниже перечислены две наиболее распространенные причины проблемы.
программа уже запущена или загружена в отладчик и
пути к библиотеке неверны или не заключены в двойные кавычки.
Эта ошибка может быть вызвана многими другими возможными причинами. Чтобы сузить их, сначала проверьте, какой тип файла имеет имя файла . Затем используйте следующие разделы, чтобы определить и устранить конкретную проблему.
Не удается открыть приложение или PDB-файл
Приложение запущено или загружено в отладчик.
Если имя файла — это имя исполняемого файла или связанный PDB-файл, проверьте, запущено ли приложение. Затем проверьте, загружена ли она в отладчик. Чтобы устранить эту проблему, остановите программу и выгрузите ее из отладчика перед повторной сборкой. Если приложение открыто в другой программе, например редактор ресурсов, закройте его. Если программа не отвечает, может потребоваться использовать диспетчер задач для завершения процесса. Кроме того, может потребоваться закрыть и перезапустить Visual Studio.
Ваше приложение заблокировано антивирусной проверкой
Антивирусные программы часто временно блокируют доступ к вновь созданным файлам, особенно .exe и .dll исполняемым файлам. Чтобы устранить эту проблему, попробуйте исключить каталоги сборки проекта из антивирусного сканера.
Не удается открыть файл библиотеки Майкрософт
Библиотеки Windows, такие как kernel32.lib
Если файл, который не удается открыть, является одним из файлов стандартной библиотеки, предоставляемых корпорацией Майкрософт, например kernel32.lib, может возникнуть ошибка конфигурации проекта или ошибка установки. Убедитесь, что пакет WINDOWS SDK установлен. Если для проекта требуются другие библиотеки Майкрософт, такие как MFC, убедитесь, что компоненты MFC также установлены установщиком Visual Studio. Установщик можно запустить еще раз, чтобы добавить дополнительные компоненты в любое время. Дополнительные сведения см. в Изменение Visual Studio. Используйте вкладку «Отдельные компоненты » в установщике, чтобы выбрать определенные библиотеки и пакеты SDK.
Библиотеки vcruntime с версиями
Если сообщение об ошибке содержит версию библиотеки Майкрософт, например msvcr120.lib, набор инструментов платформы для этой версии компилятора может быть не установлен. Чтобы устранить эту проблему, у вас есть два варианта: обновить проект, чтобы использовать текущий набор инструментов платформы, или установить старый набор инструментов и выполнить сборку проекта без изменений. Дополнительные сведения см. в разделе «Обновление проектов с более ранних версий Visual C++ и использование собственного многонацеливания в Visual Studio для сборки старых проектов».
Библиотеки для розничной торговли, отладки или платформы
Эта ошибка может возникнуть при первой сборке для новой целевой платформы или конфигурации, например розничной торговли или ARM64. Убедитесь, что в интегрированной среде разработки установлены набор инструментов платформы и версия windows SDK , указанные на странице свойств «Общие «. Также убедитесь, что необходимые библиотеки доступны в каталогах библиотек, указанных на странице свойств каталогов VC++. Проверьте свойства каждой конфигурации, такие как отладка, розничная торговля, x86 или ARM64. Если одна сборка работает, но другая нет, сравните параметры для обоих. Установите все отсутствующие необходимые средства и библиотеки.
Библиотека vccorlib.lib
Для приложений или компонентов универсальной платформы Windows (UWP) нет библиотек, смягчаемых spectre. Если сообщение об ошибке содержит vccorlib.lib, возможно, вы включили /Qspectre в проекте UWP. Отключите параметр компилятора /Qspectre , чтобы устранить эту проблему. В Visual Studio измените свойство «Устранение рисков Spectre «. Он находится на странице создания кодаC/C++> диалогового окна страниц свойств проекта.
Библиотеки в проектах из интернета или других источников
При сборке проекта, скопированного с другого компьютера, расположения установки библиотеки могут отличаться. Для сборок командной строки убедитесь, что переменная среды LIB и пути библиотеки заданы правильно для сборки. В Visual Studio можно просматривать и изменять текущие пути библиотеки, заданные на страницах свойств проекта. На странице каталогов VC++ выберите раскрывающийся список для свойства «Каталоги библиотеки «, а затем нажмите кнопку «Изменить«. В разделе «Оцененное значение » диалогового окна «Каталоги библиотеки » перечислены текущие пути, которые искали файлы библиотеки. Обновите эти пути, чтобы они указывали на локальные библиотеки.
Обновленные библиотеки Windows SDK
Эта ошибка может возникать, если путь Visual Studio к Пакету SDK для Windows устарел. Это может произойти, если вы устанавливаете более новый пакет SDK для Windows независимо от установщика Visual Studio. Чтобы исправить его в интегрированной среде разработки, обновите пути, указанные на странице свойств каталогов VC++. Задайте версию в пути, чтобы она соответствовала новому пакету SDK. Если вы используете командную строку разработчика, обновите пакетный файл, который инициализирует переменные среды новыми путями пакета SDK. Эту проблему можно избежать с помощью установщика Visual Studio для установки обновленных пакетов SDK.
Не удается открыть сторонний файл библиотеки
Эта проблема связана с несколькими распространенными причинами.
Путь к файлу библиотеки может быть неправильным или не заключен в двойные кавычки. Или, возможно, вы не указали его компоновщику.
Возможно, вы установили 32-разрядную версию библиотеки, но вы создаете для 64-разрядных или наоборот.
Библиотека может иметь зависимости от других библиотек, которые не установлены.
Чтобы устранить проблему пути для сборок из командной строки, убедитесь, что задана переменная среды LIB. Убедитесь, что он содержит пути для всех используемых библиотек и для каждой сборки конфигурации. В интегрированной среде разработки пути библиотеки задаются свойствомкаталогов>библиотеки VC++. Убедитесь, что все каталоги, содержащие необходимые библиотеки, перечислены здесь для каждой сборки конфигурации.
Возможно, потребуется указать каталог библиотеки, который переопределяет каталог стандартной библиотеки. В командной строке используйте параметр /LIBPATH . В интегрированной среде разработки используйте свойство «Дополнительные каталоги библиотек» на странице свойств компоновщика > конфигурации > общего свойства проекта.
Убедитесь, что установлены все версии библиотеки, необходимые для конфигураций, которые вы создаете. Рассмотрите возможность использования служебной программы управления пакетами vcpkg для автоматизации установки и установки для многих общих библиотек. Когда это возможно, лучше создавать собственные копии сторонних библиотек. После этого вы уверены, что все локальные зависимости библиотек созданы для тех же конфигураций, что и проект.
Не удается открыть файл, созданный проектом
Эта ошибка может появиться, если имя файла еще не существует, когда компоновщик пытается получить к нему доступ. Это может произойти, если один проект зависит от другого в решении, но проекты создаются в неправильном порядке. Чтобы устранить эту проблему, убедитесь, что ссылки на проекты заданы в проекте, который использует файл. Затем отсутствующий файл будет создан до его необходимости. Дополнительные сведения см. в статье «Добавление ссылок в проектах Visual Studio C++ и управление ссылками в проекте».
Не удается открыть файл C:Program.obj
Если в сообщении об ошибке отображается имя файла C:Program.obj , заключите пути библиотеки в двойные кавычки. Эта ошибка возникает, когда несмеченный путь, начинающийся с C:Program Files , передается компоновщику. Несмеченные пути также могут привести к аналогичным ошибкам. Как правило, они отображают непредвиденный OBJ-файл в корне диска.
Чтобы устранить эту проблему для сборок из командной строки, проверьте параметры параметра /LIBPATH . Также проверьте пути, указанные в переменной среды LIB, и пути, указанные в командной строке. Обязательно используйте двойные кавычки для всех путей, включающих пробелы.
Чтобы устранить эту проблему в интегрированной среде разработки, добавьте двойные кавычки при необходимости в следующие свойства проекта:
Свойство «Каталоги библиотеки » на странице свойств каталогов VC++ «Свойства > конфигурации» ,
Свойство «Дополнительные каталоги библиотек» на странице свойств компоновщика > конфигурации > «Общие свойства»
Свойство Additional Dependencies (Дополнительные зависимости) на странице входных данных компоновщика свойств компоновщика > конфигурации>.
Другие распространенные проблемы
Проблемы с путем или именем файла
Эта ошибка может возникать, если имя файла библиотеки или путь, указанный компоновщику, неправильный. Или, если путь содержит недопустимую спецификацию диска. Просмотрите командную строку или в любой директиве #pragma comment( lib, «library_name» ) для проблем. Проверьте орфографию и расширение файла и убедитесь, что файл существует в указанном расположении.
Параллельная синхронизация сборки
Если вы используете параметр параллельной сборки, Visual Studio, возможно, заблокировали файл в другом потоке. Чтобы устранить эту проблему, убедитесь, что один и тот же объект кода или библиотека не встроены в несколько проектов. Используйте зависимости сборки или ссылки на проекты для получения встроенных двоичных файлов в проекте.
Дополнительные зависимости, указанные в интегрированной среде разработки
При указании отдельных библиотек непосредственно в свойстве «Дополнительные зависимости» используйте пробелы для разделения имен библиотек. Не используйте запятые или точки с запятой. Если вы используете пункт меню «Изменить «, чтобы открыть диалоговое окно «Дополнительные зависимости» , используйте новые строки, чтобы разделить имена, а не запятые, точки с запятой или пробелы. Также используйте новые линии при указании путей к библиотеке в диалоговых окнах каталогов библиотек и дополнительных каталогов библиотек .
Слишком длинные пути
Эта ошибка может появиться, когда путь к имени файла расширяется до более чем 260 символов. При необходимости измените структуру каталога или сократите имена папок и файлов, чтобы сократить пути.
Слишком большие файлы
Эта ошибка может возникнуть из-за слишком большого размера файла. Библиотеки или файлы объектов, превышающие размер гигабайта, могут вызвать проблемы для 32-разрядного компоновщика. Возможное исправление этой проблемы — использовать 64-разрядный набор инструментов. Дополнительные сведения об использовании 64-разрядного набора инструментов в командной строке см. в разделе «Практическое руководство. Включение 64-разрядного набора инструментов Visual C++ в командной строке». Сведения об использовании 64-разрядного набора инструментов в интегрированной среде разработки см. в статье «Использование MSBuild с 64-разрядным компилятором и инструментами». См. также эту запись Stack Overflow: как сделать Visual Studio использовать собственную цепочку инструментов amd64.
Неправильные разрешения на файл
Эта ошибка может возникнуть, если у вас недостаточно разрешений на доступ к имени файла. Это может произойти, если вы используете обычную учетную запись пользователя для доступа к файлам библиотек в защищенных системных каталогах. Или, если вы используете файлы, скопированные другими пользователями, которые по-прежнему имеют свои исходные разрешения. Чтобы устранить эту проблему, переместите файл в каталог проектов, доступный для записи. Если перемещаемый файл имеет недоступные разрешения, выполните команду takeown.exe в окне командной строки администратора, чтобы взять на себя владение файлом.
Недостаточно места на диске
Ошибка может возникать, если у вас недостаточно места на диске. Компоновщик использует временные файлы в нескольких ситуациях. Даже если у вас достаточно места на диске, большая ссылка может очертить или фрагментировать доступное место на диске. Рассмотрите возможность использования параметра /OPT (оптимизация); выполнение транзитивного исключения COMDAT считывает все файлы объектов несколько раз.
Проблемы в переменной среды TMP
Если имя файла называется LNKnnn, это имя файла, созданное компоновщиком для временного файла. Каталог, указанный в переменной среды TMP, может не существовать. Или для переменной среды TMP может быть указано несколько каталогов. Для переменной среды TMP следует указать только один путь к каталогу.
Помощь, моя проблема не указана здесь!
Если ни одна из перечисленных здесь проблем не возникает, вы можете использовать средства обратной связи в Visual Studio для получения справки. В интегрированной среде разработки перейдите в строку меню и выберите «Отправить > отзыв о > проблеме«. Кроме того, отправьте предложение с помощью справки > по отправке отзывов>. Вы также можете использовать сайт Microsoft Learn Q&A для вопросов и веб-сайт Visual Studio C++ Сообщество разработчиков. Используйте эти сайты для поиска ответов на вопросы и запроса справки. Дополнительные сведения см. в статье «Как сообщить о проблеме с набором инструментов или документацией visual C++».
Если вы обнаружили новый способ устранения этой проблемы, которую мы должны добавить в эту статью, сообщите нам об этом. Вы можете отправить нам отзыв с помощью кнопки ниже для этой страницы. Используйте его для создания новой проблемы в репозитории GitHub документации по C++. Спасибо!
Источник
Visual Studio C ++ / CLI Таинственная ошибка с шаблоном
Ну, я пытался создать C ++ DLL в Visual Studio 2015, что заняло какое-то время, так как я не очень хорош в Visual Studio.
Мне нужно получить доступ к библиотекам .NET, в частности System :: Management. (Написание кода было немного сложнее, чем требовалось из-за плохой реализации C ++, но, по крайней мере, он есть.)
Я исправил очевидные ошибки и, наконец, понял, что мне нужно включить CLR в свойствах проекта, а затем выбрать связанные библиотеки с помощью References-> Add Reference. Но после всего этого, теперь это просто странная ошибка:
Компилятор не показывает красные волнистые линии под чем-либо, и ошибка утверждает, что строка — «1», а файл — «ССЫЛКА», так что тут никакой помощи.
Я подумал, что, возможно, где-то испортил конфигурацию проекта, поэтому я создал новый проект и перенес код. Ошибка все еще произошла. Если я отключил CLR и прокомментировал .NET-зависимый код, сборка прошла без ошибок.
Поэтому я попытался создать новый проект из шаблона (Visual C ++ -> Win32 Console Application) и затем включить CLR, прежде чем делать что-либо еще. Затем я попробовал еще раз, выбрав разные версии .NET Framework.
Наконец, я попытался создать проект с шаблоном (Visual C ++ -> CLR -> CLR Console Application) и сразу же создать его. Я имею в виду буквально, не делая ничего другого. Это все еще дало ту же ошибку!
Что на земле происходит? Я что-то не так делаю или VS2015 просто сломан?
Решение
Попробуй это,
Щелкните правой кнопкой мыши проект, который показывает «LNK1104: невозможно открыть файл« MSCOREE.lib », затем выберите« Свойства »->« Свойства конфигурации »->« Каталоги VC ++ »->« Каталоги библиотек »-> Добавить обе записи снизу, разделенные точкой с запятой
Именно здесь должен быть ваш mscoree.lib, проверьте его там, прежде чем делать это, в противном случае вам может потребоваться установить / переустановить Microsoft SDK.
Другие решения
В некоторых ситуациях SDK может не установить необходимые файлы в папке LIB, как описано в MSCoree.lib отсутствует в WinSDK . Их решение состояло в том, чтобы выполнить ремонт установки. Это может не сработать.
Я успешно побежал WinSDKInterop_amd64WinSDKInterop_amd64.msi в результате чего создается:
Источник
I have come across a number of similar issues, but none seem be exact. Sorry if this is a duplicate of something I have not come across.
I have run the vcvarsall.bat amd64 and use the generator -G «Visual Studio 15 2017 Win64»
The CMakeError.log shows that the compiler does get invoked;
C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.15.26726binHostX86x64CL.exe /c /nologo /W0 /WX- /diagnostics:classic /Od /D _MBCS /Gm- /EHsc /RTC1 /MDd /GS /fp:precise /Qspectre /Zc:wchar_t /Zc:forScope /Zc:inline /Fo"Debug\" /Fd"Debugvc141.pdb" /Gd /TC /FC /errorReport:queue CMakeCCompilerId.c
The problem is the linking:
C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.15.26726binHostX86x64link.exe /E
RRORREPORT:QUEUE /OUT:".CompilerIdC.exe" /INCREMENTAL:NO /NOLOGO kernel32.lib user32.lib gdi32.lib winspool.lib comdlg3
2.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /MANIFEST /MANIFESTUAC:"level='as
Invoker' uiAccess='false'" /manifest:embed /PDB:".CompilerIdC.pdb" /SUBSYSTEM:CONSOLE /TLBID:1 /DYNAMICBASE /NXCOMPAT /
IMPLIB:".CompilerIdC.lib" /MACHINE:X64 DebugCMakeCCompilerId.obj
LINK : fatal error LNK1104: cannot open file 'MSVCRTD.lib' [C:wrkgitmain-compiler-devcontribzlib-1.2.11CMakeFiles
3.8.0CompilerIdCCompilerIdC.vcxproj]
The vcvarsall.bat sets the LIB and LIBPATH environment variables:
LIB=C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.15.26726ATLMFClibx64;C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.15.26726libx64;C:Program Files (x86)Windows KitsNETFXSDK4.6.1libumx64;C:Program Files (x86)Windows Kits10lib10.0.17763.0ucrtx64;C:Program Files (x86)Windows Kits10lib10.0.17763.0umx64;
LIBPATH=C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.15.26726ATLMFClibx64;C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.15.26726libx64;C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.15.26726libx86storereferences;C:Program Files (x86)Windows Kits10UnionMetadata10.0.17763.0;C:Program Files (x86)Windows Kits10References10.0.17763.0;C:WindowsMicrosoft.NETFramework64v4.0.30319;
and MSVCRTD.lib is found here, which is the second expansion of either LIB or LIBPATH
C:Program Files (x86)Microsoft Visual Studio2017ProfessionalVCToolsMSVC14.15.26726libx64msvcrtd.lib
The same build setup works with Visual Studio 2015 (obviously with a different generator)
Am I not doing something I need to do with Visual Studio 2017?
BTW, for repro, I’m trying to build zlib-1.2.11 (https://zlib.net/).
I am using CMake 3.8, but have also tried Cmake that is bundled with VS2017 (cmake version 3.11.18040201-MSVC_2) and Cmake 3.12.3 — they all report the exact same error.
If you need any more information, just ask.
Edited Oct 19, 2018 by