Не удается открыть файл kernel32 lib
I have a project on VS 2012. latest SDK is installed on the WIN 8 x64 computer, the project is targeting WIn32.
I have a clean build in Debug, but when I go to release I get the 1181 LNK error - cannot open input file kernel32.lib.
I have the file on the computer in several location, and in the VC directories there is $(WindowsSdkDir_71A)lib and $(WindowsSdkDir)\lib.
Using process monitor I've tried to rebuild and see where devenv.exe is looking for the file
** UPDATE: In debug it looks in the right place. in release it doesn't look for the sdk, but I see this:
Y:\MyProjectFofler\$(LibraryPath)\kernel32.lib PATH NOT FOUND and also several successful reads from the win8.0 sdk (which should be ok, but the result is the same, and I need it to read from the V7.1A SDK folder. )
What can it be and what might be the solution for this error ?
Не удается открыть файл "К:\програм.ОБЖ"
Чтобы устранить эту проблему для сборок из командной строки, проверьте параметры параметра /libpath . Также проверьте пути, указанные в переменной среды LIB, и пути, указанные в командной строке. Обязательно используйте двойные кавычки для всех путей, содержащих пробелы.
Чтобы устранить эту проблему в интегрированной среде разработки, при необходимости добавьте двойные кавычки для следующих свойств проекта:
свойство каталоги библиотеки на странице свойств конфигурации > VC++ каталоги
Свойство " Дополнительные каталоги библиотек " на странице свойств " Общие" компоновщика > свойств > конфигурации
Свойство Дополнительные зависимости на странице свойств входных данных компоновщика > свойств > конфигурации .
Библиотека vccorlib. lib
Дополнительные зависимости, указанные в интегрированной среде разработки
При указании отдельных библиотек в свойстве Дополнительные зависимости используйте пробелы для разделения имен библиотек. Не используйте запятые или точки с запятой. При использовании пункта меню Правка для открытия диалогового окна Дополнительные зависимости используйте символы новой строки для разделения имен, а не запятых, точек с запятой или пробелов. Также используйте символы новой строки при указании путей к библиотекам в папках библиотек и дополнительных каталогах библиотек .
Can't open a file built by your project
You may see this error if filename doesn't exist yet when the linker tries to access it. It can happen when one project depends on another in the solution, but the projects build in the wrong order. To fix this issue, make sure your project references are set in the project that uses the file. Then the missing file gets built before it's required. For more information, see Adding references in Visual Studio C++ projects and Managing references in a project.
Problems in the TMP environment variable
If the filename is named LNKnnn, it's a filename generated by the linker for a temporary file. The directory specified in the TMP environment variable may not exist. Or, more than one directory may be specified for the TMP environment variable. Only one directory path should be specified for the TMP environment variable.
Path or filename issues
Can't open file 'C:\Program.obj'
If you see the filename C:\Program.obj in the error message, wrap your library paths in double quotes. This error happens when an unwrapped path that begins with C:\Program Files gets passed to the linker. Unwrapped paths may also cause similar errors. Typically, they show an unexpected .obj file in the root of your drive.
To fix this issue for command-line builds, check the /LIBPATH option parameters. Also check the paths specified in the LIB environment variable, and the paths specified on the command line. Make sure to use double-quotes around any paths that include spaces.
To fix this issue in the IDE, add double-quotes as necessary to the following properties for your project:
The Library Directories property on the Configuration Properties > VC++ Directories property page,
The Additional Library Directories property in the Configuration Properties > Linker > General property page,
The Additional Dependencies property in the Configuration Properties > Linker > Input property page.
The vccorlib.lib library
There are no Spectre-mitigated libraries for Universal Windows (UWP) apps or components. If the error message includes vccorlib.lib, you may have enabled /Qspectre in a UWP project. Disable the /Qspectre compiler option to fix this issue. In Visual Studio, change the Spectre Mitigation property. It's found in the C/C++ > Code Generation page of the project Property Pages dialog.
Не удается открыть файл библиотеки Майкрософт
Библиотеки в проектах из сетевых или других источников
При построении проекта, скопированного с другого компьютера, расположения установки библиотеки могут отличаться. Для сборок из командной строки убедитесь, что для сборки правильно заданы пути к переменной среды LIB и библиотеке. в Visual Studio можно просмотреть и изменить текущие пути к библиотекам, заданные на страницах свойств проекта. на странице VC++ каталоги выберите элемент управления "раскрывающийся список" для свойства каталоги библиотек , а затем нажмите кнопку изменить. В разделе вычисленное значение диалогового окна каталоги библиотек перечислены текущие пути поиска файлов библиотек. Обновите эти пути, чтобы они указывали на локальные библиотеки.
Paths that are too long
You may see this error when the path for filename expands to more than 260 characters. If needed, rearrange your directory structure or shorten your folder and file names to shorten the paths.
Не удается открыть файл, созданный проектом
Эта ошибка может возникать, если файл filename еще не существует, когда компоновщик пытается получить к нему доступ. Это может произойти, когда один проект зависит от другого в решении, но проекты создаются в неправильном порядке. Чтобы устранить эту проблему, убедитесь, что ссылки проекта заданы в проекте, который использует этот файл. После этого отсутствующий файл будет создан до того, как он потребуется. дополнительные сведения см. в статьях добавление ссылок в проекты Visual Studio C++ и управление ссылками в проекте.
Слишком длинные пути
Эта ошибка может появиться, когда путь к файлу расширяется до 260 символов. При необходимости измените структуру каталогов или Сократите имена папок и файлов, чтобы сократить пути.
Библиотеки для розничной торговли, отладки или конкретной платформы
Эта ошибка может возникнуть при первой сборке для новой целевой платформы или конфигурации, например в розничной торговле или ARM64. в интегрированной среде разработки проверьте, установлены ли набор инструментов платформы и Windows SDK версии , указанной на странице свойств общие . также убедитесь, что необходимые библиотеки доступны в каталогах библиотек , указанных на странице свойств каталоги VC++. Проверьте свойства каждой конфигурации, например Debug, Retail, x86 или ARM64. Если одна сборка работает, но другая нет, Сравните параметры обоих параметров. Установите все отсутствующие необходимые инструменты и библиотеки.
Other common issues
Windows библиотеки, например kernel32. lib
Если файл, который не удается открыть, является одним из стандартных файлов библиотеки, предоставляемых корпорацией Майкрософт, например kernel32. lib, может возникнуть ошибка конфигурации проекта или ошибка установки. убедитесь, что Windows SDK установлен. если для проекта требуются другие библиотеки майкрософт, такие как MFC, убедитесь, что компоненты MFC также установлены установщиком Visual Studio. Вы можете снова запустить установщик, чтобы добавить дополнительные компоненты в любое время. Дополнительные сведения см. в Изменение Visual Studio. Используйте вкладку отдельные компоненты в установщике, чтобы выбрать конкретные библиотеки и пакеты SDK.
Другие распространенные проблемы
Проблемы в переменной среды TMP
Если имя файла LNKnnn, то это имя файла, созданного компоновщиком для временного файла. Каталог, указанный в переменной среды TMP, может не существовать. Кроме того, для переменной среды TMP может быть задано несколько каталогов. Для переменной среды TMP должен быть указан только один путь к каталогу.
Your app is locked by an antivirus scan
Antivirus programs often temporarily block access to newly created files, especially .exe and .dll executable files. To fix this issue, try excluding your project build directories from the antivirus scanner.
Слишком большие файлы
Эта ошибка может возникать из-за слишком большого размера файла. Библиотеки или объектные файлы, размер которых превышает гигабайт, может вызвать проблемы для 32-разрядного компоновщика. Возможным исправлением этой проблемы является использование 64-разрядного набора инструментов. Дополнительные сведения о том, как использовать 64-разрядный набор средств в командной строке, см. в разделе как включить 64-разрядный Visual C++ набор инструментов в командной строке. сведения о том, как использовать 64-разрядный набор инструментов в интегрированной среде разработки, см. в разделе использование MSBuild с 64-разрядным компилятором и инструментами. также см. статью Stack Overflow post: как сделать Visual Studio использовать собственную цепочки инструментов amd64.
Can't open a third-party library file
There are several common causes for this issue:
The path to your library file may be incorrect, or not wrapped in double-quotes. Or, you may not have specified it to the linker.
You may have installed a 32-bit version of the library but you're building for 64 bits, or the other way around.
The library may have dependencies on other libraries that aren't installed.
To fix a path issue for command-line builds, verify the LIB environment variable is set. Make sure it includes paths for all the libraries you use, and for every configuration you build. In the IDE, the library paths get set by the VC++ Directories > Library Directories property. Make sure all the directories that contain the libraries you need are listed here, for every configuration you build.
You might need to supply a library directory that overrides a standard library directory. On the command line, use the /LIBPATH option. In the IDE, use the Additional Library Directories property in the Configuration Properties > Linker > General property page for your project.
Make sure you install every version of the library you need for the configurations you build. Consider using the vcpkg package management utility to automate the installation and setup for many common libraries. When you can, it's best to build your own copies of third-party libraries. Then you're sure to have all the libraries' local dependencies, built for the same configurations as your project.
Retail, Debug, or platform-specific libraries
The error may occur when you first build for a new target platform or configuration, such as Retail, or ARM64. In the IDE, verify the Platform toolset and Windows SDK Version specified in the General property page are installed. Also verify the required libraries are available in the Library Directories specified in the VC++ Directories Property Page. Check the properties for each configuration, such as Debug, Retail, x86, or ARM64. If one build works but another doesn't, compare the settings for both. Install any missing required tools and libraries.
Дополнительная информация
Выполненный процесс не имеет правильного доступа безопасности к оконной станции и рабочему столу, которые связаны с процессом.
Член lpDesktop структуры STARTUPINFO CreateProcess CreateProcessAsUser , которая передается или указывает оконную станцию и рабочий стол, связанные с выполненным процессом. Выполненный процесс должен иметь правильный доступ к указанной оконной станции и рабочему столу.
В системе закончилась куча настольных компьютеров.
Каждый объект рабочего стола в системе имеет кучи настольных компьютеров, которые связаны с ним. Объект настольного компьютера использует кучу для хранения меню, крючков, строк и окон. В Windows Server 2003 и Windows XP 32-bit система выделяет кучи настольных компьютеров из буфера 48 мегабайт (МБ) по всей системе. Помимо кучи настольных компьютеров, драйверы принтеров и драйверы шрифтов также используют этот буфер.
Настольные компьютеры связаны с оконными станциями. Оконная станция может содержать ноль или несколько настольных компьютеров. Можно изменить размер кучи рабочего стола, выделенной для рабочего стола, связанного со станцией окна, изменив следующее значение реестра.
Мы не рекомендуем использовать переключатель /3GB. Переключатель /3 ГБ указан в Boot.ini файле. Переключатель /3 ГБ поддерживается только для 32-битных операционных систем. HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SubSystems\Windows
В Windows Server 2003 и Windows XP 32-bit данные по умолчанию для этого значения реестра будут напоминать следующие (все на одной строке):
В различных версиях Windows данные по умолчанию для этого значения реестра будут напоминать следующее:
Для Windows Vista RTM (32-bit)
Для Windows Vista SP1 Windows 7, Windows 8, Windows 8.1 (32-битный) и Windows Server 2008 (32-bit)
Для Windows Vista Windows, Windows 8, Windows 8.1 (64-битный), Windows Server 2008, Windows Server 2008 R2, Windows Server 2012 и Windows Server 2012 R2 (64- bit)
Числимые значения, следующие за тем SharedSection= , как распределяется кучи рабочего стола. Эти SharedSection значения указаны в килобайтах. Для настольных компьютеров существуют отдельные параметры, связанные с интерактивными и неинтеративными оконными станциями.
При изменении SharedSection значений в реестре необходимо перезапустить систему, чтобы изменения вступили в силу.
В этот раздел, описание метода или задачи включены действия, содержащие указания по изменению параметров реестра. Однако неправильное изменение параметров реестра может привести к возникновению серьезных проблем. Поэтому следует в точности выполнять приведенные инструкции. Для дополнительной защиты создайте резервную копию реестра, прежде чем редактировать его. Так вы сможете восстановить реестр, если возникнет проблема. Для получения дополнительной информации о том, как создать резервную копию и восстановить реестр, см. статью Сведения о резервном копировании и восстановлении реестра Windows.
Первое SharedSection значение (1024) — общий размер кучи, общий для всех настольных компьютеров. Это включает глобальную таблицу обработки. Эта таблица содержит ручки для окон, меню, значков, курсоров и так далее и общих параметров системы. Маловероятно, что вам когда-либо придется изменить это значение.
Второе значение SharedSection — размер кучи рабочего стола для каждого рабочего стола, связанного с интерактивной оконной станцией WinSta0. Объекты пользователей, такие как крюки, меню, строки и окна, потребляют память в этой кучи рабочего стола. Маловероятно, что вам когда-либо придется изменить это значение.
Каждый рабочий стол, созданный в интерактивной оконной станции, использует кучи рабочего стола по умолчанию 3072 КБ. По умолчанию система создает в Winsta0 следующие три настольных компьютера:
Рабочий стол приложения по Winsta0\default умолчанию будет использоваться всеми процессами, для которых указан член структуры STARTUPINFO.lpDesktop. Когда член структуры lpDesktop является NULL, оконная станция и рабочий стол наследуются от родительского процесса. Будут использоваться все службы, которые выполняются в учетной записи LocalSystem с помощью выбранного варианта запуска Desktop Winsta0\Default . Все эти процессы будут совместно работать с настольной кучей, связанной с настольным компьютером приложения по умолчанию.
Рабочий стол для сохранения экрана создается в интерактивной оконной станции (WinSta0) при отобра-ции сохранения экрана.
Третье значение SharedSection — размер кучи рабочего стола для каждого рабочего стола, связанного с неинтерактивной оконной станцией. Если этого значения нет, размер кучи рабочего стола для неинтерактивных оконных станций будет таким же, как и размер, заданный для интерактивных оконных станций (то есть второе значение SharedSection).
Если имеется только два значения SharedSection, можно добавить третье значение, чтобы указать размер настольной кучи для настольных компьютеров, созданных в неинтеративных оконных станциях.
Каждый процесс службы, который выполняется в учетной записи пользователя, получает новый рабочий стол в неинтерактивной оконной станции, созданной диспетчером управления службами (SCM). Поэтому каждая служба, которая выполняется в учетной записи пользователя, будет потреблять количество килобайт настольной кучи, указанное в третьем значении SharedSection. Все службы, которые выполняются в учетной записи LocalSystem, когда разрешить службе взаимодействовать с настольным компьютером не выбрана доля настольного компьютера по умолчанию в неинтерактивной станции windows службы (Service-0x0-3e7$).
Общая куча настольных компьютеров, используемая в интерактивных и неинтеративных оконных станциях, должна соответствовать буферу.
Уменьшение второго или третьего значения SharedSection увеличит число настольных компьютеров, которые можно создать в соответствующих оконных станциях. Меньшие значения ограничат количество крючков, меню, строк и окон, которые можно создать на рабочем столе. С другой стороны, увеличение второго или третьего значения SharedSection уменьшит количество созданных настольных компьютеров. Однако это также увеличит количество крючков, меню, строк и окон, которые можно создать на рабочем столе.
Так как SCM создает новый рабочий стол в неинтерактивной оконной станции для каждого процесса службы, запущенного под учетной записью пользователя, большее значение SharedSection позволит сократить число служб учетных записей пользователей, которые могут успешно работать в системе. Минимальное значение, которое может быть задано для второго или третьего значения SharedSection, — 128. Любая попытка использовать меньшее значение будет вместо этого использовать 128.
Куча настольных компьютеров выделяется User32.dll, когда процессу нужны объекты пользователя. Если приложение не зависит от User32.dll, оно не будет потреблять кучи настольных компьютеров.
В Windows Server 2003 определенное событие регистрируется в журнале System, если одно из следующих условий верно:
Если кучи рабочего стола заполнены, регистрируется следующее событие:
В этом случае увеличить размер кучи рабочего стола.
Если общая куча настольных компьютеров становится размером буфера в масштабах всей системы, регистрируется следующее событие:
В этом случае уменьшите размер кучи рабочего стола.
В Windows Server 2003 буфер всей системы составляет 20 МБ, если одно из следующих условий верно:
your program is already running or is loaded in the debugger, and
your library paths are incorrect, or aren't wrapped in double-quotes.
There are many other possible causes for this error. To narrow them down, first check what kind of file filename is. Then, use the following sections to help identify and fix the specific issue.
Windows libraries, such as kernel32.lib
If the file that can't be opened is one of the standard library files provided by Microsoft, such as kernel32.lib, you may have a project configuration error or an installation error. Verify the Windows SDK has been installed. If your project requires other Microsoft libraries, such as MFC, make sure the MFC components were also installed by the Visual Studio installer. You can run the installer again to add optional components at any time. For more information, see Modify Visual Studio. Use the Individual components tab in the installer to choose specific libraries and SDKs.
Versioned vcruntime libraries
If the error message has a versioned Microsoft library such as msvcr120.lib, the platform toolset for that compiler version may not be installed. To fix this issue, you have two options: Upgrade the project to use the current platform toolset, or install the older toolset and build the project unchanged. For more information, see Upgrading Projects from Earlier Versions of Visual C++ and Use native multi-targeting in Visual Studio to build old projects.
Причина
Этот сбой возникает по одной из следующих причин:
Выполненный процесс не имеет правильного доступа безопасности к оконной станции и рабочему столу, которые связаны с процессом.
В системе закончилась куча настольных компьютеров.
Справка, моей проблемы нет в списке!
В этой статье описывается проблема CreateProcess CreateProcessAsUser , из-за которой приложение, выполнено или может не выполняться.
Применяется к: Microsoft Windows
Исходный номер КБ: 184802
Неправильные разрешения для файла
Эта ошибка может возникать, если у вас недостаточно разрешений для доступа к файлу filename. Это может произойти, если для доступа к файлам библиотеки в защищенных системных каталогах используется обычная учетная запись пользователя. Или, если вы используете файлы, скопированные с других пользователей, у которых все еще есть исходный набор разрешений. Чтобы устранить эту проблему, переместите файл в каталог проекта с возможностью записи. Если перемещенный файл имеет недоступные разрешения, выполните команду takeown.exe в окне командной строки администратора, чтобы стать владельцем файла.
Не удается открыть сторонний файл библиотеки
Существует несколько распространенных причин этой проблемы.
Путь к файлу библиотеки может быть неверным или не заключен в двойные кавычки. Или, возможно, вы не указали его для компоновщика.
Возможно, вы установили 32-разрядную версию библиотеки, но при этом собираетесь на 64 бит или наоборот.
Библиотека может зависеть от других библиотек, которые не установлены.
Может потребоваться предоставить каталог библиотеки, переопределяющий каталог стандартной библиотеки. В командной строке используйте параметр /libpath . В интегрированной среде разработки используйте свойство Дополнительные каталоги библиотек на странице свойств " Общие" компоновщика > свойств > конфигурации для проекта.
Убедитесь, что установлены все версии библиотеки, необходимые для создаваемых конфигураций. воспользуйтесь программой управления пакетами vcpkg , чтобы автоматизировать установку и настройку для многих распространенных библиотек. По возможности лучше создавать собственные копии сторонних библиотек. Затем вы убедитесь, что все локальные зависимости библиотек созданы для тех же конфигураций, что и ваш проект.
Приложение выполняется или загружается в отладчике
Если filename — имя исполняемого файла или связанный с ним PDB-файл, см. раздел Если приложение уже запущено. Затем проверьте, загружен ли он в отладчик. Чтобы устранить эту проблему, перед повторным созданием программы закройте программу и выгрузите ее из отладчика. Если приложение открыто в другой программе, например в редакторе ресурсов, закройте его. Если программа не отвечает, может потребоваться завершить процесс с помощью диспетчера задач. Также может потребоваться закрыть и перезапустить Visual Studio.
Приложение заблокировано антивирусным сканированием
Антивирусные программы часто временно блокируют доступ к вновь созданным файлам, особенно .exe и .dll исполняемые файлы. Чтобы устранить эту проблему, попробуйте исключить каталоги сборки проекта из антивирусного сканера.
1 Answer 1
I ran into this using Visual Studio 2017. I was trying to get the Visual Studio project configurations to reference the external library .lib files I wanted. I managed to trigger this error when I removed any reference to the system libraries. I later figured out this can be corrected by including one of their macro values (though you can specify an absolute direct path, but that's probably not the best coding convention and prone to brittleness).
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:
VC++ Directories --> Library Directories : $(ProjectDir)lib; $(LibraryPath)
Note the $(LibraryPath) value will include extra values such as inherited from parents, and from what I can tell this is a verbose option. My folder project contained a folder called 'lib' which is why I had the first value there before the semicolon.
There are other common options I have used to specify the Library Directories value:
If you look at the section VC++ Directories --> Library Directories, you can click on the entry line and select 'Edit', then you can watch live previews of what Macros values will be evaluated and resolved to. If you need additional or more specialized values, click on the Macros button to look for more options.
Эта ошибка возникает, когда компоновщику не удается открыть файл для чтения или записи. Ниже перечислены две наиболее распространенные причины этой проблемы.
Программа уже запущена или загружена в отладчике, и
пути к библиотеке неверны или не заключены в двойные кавычки.
Существует множество других возможных причин этой ошибки. Чтобы сократить их, сначала проверьте Тип файла. Затем используйте следующие разделы для выявления и исправления конкретной проблемы.
Проблемы с путями или именами файлов
Недостаточно места на диске
Эта ошибка может возникать, если на диске недостаточно места. Компоновщик использует временные файлы в нескольких ситуациях. Даже если на диске достаточно места, большие ссылки могут выпустить или фрагментировать свободное место на диске. Рассмотрите возможность использования параметра /OPT (оптимизация) . выполнение транзитного исключения COMDAT считывает все объектные файлы несколько раз.
Параллельная синхронизация сборок
если вы используете параллельный вариант сборки, Visual Studio мог заблокировать файл в другом потоке. Чтобы устранить эту проблему, убедитесь, что один и тот же объект кода или библиотека не встроены в несколько проектов. Используйте зависимости сборки или ссылки проекта, чтобы выбрать в проекте созданные двоичные файлы.
Additional dependencies specified in the IDE
When you specify individual libraries in the Additional Dependencies property directly, use spaces to separate the library names. Don't use commas or semicolons. If you use the Edit menu item to open the Additional Dependencies dialog box, use newlines to separate the names, not commas, semicolons, or spaces. Also use newlines when you specify library paths in the Library Directories and Additional Library Directories dialog boxes.
Help, my issue isn't listed here!
When none of the issues listed here apply, you can use the feedback tools in Visual Studio for help. In the IDE, go to the menu bar and choose Help > Send Feedback > Report a Problem. Or, submit a suggestion by using Help > Send Feedback > Send a Suggestion. You can also use the Microsoft Docs Q&A site for questions, and the Visual Studio C++ Developer Community website. Use these sites to search for answers to questions and ask for help. For more information, see How to report a problem with the Visual C++ toolset or documentation.
If you've discovered a new way to fix this issue that we should add to this article, let us know. You can send us feedback by using the button below for this page. Use it to create a new issue in our C++ documentation GitHub repo. Thanks!
I don't know what more to say. I just downloaded this compiler yesterday and it was working fine. I wanted to upgrade from 32-bit programming to 64-bit so I could work with Assembly, so I downloaded this SDK. I searched on Google and even here on Stackoverflow. Google didn't help much, but I found a post here that seemed similar to mine but the answers didn't do much justice. Does anyone know why this error is occurring and how I can get rid of it?
I'd try this: First search your Program Files directory to see where kernel32.lib is installed, then check the Library Directories listed in your project's VC++ Directories property page and verify that the paths are correct.
This was triggered by path mix-ups between multiple SDK installations for my VS2017 installation. I used the VS2017 installer to remove all Win10 SDKs and Toolsets (140 and 141), updated my installation, then re-installed them via the VS2017 installer. After that, problem solved.
Parallel build synchronization
If you're using a parallel build option, Visual Studio may have locked the file on another thread. To fix this issue, verify the same code object or library isn't built in multiple projects. Use build dependencies or project references to pick up built binaries in your project.
Симптомы
Инициализация динамической библиотеки\system32\user32.dll не удалось. Процесс завершается ненормально. Инициализация динамической библиотеки\system32\kernel32.dll не удалось. Процесс завершается ненормально.
Кроме того, неудачный процесс возвращает код выхода 128 или следующий:
обновленные библиотеки Windows SDK
Can't open your app or its .pdb file
Incorrect file permissions
This error can occur if you have insufficient file permissions to access filename. It may happen if you use an ordinary user account to access library files in protected system directories. Or, if you use files copied from other users that still have their original permissions set. To fix this issue, move the file to a writeable project directory. If the moved file has inaccessible permissions, run the takeown.exe command in an Administrator command window to take ownership of the file.
Не удается открыть приложение или его PDB-файл
Библиотеки vcruntime с отслеживанием версий
Libraries in projects from online or other sources
If you build a project copied from another computer, the library installation locations may be different. For command-line builds, verify the LIB environment variable and library paths are set correctly for the build. In Visual Studio, you can see and edit the current library paths set in the Property pages for your project. In the VC++ Directories page, choose the drop-down control for the Library Directories property, then choose Edit. The Evaluated value section of the Library Directories dialog lists the current paths searched for library files. Update these paths to point to your local libraries.
Files that are too large
This error can occur because the file is too large. Libraries or object files more than a gigabyte in size may cause problems for the 32-bit linker. A possible fix for this issue is to use the 64-bit toolset. For more information on how to use the 64-bit toolset at the command line, see How to: Enable a 64-Bit Visual C++ Toolset on the Command Line. For information on how to use the 64-bit toolset in the IDE, see Using MSBuild with the 64-bit Compiler and Tools. Also see this Stack Overflow post: How to make Visual Studio use the native amd64 toolchain.
Can't open a Microsoft library file
13 Answers 13
Check the VC++ directories, in VS 2010 these can be found in your project properties. Check whether $(WindowsSdkDir)\lib is included in the directories list, if not, manually add it. If you're building for X64 platform, you should select X64 from the “Platform” ComboBox, and make sure that $(WindowsSdkDir)\lib\x64 is included in the directories list.
There are a lot of directories. How do I know which one to add it to? For example, there's Executable Directories, Include Directories, etc. Here's a screen shot.
You'll probably need to modify all of them. Bin directory of the sdk goes in the executable directories property, the lib directory goes in the library and so on
You added them as an environment variable or a full path. If its the fOrmer, did you check if that variable was recognised by VS
I simply copy-pasted $(WindowsSdkDir)\lib between the semi-colons ; where I did not see one in the full path.
Well, you need to check if that variable exists.. Simply from the vc++ directories windows, click on any value box, you'll notice an drop arrow, click that and select edit. From the new dialog that popped up, expand macros and see if $(WindowsSdkDir) exists and make sure that the path it refers to is valid. I not then you can simply replace $(WindowsSdkDir) mentioned in my answer with the full path of the sdk.
Change the platform toolset to: "Windows7.1SDK" under project properties->configuration properties->general
This worked instantaneously for me. I had (over time) installed a few tools, and when I came back to my VC++ project, it would not compile (missing headers) etc. I started to hand code include paths, that worked, then I hit link errors, then I tried this solution, and as I said, it just worked!! Many thanks.
Make sure you have in VC++ directories (Right click project, Click Property Page),
- Include Directories: $(IncludePath)
- List item Library Directories: $(LibraryPath)
For command line (i.e. - makefile) users only:
- When you install VC++ Express, it is 32-bit only. So, things go into C:\Program Files (x86).
- Then, you decide to upgrade to 64-bit capabillities. So, you install the SDK. But it is 64-bit capable. So, things go into C:\Program Files.
(Don't miss the "v7.0A" to "v7.1" change, as well.)
Add lib path of WindowsSdks in project->properties->Configuration Properties->VC++ Directories -> Library directories.
I added following path and error goes::
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib;
I got a similar error, the problem stopped when I checked my "Linker -> Input -> Additional Dependencies" list in the project properties. I was missing a semi colon ";" just before "%(AdditionalDependencies)". I also had the same entry in twice. You should edit this list separately for Debug and Release.
+ vote for reminding me that settings change when switching from debug to release, or Win32 to x64. Bah, this project I'm working on his a lot of pre-reqs set before you can do anything, and I made a bonehead mistake and forgot to switch to the correct configuration before tweaking all the values.
I had a differnt problem on Windows 10 with Visual Studio 2017 but with the same effects. I think my problems came down to VS being installed onto a drive other than "C:\". I solved the problem by Reinstalling Windows 10 SDK
First I had to uninstall the Windows SDK (there were two versions installed). Then ran the executable. Once installed, ran visual studio and it worked fine.
I just met and solved this problem by myself. My problem is a little different. I'm using visual studio on Windows 10. When I create the project, the Target Platform Version was automatically set to 10.0.15063.0 . But there is no kernel32.lib for this version of SDK, neither are other necessary header files and lib files. So I modified the Target Platform Version to 8.1 . And it worked.
Environment:
- Windows 10
- Visual Studio 2015
- Visual C++
Solution:
- Open the project's Property Page ;
- Navigate to General page;
- Modify Target Platform Version to the desired target platform (e.g. 8.1 ).
gero's solution worked for me.
In Visual Studios 2012, take the following steps.
- Go to Solution Explorer
- Right click on your project
- Go to Properties
- Configuration Properties -> General
- Platform Toolset -> change to Windows7.1SDK
If the above solution doesn't work, check to see if you have $(LibraryPath) in Properties->VC++ Directories->Library Directories. If you are missing it, try adding it.
OS : Win10, Visual Studio 2015
Solution : Go to control panel ---> uninstall program ---MSvisual studio ----> change ---->organize = repair
and repair it. Note that you must connect to internet until repairing finish.
Today in Visual Studio 2017 I had the same problem.
The cause in my case turned out to be a bad environment setting in NETFXSDKDir ( NETFXSDKDir=C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1 ). It needs to be instead NETFXSDKDir=C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86 . Specifically, as set in this batch file (my directory actually has 4 different files) for the Command Prompt for VS2017:
as I am reluctant to change one of the "as installed" batch files… even more as that batch file calls another yet another:
. instead for my specific C++ command-line app, I simply added the explicit path text: ;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86 for a total string in "Library Directories" like this: $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86 . (Right click on project, Properties → Configuration Properties → VC++ Directories → Library Directories.) That resolved my "fatal error LNK1104: cannot open file 'kernel32.lib'" error. I found that hint in this GitHub issue.
Note this is reproducible in Visual Studio 2017 Enterprise 2017 Version 15.1 (26403.0) even after successful "repair" install… when creating a new Visual C++ Win32 Console Application and attempting to compile.
In fact, unless a blank application is created, the default template also includes reference to and with that I get this additional error: Error (active) E1696 cannot open source file "SDKDDKVer.h" . So I created an empty C++ project.
Your app is running, or it's loaded in the debugger
When filename is your executable's name, or an associated .pdb file, see if your application is already running. Then check whether it's loaded in a debugger. To fix this issue, stop the program and unload it from the debugger before building it again. If the app is open in another program, such as a resource editor, close it. If your program is unresponsive, you may need to use Task Manager to end the process. You might also need to close and restart Visual Studio.
Insufficient disk space
The error can occur when you don't have enough disk space. The linker uses temporary files in several cases. Even if you have sufficient disk space, a large link can deplete or fragment the available disk space. Consider using the /OPT (Optimizations) option; doing transitive COMDAT elimination reads all the object files multiple times.
Updated Windows SDK libraries
This error can occur when the Visual Studio path to the Windows SDK is out of date. It may happen if you install a newer Windows SDK independently of the Visual Studio installer. To fix it in the IDE, update the paths specified in the VC++ Directories property page. Set the version in the path to match the new SDK. If you use the Developer Command Prompt, update the batch file that initializes the environment variables with the new SDK paths. This problem can be avoided by using the Visual Studio installer to install updated SDKs.
Читайте также: