- Remove From My Forums
-
Question
-
Hi All
OK so i know there is A LOT on this error floating around. I am a complete newb to VS 2008. i’ve just done a complete install of Visual Studio 2008 on Xp32 SP2 etc, with the view of using it as a simple compiler for now, and moving onto building app later.
Having created a new empty project, added a .cpp file and created the simplest of simple Hello world applications i get the following linking error:
1>—— Build started: Project: hello, Configuration: Debug Win32 ——
1>Linking…
1>LINK : fatal error LNK1104: cannot open file ‘kernel32.lib’
1>Build log was saved at «file://c:CPPhellohelloDebugBuildLog.htm»
1>hello — 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========I’ve not touched or configured anything to get this error. Since this i have been googling like mad, and most replies just say «check your linker settings» etc. But there is nothing there. I’ve tried adding multiple different paths to the linker dependancies and the VC++ DIrectories and nothing
On my system, the only Kernel32.lib is located at:
C:Program FilesMicrosoft SDKsWindowsv5.0LibIA64But surely this is for 64 bit platforms? Sometimes adding this path results in an expected error of it not being the right target machine.
I’ve tried adding the path to the folder and to the file to the linker dependancies, i’ve tried adding it to the VC++ Directories for all entries except include. Basically anything that i’ve found suggested on the net.
This is so frustrating as i’ve not done anything other than install VS and it wont work! So i dont know am i missing something?
Many thanks in advance
‘Oom
Answers
-
You have not provided all pertinent information.
Quote>i’ve just done a complete install of Visual Studio 2008
Was this actually VS or was it one or more of the language products?
Which edition? Express? Standard? Professional? Note that this
forum is for issues related to the Express Editions of VC++.
If VC Express, how did you install it? Via the MS web install or via
a downloaded ISO disc?
If Express, what other supporting libraries have you installed?
MSDN? Win32 SDK?
Quote>On my system, the only Kernel32.lib is located at:
Quote>C:Program FilesMicrosoft SDKsWindowsv5.0LibIA64When and why did you install this version of the SDK? What is your
hardware platform? You have the SDK libs for Itanium processors.
It is certainly not the latest, and not even as recent as the version
originally available when VC 2008 was initially released. If you are
running on an Intel/AMD x86 system you should have at least v6.0a and
there should be a kernel32.lib for 32-bit (in lib) and one for 64-bit (in Libx64).
If you actually do have Visual Studio 2008, you may not have completed
the full installation.
— Wayne
I reinstallt everything and checked my SDK version.
The testprogram is a simple hello world program.
The error promt is:
Microsoft (R) C/C++ Optimizing Compiler Version 19.21.27702.2 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
hello.cpp
Microsoft (R) Incremental Linker Version 14.21.27702.2
Copyright (C) Microsoft Corporation. All rights reserved.
/out:hello.exe
hello.obj
LINK : fatal error LNK1104: cannot open file ‘kernel32.lib’
I checked my environmental varibales and didn’t have the kernel32.lib path in there but the error didn’t vanish after adding it to %path% (did it systemwide). I tried to fix it by adding the path to kernel32 for x86 and x64 which din’t help either.
didn’t have the kernel32.lib path in there
Which directory is kernel32.lib on your machine?
Also, adding it to %path% won’t help. Adding it to %LIB% might help.
It is at C:Program Files (x86)Windows Kits10Lib10.0.17763.0umx86kernel32.lib
I thought the problem would be fixed with addind LIB to my environmental varibales as I didnt have one. But after Icreated it I still get the same error even though I get the path after typing ‘set LIB’ in the terminal in VS Code.
LIB=C:Program Files (x86)Microsoft Visual Studio2019BuildToolsVCToolsMSVC14.21.27702libx86;%LIB%; C:Program Files (x86)Windows Kits10Lib10.0.17763.0umx86kernel32.lib
LIBPATH=C:Program Files (x86)Microsoft Visual Studio2019BuildToolsVCToolsMSVC14.21.27702libx86;C:Program Files (x86)Microsoft Visual Studio2019BuildToolsVCToolsMSVC14.21.27702libx86storereferences;C:WindowsMicrosoft.NETFrameworkv4.0.30319;
CoreRT needs the 64-bit version of the kernel32.lib that lives in the x64 subdirectory, e.g. ...umx64kernel32.lib
Ok, I changed the path, but it didn’t change anything.
I do have another version (10.0.18362.0) to choose when I’m in the lib folder apart from 10.0.17763.0, so I did add this path aswell and tried to have just one of them in there, which didn’t show any changes.
Try Downloading the Latest SDK from The Microsoft Website It Worked for me.I had the same error too
Thank you! I was just having problems and this fixed it.
Hi Steve,
Here’s the Help | About info.
Cheers,
Leigh
Microsoft Visual Studio 2010
Version 10.0.40219.1 SP1Rel
Microsoft .NET Framework
Version 4.5.50938 SP1Rel
Installed Version: Ultimate
Microsoft Visual Basic 2010 01019-532-2002102-70444
Microsoft Visual Basic 2010
Microsoft Visual C# 2010 01019-532-2002102-70444
Microsoft Visual C# 2010
Microsoft Visual C++ 2010 01019-532-2002102-70444
Microsoft Visual C++ 2010
Microsoft Visual Studio 2010 Architecture and Modeling Tools 01019-532-2002102-70444
Microsoft Visual Studio 2010 Architecture and Modeling Tools
UML® and Unified Modeling Language™ are trademarks or registered trademarks of the Object Management Group, Inc. in the United States and other countries.
Microsoft Visual Studio 2010 Code Analysis Spell Checker 01019-532-2002102-70444
Microsoft Visual Studio 2010 Code Analysis Spell Checker
Portions of International CorrectSpell™ spelling correction system © 1993 by Lernout & Hauspie Speech Products N.V. All rights reserved.
The American Heritage® Dictionary of the English Language, Third Edition Copyright © 1992 Houghton Mifflin Company. Electronic version licensed from Lernout & Hauspie Speech Products N.V. All rights reserved.
Microsoft Visual Studio 2010 Team Explorer 01019-532-2002102-70444
Microsoft Visual Studio 2010 Team Explorer
AWS Toolkit for Visual Studio 2010 1.6.3.0
AWS Toolkit for Visual Studio 2010.
Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
This software includes third party software subject to the following copyrights:
— WPF Toolkit for charting and grid controls, Microsoft Public License (Ms-PL)
[http://wpf.codeplex.com/license]
— Logging from log4net, Apache License
[http://logging.apache.org/log4net/license.html]
— Putty for PPK to PEM conversion, MIT license
[http://www.chiark.greenend.org.uk/~sgtatham/putty/licence.html]
— NGit for AWS Elastic Beanstalk incremental push
[https://github.com/mono/ngit/blob/master/NGit.license.txt]
— NSch dependency for NGit
[https://github.com/mono/ngit/blob/master/NSch.license.txt]
— Sharpen dependency for NGit
[https://github.com/mono/ngit/blob/master/Sharpen/AssemblyInfo.cs]
— ICSharpCode.SharpZipLib dependency for NGit
[http://www.icsharpcode.net/opensource/sharpziplib/]
— Mono.Posix.dll and Mono.Security.dll dependencies for NGit
[http://mono-project.com/FAQ:_Licensing#Licensing]
— MPFProj for Visual Studio Project Framework
[http://mpfproj10.codeplex.com/license]
— JSONLint for JSON validation
[https://github.com/zaach/jsonlint/blob/master/README.md]
— Noesis.Javascript.dll for JSON validation
[http://javascriptdotnet.codeplex.com/license]
Critical Update for Microsoft Visual Studio 2010 Ultimate — ENU (KB2938807) KB2938807
This critical update is for Microsoft Visual Studio 2010 Ultimate — ENU.
If you later install a more recent service pack, this critical update will be uninstalled automatically.
For more information, visit http://support.microsoft.com/kb/2938807.
Crystal Reports Templates for Microsoft Visual Studio 2010
Crystal Reports Templates for Microsoft Visual Studio 2010
Hotfix for Microsoft Visual Studio 2010 Ultimate — ENU (KB2529927) KB2529927
This hotfix is for Microsoft Visual Studio 2010 Ultimate — ENU.
If you later install a more recent service pack, this hotfix will be uninstalled automatically.
For more information, visit http://support.microsoft.com/kb/2529927.
Hotfix for Microsoft Visual Studio 2010 Ultimate — ENU (KB2548139) KB2548139
This hotfix is for Microsoft Visual Studio 2010 Ultimate — ENU.
If you later install a more recent service pack, this hotfix will be uninstalled automatically.
For more information, visit http://support.microsoft.com/kb/2548139.
Hotfix for Microsoft Visual Studio 2010 Ultimate — ENU (KB2549864) KB2549864
This hotfix is for Microsoft Visual Studio 2010 Ultimate — ENU.
If you later install a more recent service pack, this hotfix will be uninstalled automatically.
For more information, visit http://support.microsoft.com/kb/2549864.
Hotfix for Microsoft Visual Studio 2010 Ultimate — ENU (KB2565057) KB2565057
This hotfix is for Microsoft Visual Studio 2010 Ultimate — ENU.
If you later install a more recent service pack, this hotfix will be uninstalled automatically.
For more information, visit http://support.microsoft.com/kb/2565057.
Intel(R) Visual Fortran Package ID: w_fcompxe_2013_sp1.3.202
Intel(R) Visual Fortran Composer XE 2013 SP1 Update 3 Integration for Microsoft Visual Studio* 2010, 14.0.0092.2010, Copyright (C) 2002-2014 Intel Corporation
* Other names and brands may be claimed as the property of others.
Microsoft Visual Studio 2010 Ultimate — ENU Service Pack 1 (KB983509) KB983509
This service pack is for Microsoft Visual Studio 2010 Ultimate — ENU.
If you later install a more recent service pack, this service pack will be uninstalled automatically.
For more information, visit http://support.microsoft.com/kb/983509.
Security Update for Microsoft Visual Studio 2010 Ultimate — ENU (KB2645410) KB2645410
This security update is for Microsoft Visual Studio 2010 Ultimate — ENU.
If you later install a more recent service pack, this security update will be uninstalled automatically.
For more information, visit http://support.microsoft.com/kb/2645410.
VSdocman
Code commenter and documentation generator. http://www.helixoft.com. Copyright (c) Helixoft
12 Years Ago
No programs are running.Both is Visual Studio and Codeblocks…
both are showing the following error,
LINK : fatal error LNK1104: cannot open file ‘kernel32.lib’
I have google it, some say setting environment to «C:Program FilesMicrosoft SDKsWindowsv5.0» or reinstalling visual studio, or editing registry key «HKEY_CURRENT_USERSOFTWAREMicrosoftMicrosoftSDKsWindowsCurrentInstallFolder»(i didn’t find any MicrosoftSDKs under Microsoft) usually solves the problem…
But none of them worked for me…
Can anyone help.This is freaking me out.
Edited
12 Years Ago
by iamcreasy because:
n/a
Recommended Answers
How long has that been happening? Just recently or a very long time? Did you install something that may have affected the compiler’s installation? Try reinstalling Visual Studio, uninstall it completely first so that it will reinstall fresh.
Does kernel32.lib actually exist on the computer?
[edit]Oh, I reread …
Jump to Post
Hi,
I had the same problem when I installed new codeblocks version 10.05 recently. I solved it by entering the complete path to kernel32.lib that way:1. Identify kernel32.lib
on my computer, also running visual studio2008, I found complete path:
C:Program filesMicrosoft SDKsWindowsv6.0ALibkernel32.lib2. on codeblocks v10 choose
…
Jump to Post
seriously, this *.cpp file includes only the following line…
int main{ return 0; }N.B. I am in Codeblocks and i have changed the settings of linker as tesuji suggested.
>>> int main{ return 0; } ???
So what about this one:int main(){return …
Jump to Post
All 11 Replies
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
12 Years Ago
How long has that been happening? Just recently or a very long time? Did you install something that may have affected the compiler’s installation? Try reinstalling Visual Studio, uninstall it completely first so that it will reinstall fresh.
Does kernel32.lib actually exist on the computer?
[edit]Oh, I reread your post and see you may have already tried that. Do you also have the Platform SDK installed? If you do then remove it then reinstall it.
Edited
12 Years Ago
by Ancient Dragon because:
n/a
iamcreasy
0
Junior Poster in Training
12 Years Ago
How long has that been happening? Just recently or a very long time? Did you install something that may have affected the compiler’s installation? Try reinstalling Visual Studio, uninstall it completely first so that it will reinstall fresh.
[edit]Oh, I reread your post and see you may have already tried that. Do you also have the Platform SDK installed? If you do then remove it then reinstall it.
thanks for the reply…i was starting to loose hope.
Well the problem started recently, after I reinstalled my Windows….there is nothing installed that might affect compiler… 
I have uninstalled and reinstalled VS….but, nothing has changed…
12 Years Ago
Hi,
I had the same problem when I installed new codeblocks version 10.05 recently. I solved it by entering the complete path to kernel32.lib that way:
1. Identify kernel32.lib
on my computer, also running visual studio2008, I found complete path:
C:Program filesMicrosoft SDKsWindowsv6.0ALibkernel32.lib
2. on codeblocks v10 choose
Settings->Compiler and debugger-> linker setup
There ADD C:Program filesMicrosoft SDKsWindowsv6.0ALibkernel32.lib. I also added there odbc.lib to using odbc within c++
Both now work fine. There are no problems with new Visual Studio 2008. The same programs where I had had some trouble on codeblocks with kernel32.lib and odbc run perfectly there.
I hope this will also work on your codeblocks.
— tesu
Edited
12 Years Ago
by tesuji because:
n/a
iamcreasy
0
Junior Poster in Training
12 Years Ago
[edit]Oh, I reread your post and see you may have already tried that. Do you also have the Platform SDK installed? If you do then remove it then reinstall it.
Do you mean Windows SDK? Yes I think so, I saw something named Windows SDK while installing VS and «C:Program FilesMicrosoft SDKsWindows» folder contains v5.0 and v.6.0A..total 434MB of files.
I repaired the whole VS again…but, no improvement.
iamcreasy
0
Junior Poster in Training
12 Years Ago
Hi,
I had the same problem when I installed new codeblocks version 10.05 recently. I solved it by entering the complete path to kernel32.lib that way:1. Identify kernel32.lib
on my computer, also running visual studio2008, I found complete path:
C:Program filesMicrosoft SDKsWindowsv6.0ALibkernel32.lib2. on codeblocks v10 choose
Settings->Compiler and debugger-> linker setup
There ADD C:Program filesMicrosoft SDKsWindowsv6.0ALibkernel32.lib. I also added there odbc.lib to using odbc within c++Both now work fine. There are no problems with new Visual Studio 2008. The same programs where I had had some trouble on codeblocks with kernel32.lib and odbc run perfectly there.
I hope this will also work on your codeblocks.
— tesu
this doesn’t work…simple
int main{ return 0; }
gives me following error…
LIBCMT.lib(crt0.obj)||error LNK2019: unresolved external symbol __imp__GetCommandLineA@0 referenced in function ___tmainCRTStartup|
LIBCMT.lib(unhandld.obj)||error LNK2019: unresolved external symbol __imp__SetUnhandledExceptionFilter@4 referenced in function ___CxxSetUnhandledExceptionFilter|
LIBCMT.lib(invarg.obj)||error LNK2001: unresolved external symbol __imp__SetUnhandledExceptionFilter@4|
LIBCMT.lib(abort.obj)||error LNK2001: unresolved external symbol __imp__SetUnhandledExceptionFilter@4|
LIBCMT.lib(gs_report.obj)||error LNK2001: unresolved external symbol __imp__SetUnhandledExceptionFilter@4|
LIBCMT.lib(crt0dat.obj)||error LNK2019: unresolved external symbol __imp__GetModuleHandleW@4 referenced in function __crt_waiting_on_module_handle|
LIBCMT.lib(tidtable.obj)||error LNK2001: unresolved external symbol __imp__GetModuleHandleW@4|
LIBCMT.lib(crt0dat.obj)||error LNK2019: unresolved external symbol __imp__Sleep@4 referenced in function __crt_waiting_on_module_handle|
LIBCMT.lib(crtheap.obj)||error LNK2001: unresolved external symbol __imp__Sleep@4|
LIBCMT.lib(crt0dat.obj)||error LNK2019: unresolved external symbol __imp__GetProcAddress@8 referenced in function ___crtCorExitProcess|
LIBCMT.lib(tidtable.obj)||error LNK2001: unresolved external symbol __imp__GetProcAddress@8|
LIBCMT.lib(rand_s.obj)||error LNK2001: unresolved external symbol __imp__GetProcAddress@8|
LIBCMT.lib(crtmbox.obj)||error LNK2001: unresolved external symbol __imp__GetProcAddress@8|
LIBCMT.lib(crt0dat.obj)||error LNK2019: unresolved external symbol __imp__ExitProcess@4 referenced in function ___crtExitProcess|
LIBCMT.lib(crt0msg.obj)||error LNK2019: unresolved external symbol __imp__WriteFile@20 referenced in function __NMSG_WRITE|
LIBCMT.lib(crt0msg.obj)||error LNK2019: unresolved external symbol __imp__GetStdHandle@4 referenced in function __NMSG_WRITE|
LIBCMT.lib(ioinit.obj)||error LNK2001: unresolved external symbol __imp__GetStdHandle@4|
LIBCMT.lib(crt0msg.obj)||error LNK2019: unresolved external symbol __imp__GetModuleFileNameA@12 referenced in function __NMSG_WRITE|
LIBCMT.lib(stdargv.obj)||error LNK2001: unresolved external symbol __imp__GetModuleFileNameA@12|
LIBCMT.lib(a_env.obj)||error LNK2019: unresolved external symbol __imp__FreeEnvironmentStringsA@4 referenced in function ___crtGetEnvironmentStringsA|
LIBCMT.lib(a_env.obj)||error LNK2019: unresolved external symbol __imp__GetEnvironmentStrings@0 referenced in function ___crtGetEnvironmentStringsA|
LIBCMT.lib(a_env.obj)||error LNK2019: unresolved external symbol __imp__FreeEnvironmentStringsW@4 referenced in function ___crtGetEnvironmentStringsA|
LIBCMT.lib(tzset.obj)||error LNK2001: unresolved external symbol __imp__WideCharToMultiByte@32|
LIBCMT.lib(wtombenv.obj)||error LNK2001: unresolved external symbol __imp__WideCharToMultiByte@32|
LIBCMT.lib(a_env.obj)||error LNK2019: unresolved external symbol __imp__WideCharToMultiByte@32 referenced in function ___crtGetEnvironmentStringsA|
LIBCMT.lib(a_loc.obj)||error LNK2001: unresolved external symbol __imp__WideCharToMultiByte@32|
LIBCMT.lib(a_map.obj)||error LNK2001: unresolved external symbol __imp__WideCharToMultiByte@32|
LIBCMT.lib(convrtcp.obj)||error LNK2001: unresolved external symbol __imp__WideCharToMultiByte@32|
LIBCMT.lib(a_map.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(a_str.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(a_cmp.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(inithelp.obj)||error LNK2019: unresolved external symbol __imp__GetLastError@0 referenced in function ___getlocaleinfo|
LIBCMT.lib(free.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(a_loc.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(realloc.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(a_env.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(tidtable.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(winsig.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(rand_s.obj)||error LNK2001: unresolved external symbol __imp__GetLastError@0|
LIBCMT.lib(a_env.obj)||error LNK2019: unresolved external symbol __imp__GetEnvironmentStringsW@0 referenced in function ___crtGetEnvironmentStringsA|
LIBCMT.lib(ioinit.obj)||error LNK2019: unresolved external symbol __imp__SetHandleCount@4 referenced in function __ioinit|
LIBCMT.lib(ioinit.obj)||error LNK2019: unresolved external symbol __imp__GetFileType@4 referenced in function __ioinit|
LIBCMT.lib(ioinit.obj)||error LNK2019: unresolved external symbol __imp__GetStartupInfoA@4 referenced in function __ioinit|
LIBCMT.lib(ioinit.obj)||error LNK2019: unresolved external symbol __imp__DeleteCriticalSection@4 referenced in function __ioterm|
LIBCMT.lib(mlock.obj)||error LNK2001: unresolved external symbol __imp__DeleteCriticalSection@4|
LIBCMT.lib(tidtable.obj)||error LNK2019: unresolved external symbol __imp__TlsGetValue@4 referenced in function __encode_pointer|
LIBCMT.lib(tidtable.obj)||error LNK2019: unresolved external symbol __imp__TlsAlloc@0 referenced in function ___crtTlsAlloc@4|
LIBCMT.lib(tidtable.obj)||error LNK2019: unresolved external symbol __imp__TlsSetValue@8 referenced in function ___set_flsgetvalue|
LIBCMT.lib(tidtable.obj)||error LNK2019: unresolved external symbol __imp__TlsFree@4 referenced in function __mtterm|
LIBCMT.lib(tidtable.obj)||error LNK2019: unresolved external symbol __imp__InterlockedIncrement@4 referenced in function __initptd|
||More errors follow but not being shown.|
||Edit the max errors limit in compiler options…|
||=== Build finished: 50 errors, 0 warnings ===|
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
12 Years Ago
Start a new project that only contains main(). The errors you posted appear as if there are other *.cpp files in the project.
iamcreasy
0
Junior Poster in Training
12 Years Ago
Start a new project that only contains main(). The errors you posted appear as if there are other *.cpp files in the project.
it is one file and a single line of code…
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
12 Years Ago
I’ll bet the file is including windows.h ???? One of the errors references a function Sleep() that is in that header file. Remove all the include files from that *.cpp file.
iamcreasy
0
Junior Poster in Training
12 Years Ago
I’ll bet the file is including windows.h ???? One of the errors references a function Sleep() that is in that header file. Remove all the include files from that *.cpp file.
seriously, this *.cpp file includes only the following line…
int main{ return 0; }
N.B. I am in Codeblocks and i have changed the settings of linker as tesuji suggested.
12 Years Ago
seriously, this *.cpp file includes only the following line…
int main{ return 0; }N.B. I am in Codeblocks and i have changed the settings of linker as tesuji suggested.
>>> int main{ return 0; } ???
So what about this one:
int main(){return 0;}
tesu
iamcreasy
0
Junior Poster in Training
12 Years Ago
>>> int main{ return 0; } ???
So what about this one:int main(){return 0;}tesu
Sorry, somehow the brackets was missed while typing.But i reopen the last file and there was brackets.
The problem has been solved, but in a weird manner,
1. I uninstalled the pro edition of VS and then installed the express edition(2008).
2. Then i uninstalled the express edition and reinstalled the pro edition, then everything became ok.
3. But the codeblocks issue was not solved, I have to relocate the kerner32.lib to make it work.
The interesting thing in the process is that, the folder structure inside the Microsoft SDKWindows folder has been changed.
When the problem existed there was two folder one names, «v5.0 » and other named «v6.0A»
«v5.0″ contained two folders, Include and Lib, where this lib contains Kernel32.lib.I added this kerner32.lib(from v5.0lib) to codeblock, which didn’t work.»v6.0» contained only «bin» & «Bootstrapper».
But when I went through, the VS’s Pro and express installation and uninstallation procedure, there were added two more folders inside «v6.0A» folder.They are Include & Lib.
Now, when I relocated kerner32.lib(from v6.0Alib) in the linker setup of codeblocks, everything worked fine.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Содержание
- Ошибка средств компоновщика 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 в результате чего создается:
Источник

