Error lnk2019 unresolved external symbol declspec dllimport public cdecl

I'm building an application against some legacy, third party libraries, and having problems with the linking stage. I'm trying to compile with Visual Studio 9. My compile command is: cl -DNT40 -

I’m building an application against some legacy, third party libraries, and having problems with the linking stage. I’m trying to compile with Visual Studio 9. My compile command is:

cl -DNT40 -DPOMDLL -DCRTAPI1=_cdecl
-DCRTAPI2=cdecl -D_WIN32 -DWIN32 -DWIN32_LEAN_AND_MEAN -DWNT -DBYPASS_FLEX -D_INTEL=1 -DIPLIB=none -I. -I"D:srcinclude" -I"C:Program FilesMicrosoft Visual Studio
9.0VCinclude" -c -nologo -EHsc -W1 -Ox -Oy- -MD mymain.c

The code compiles cleanly. The link command is:

link -debug -nologo -machine:IX86
-verbose:lib -subsystem:console mymain.obj wsock32.lib advapi32.lib
msvcrt.lib oldnames.lib kernel32.lib
winmm.lib [snip large list of
dependencies] D:srclibapp_main.obj
-out:mymain.exe

The errors that I’m getting are:

app_main.obj : error LNK2019:
unresolved external symbol
"__declspec(dllimport) public: void
__thiscall std::locale::facet::_Register(void)"
(__imp_?_Register@facet@locale@std@@QAEXXZ)
referenced in function "class
std::ctype<char> const & __cdecl
std::use_facet<class std::ctype<char>
(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)

app_main.obj : error LNK2019:
unresolved external symbol
"__declspec(dllimport)  public: static
unsigned int __cdecl
std::ctype<char>::_Getcat(class
std::locale::facet const * *)"
(__imp_?_Getcat@?$ctype@D@std@@SAIPAPBVfacet@locale@2@@Z)
referenced in function "class
std::ctype<char> const & __cdecl
std::use_facet<class std::ctype<char>
(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)

app_main.obj : error LNK2019:
unresolved external symbol
"__declspec(dllimport)  public: static
unsigned int __cdecl
std::ctype<unsigned
short>::_Getcat(class
std::locale::facet const * *)"
(__imp_?_Getcat@?$ctype@G@std@@SAIPAPBVfacet@locale@2@@Z)
referenced in function "class
std::ctype<unsigned short> const &
__cdecl std::use_facet<class std::ctype<unsigned short> >(class
std::locale const &)"
(??$use_facet@V?$ctype@G@std@@@std@@YAABV?$ctype@G@0@ABVlocale@0@@Z)

mymain.exe : fatal error LNK1120: 3
unresolved externals

Notice that these errors are coming from the legacy code, not my code — app_main.obj is part of the legacy code, while mymain.c is my source. I’ve done some searching around, and what that I’ve read says that this type of error is caused by a mismatch with the -MD switch between my code and the library that I’m linking to. Since I’m dealing with legacy code, a solution has to come from my environment. It’s been a long time since I’ve done C++ work, and even longer since I’ve used Visual Studio, so I’m hoping that this is just some ignorance on my part. Any ideas on how to get these resolved?

Содержание

  1. Ошибка средств компоновщика LNK2019
  2. Возможные причины
  3. Исходный файл, содержащий определение символа, не компилируется
  4. Файл объекта или библиотека, содержащие определение символа, не связана
  5. Объявление символа не совпадает с определением символа.
  6. Функция используется, но тип или число параметров не совпадают с определением функции.
  7. Функция или переменная объявлена, но не определена
  8. Соглашение о вызовах отличается между объявлением функции и определением функции.
  9. Символ определяется в файле C, но объявлен без использования extern «C» в файле C++.
  10. Символ определяется как static и позже ссылается за пределами файла.
  11. Член static класса не определен
  12. Зависимость сборки определяется только как зависимость проекта в решении
  13. Точка входа не определена
  14. Создание консольного приложения с помощью параметров для приложения Windows
  15. Попытка связать 64-разрядные библиотеки с 32-разрядным кодом или 32-разрядными библиотеками с 64-разрядным кодом
  16. Для встраивание функций в разные исходные файлы используются различные параметры компилятора.
  17. Автоматические переменные используются вне их области
  18. Вы вызываете встроенные функции или передаете типы аргументов в встроенные функции, которые не поддерживаются в целевой архитектуре.
  19. Вы смешиваете код, который использует машинный wchar_t код с кодом, который не используется
  20. При связывании устаревшей библиотеки static возникают ошибки *printf* и *scanf* функции.
  21. Проблемы со сторонними библиотеками и vcpkg
  22. Средства диагностики
  23. Примеры
  24. Символ объявлен, но не определен
  25. Элемент static данных объявлен, но не определен
  26. Параметры объявления не соответствуют определению
  27. Несогласованные wchar_t определения типов
  28. См. также раздел
  29. Linker Tools Error LNK2019
  30. Possible causes
  31. The source file that contains the definition of the symbol isn’t compiled
  32. The object file or library that contains the definition of the symbol isn’t linked
  33. The declaration of the symbol isn’t spelled the same as the definition of the symbol
  34. A function is used but the type or number of the parameters don’t match the function definition
  35. A function or variable is declared but not defined
  36. The calling convention is different between the function declaration and the function definition
  37. A symbol is defined in a C file, but declared without using extern «C» in a C++ file
  38. A symbol is defined as static and then later referenced outside the file
  39. A static member of a class isn’t defined
  40. A build dependency is only defined as a project dependency in the solution
  41. An entry point isn’t defined
  42. You build a console application by using settings for a Windows application
  43. You attempt to link 64-bit libraries to 32-bit code, or 32-bit libraries to 64-bit code
  44. You use different compiler options for function inlining in different source files
  45. You use automatic variables outside their scope
  46. You call intrinsic functions or pass argument types to intrinsic functions that aren’t supported on your target architecture
  47. You mix code that uses native wchar_t with code that doesn’t
  48. You get errors for *printf* and *scanf* functions when you link a legacy static library
  49. Third-party library issues and vcpkg
  50. Diagnosis tools
  51. Examples
  52. A symbol is declared but not defined
  53. A static data member is declared but not defined
  54. Declaration parameters don’t match the definition
  55. Inconsistent wchar_t type definitions
  56. See also

Ошибка средств компоновщика LNK2019

неразрешенный externсимвол al «symbol«, на который ссылается функция «function«

Скомпилированный код для функции создает ссылку или вызов символа, но компоновщик не может найти определение символа ни в одной из библиотек или файлов объектов.

За этим сообщением об ошибке следует неустранимая ошибка LNK1120. Чтобы устранить ошибку LNK1120, сначала необходимо исправить все ошибки LNK2001 и LNK2019.

Возможные причины

Существует множество способов получения этой ошибки. Все они включают ссылку на функцию или переменную, для которых компоновщик не может разрешить или найти определение. Компилятор может определить, когда символ не объявлен, но не может определить, когда символ не определен. Это связано с тем, что определение может находиться в другом исходном файле или библиотеке. Если символ ссылается, но никогда не определен, компоновщик создает неразрешенную externошибку символа al.

Ниже приведены некоторые распространенные проблемы, вызывающие ошибку LNK2019.

Исходный файл, содержащий определение символа, не компилируется

В Visual Studio убедитесь, что исходный файл, определяющий символ, компилируется как часть проекта. Проверьте выходной каталог промежуточной сборки на наличие соответствующего OBJ-файла. Если исходный файл не компилируется, щелкните его правой кнопкой мыши в Обозреватель решений и выберите пункт «Свойства«, чтобы проверить свойства файла. На странице«Общиесвойства> конфигурации» должен отображаться тип элементакомпилятора C/C++. В командной строке убедитесь, что исходный файл, содержащий определение, компилируется.

Файл объекта или библиотека, содержащие определение символа, не связана

В Visual Studio убедитесь, что файл объекта или библиотека, содержащие определение символа, связаны как часть проекта. В командной строке убедитесь, что список файлов для ссылки содержит файл объекта или библиотеку.

Объявление символа не совпадает с определением символа.

Убедитесь, что в объявлении и определении используются правильные орфографические и прописные буквы, а также везде, где используется или вызывается символ.

Функция используется, но тип или число параметров не совпадают с определением функции.

Объявление функции должно соответствовать определению. Убедитесь, что вызов функции соответствует объявлению и что объявление соответствует определению. Код, вызывающий шаблоны функций, также должен иметь соответствующие объявления шаблонов функций, которые включают те же параметры шаблона, что и определение. Пример несоответствия объявления шаблона см. в примере LNK2019e.cpp в разделе «Примеры».

Функция или переменная объявлена, но не определена

LNK2019 может возникать, если объявление существует в файле заголовка, но не реализовано соответствующее определение. Для функций-членов или static членов данных реализация должна включать селектор области класса. Пример см. в разделе Missing Function Body or Variable.

Соглашение о вызовах отличается между объявлением функции и определением функции.

Некоторые соглашения о вызовах ( __cdecl , __stdcall , __fastcall и __vectorcall ) кодируются как часть декорированного имени. Убедитесь, что соглашение о вызовах совпадает.

Символ определяется в файле C, но объявлен без использования extern «C» в файле C++.

Файл, скомпилированный как C, создает декорированные имена для символов, отличающихся от украшенных имен для тех же символов, объявленных в файле C++, если не используется extern «C» модификатор. Убедитесь, что объявление соответствует компоновке компиляции для каждого символа. Аналогично, если символ определяется в файле C++, который будет использоваться программой C, в определении следует использовать extern «C» .

Символ определяется как static и позже ссылается за пределами файла.

В C++ в отличие от C глобальные constмуравьи имеют static компоновку. Чтобы обойти это ограничение, можно включить const инициализации в файл заголовка и включить этот заголовок в CPP-файлыconst или сделать переменную неантой и использовать constссылку на муравей для доступа к ней.

Член static класса не определен

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

Зависимость сборки определяется только как зависимость проекта в решении

В более ранних версиях Visual Studio этот уровень зависимости был достаточным. Тем не менее, начиная с Visual Studio 2010, Visual Studio требует ссылки на проект в проект. Если у проекта нет ссылки на проект в проект, может появиться эта ошибка компоновщика. Чтобы устранить ошибку, добавьте ссылку одного проекта на другой.

Точка входа не определена

Код приложения должен определить соответствующую точку входа: main для wmain консольных приложений, а также WinMain wWinMain для приложений Windows. Дополнительные сведения см. в описании main аргументов WinMain или функций командной строки. Чтобы использовать пользовательскую точку входа, укажите параметр компоновщика (символ точки входа). /ENTRY

Создание консольного приложения с помощью параметров для приложения Windows

Если сообщение об ошибке похоже на неразрешенный externсимвол WinMain al, на который ссылается функцияfunction_name, ссылка используется /SUBSYSTEM:CONSOLE вместо /SUBSYSTEM:WINDOWS . Дополнительные сведения об этом параметре и инструкции по настройке этого свойства в Visual Studio см. в разделе /SUBSYSTEM (Указание подсистемы).

Попытка связать 64-разрядные библиотеки с 32-разрядным кодом или 32-разрядными библиотеками с 64-разрядным кодом

Библиотеки и файлы объектов, связанные с кодом, должны быть скомпилированы для той же архитектуры, что и код. Убедитесь, что библиотеки, на которые ссылается проект, компилируются для той же архитектуры, что и проект. Убедитесь, /LIBPATH что свойство или дополнительные каталоги библиотек указывают на библиотеки, созданные для правильной архитектуры.

Для встраивание функций в разные исходные файлы используются различные параметры компилятора.

Использование встроенных функций, определенных в CPP-файлах, и смешение в различных исходных файлах параметров компилятора для встраивания функций может привести к возникновению ошибки LNK2019. Для получения дополнительной информации см. Function Inlining Problems.

Автоматические переменные используются вне их области

Автоматические переменные (области видимости функции) могут использоваться только в области видимости данной функции. Эти переменные не могут объявляться extern и использоваться в других исходных файлах. Пример см. в разделе Automatic (Function Scope) Variables.

Вы вызываете встроенные функции или передаете типы аргументов в встроенные функции, которые не поддерживаются в целевой архитектуре.

Например, если вы используете встроенную AVX2 функцию, но не указываете /ARCH:AVX2 параметр компилятора, компилятор предполагает, что встроенная функция al extern. Вместо создания встроенной инструкции компилятор создает вызов externсимвола al с тем же именем, что и встроенная инструкция. Когда компоновщик пытается найти определение этой отсутствующей функции, он создает ошибку LNK2019. Убедитесь, что используются только встроенные и типы, поддерживаемые целевой архитектурой.

Вы смешиваете код, который использует машинный wchar_t код с кодом, который не используется

Работа по соответствию языкаМ C++, выполненная в Visual Studio 2005, по умолчанию сделала wchar_t собственный тип. Если не все файлы были скомпилированы с помощью одних и того же /Zc:wchar_t параметра, ссылки на типы могут не разрешаться в совместимые типы. Убедитесь, что wchar_t типы во всех библиотеках и файлах объектов совместимы. Обновление из wchar_t typedef или использование согласованных параметров /Zc:wchar_t при компиляции.

При связывании устаревшей библиотеки static возникают ошибки *printf* и *scanf* функции.

Библиотека static , созданная с помощью версии Visual Studio до Visual Studio 2015, может привести к ошибкам LNK2019 при связывании с UCRT. Файлы заголовков UCRT и теперь определяют многие *printf* варианты как *scanf* inline функции. Встроенные функции реализуются небольшим набором общих функций. Отдельные экспорты встроенных функций недоступны в стандартных библиотеках UCRT, которые экспортируют только общие функции. Существует несколько способов решения этой проблемы. Рекомендуется перестроить устаревшую библиотеку с текущей версией Visual Studio. Убедитесь, что код библиотеки использует стандартные заголовки для определений *printf* и *scanf* функций, вызвавших ошибки. Еще один вариант для устаревшей библиотеки, которую нельзя перестроить, — добавить legacy_stdio_definitions.lib в список библиотек, которые вы связываете. Этот файл библиотеки предоставляет символы и *printf* *scanf* функции, которые встраиваются в заголовки UCRT. Дополнительные сведения см. в разделе «Библиотеки » статьи «Общие сведения о потенциальных проблемах обновления».

Проблемы со сторонними библиотеками и vcpkg

Если эта ошибка возникает при попытке настроить стороннюю библиотеку в рамках сборки, рассмотрите возможность использования vcpkg. vcpkg — это диспетчер пакетов C++, который использует существующие инструменты Visual Studio для установки и сборки библиотеки. vcpkg поддерживает большой и растущий список сторонних библиотек. Он задает все свойства и зависимости конфигурации, необходимые для успешных сборок в рамках проекта.

Средства диагностики

Иногда трудно определить, почему компоновщик не может найти определенное определение символа. Часто проблема заключается в том, что вы не включили код, содержащий определение в сборке. Кроме того, варианты сборки создали разные декорированные имена для externсимволов al. Существует несколько средств и вариантов, которые помогут диагностировать ошибки LNK2019.

Параметр /VERBOSE компоновщика поможет определить файлы ссылок компоновщика. Этот параметр поможет проверить, включен ли файл, содержащий определение символа, в сборку.

Служебная /EXPORTS DUMPBIN программа позволяет /SYMBOLS определить, какие символы определены в файлах .dll и объектов или библиотек. Убедитесь, что экспортированные имена совпадают с декорированными именами, которые выполняет поиск компоновщика.

Служебная UNDNAME программа может показать эквивалентный неоцененный externсимвол al для украшенного имени.

Примеры

Ниже приведено несколько примеров кода, вызывающих ошибки LNK2019, а также сведения об устранении ошибок.

Символ объявлен, но не определен

В этом примере переменная al объявлена extern, но не определена:

Ниже приведен еще один пример объявления переменной и функции, но extern не предоставляется определение:

Если i и g не определены в одном из файлов, включенных в сборку, компоновщик создает LNK2019. Чтобы исправить ошибки, включите файл исходного кода, который содержит определения, в процесс компиляции. Кроме того, можно передать .obj файлы или .lib файлы, содержащие определения компоновщика.

Элемент static данных объявлен, но не определен

LNK2019 также может возникать, когда static член данных объявлен, но не определен. В следующем примере показано возникновение ошибки LNK2019 и приводятся сведения по ее устранению.

Параметры объявления не соответствуют определению

Код, вызывающий шаблоны функций, должен иметь соответствующие объявления шаблонов функций. Объявления должны содержать те же параметры шаблона, что и определение. В следующем примере показано возникновение ошибки LNK2019 для определяемого пользователем оператора и приводятся сведения по ее устранению.

Несогласованные wchar_t определения типов

В этом примере создается библиотека DLL с экспортом, который использует WCHAR , который разрешается wchar_t в .

Следующий пример использует библиотеку DLL в предыдущем примере и создает LNK2019, так как типы unsigned short* и WCHAR* не совпадают.

Чтобы устранить эту ошибку, измените unsigned short wchar_t WCHAR или скомпилируйте LNK2019g.cpp с помощью . /Zc:wchar_t-

См. также раздел

Дополнительные сведения о возможных причинах и решениях ошибок LNK2019, LNK2001 и LNK1120 см. в вопросе Stack Overflow: What is an undefined reference/unresolved external symbol error and how do I fix it?

Источник

unresolved external symbol ‘symbol‘ referenced in function ‘function

The compiled code for function makes a reference or call to symbol, but the linker can’t find the symbol definition in any of the libraries or object files.

This error message is followed by fatal error LNK1120. To fix error LNK1120, you must fix all LNK2001 and LNK2019 errors first.

Possible causes

There are many ways to get this error. All of them involve a reference to a function or variable that the linker couldn’t resolve, or find a definition for. The compiler can identify when a symbol isn’t declared, but it can’t tell when the symbol isn’t defined. It’s because the definition may be in a different source file or library. If a symbol is referred to but never defined, the linker generates an unresolved external symbol error.

Here are some common problems that cause LNK2019:

The source file that contains the definition of the symbol isn’t compiled

In Visual Studio, make sure the source file that defines the symbol gets compiled as part of your project. Check the intermediate build output directory for a matching .obj file. If the source file isn’t compiled, right-click on the file in Solution Explorer, and then choose Properties to check the properties of the file. The Configuration Properties > General page should show an Item Type of C/C++ Compiler. On the command line, make sure the source file that contains the definition is compiled.

The object file or library that contains the definition of the symbol isn’t linked

In Visual Studio, make sure the object file or library that contains the symbol definition is linked as part of your project. On the command line, make sure the list of files to link includes the object file or library.

The declaration of the symbol isn’t spelled the same as the definition of the symbol

Verify you use the correct spelling and capitalization in both the declaration and the definition, and wherever the symbol is used or called.

A function is used but the type or number of the parameters don’t match the function definition

The function declaration must match the definition. Make sure the function call matches the declaration, and that the declaration matches the definition. Code that invokes function templates must also have matching function template declarations that include the same template parameters as the definition. For an example of a template declaration mismatch, see sample LNK2019e.cpp in the Examples section.

A function or variable is declared but not defined

LNK2019 can occur when a declaration exists in a header file, but no matching definition is implemented. For member functions or static data members, the implementation must include the class scope selector. For an example, see Missing Function Body or Variable.

The calling convention is different between the function declaration and the function definition

Some calling conventions ( __cdecl , __stdcall , __fastcall , and __vectorcall ) are encoded as part of the decorated name. Make sure the calling convention is the same.

A symbol is defined in a C file, but declared without using extern «C» in a C++ file

A file that’s compiled as C creates decorated names for symbols that are different from the decorated names for the same symbols declared in a C++ file, unless you use an extern «C» modifier. Make sure the declaration matches the compilation linkage for each symbol. Similarly, if you define a symbol in a C++ file that will be used by a C program, use extern «C» in the definition.

A symbol is defined as static and then later referenced outside the file

In C++, unlike C, global constants have static linkage. To get around this limitation, you can include the const initializations in a header file and include that header in your .cpp files, or you can make the variable non-constant and use a constant reference to access it.

A static member of a class isn’t defined

A static class member must have a unique definition, or it will violate the one-definition rule. A static class member that can’t be defined inline must be defined in one source file by using its fully qualified name. If it isn’t defined at all, the linker generates LNK2019.

A build dependency is only defined as a project dependency in the solution

In earlier versions of Visual Studio, this level of dependency was sufficient. However, starting with Visual Studio 2010, Visual Studio requires a project-to-project reference. If your project doesn’t have a project-to-project reference, you may receive this linker error. Add a project-to-project reference to fix it.

An entry point isn’t defined

The application code must define an appropriate entry point: main or wmain for console applications, and WinMain or wWinMain for Windows applications. For more information, see main function and command-line arguments or WinMain function. To use a custom entry point, specify the /ENTRY (Entry-Point Symbol) linker option.

You build a console application by using settings for a Windows application

If the error message is similar to unresolved external symbol WinMain referenced in function function_name, link by using /SUBSYSTEM:CONSOLE instead of /SUBSYSTEM:WINDOWS . For more information about this setting, and for instructions on how to set this property in Visual Studio, see /SUBSYSTEM (Specify Subsystem).

You attempt to link 64-bit libraries to 32-bit code, or 32-bit libraries to 64-bit code

Libraries and object files linked to your code must be compiled for the same architecture as your code. Make sure the libraries your project references are compiled for the same architecture as your project. Make sure the /LIBPATH or Additional Library Directories property points to libraries built for the correct architecture.

You use different compiler options for function inlining in different source files

Using inlined functions defined in .cpp files and mixing function inlining compiler options in different source files can cause LNK2019. For more information, see Function Inlining Problems.

You use automatic variables outside their scope

Automatic (function scope) variables can only be used in the scope of that function. These variables can’t be declared extern and used in other source files. For an example, see Automatic (Function Scope) Variables.

You call intrinsic functions or pass argument types to intrinsic functions that aren’t supported on your target architecture

For example, if you use an AVX2 intrinsic, but don’t specify the /ARCH:AVX2 compiler option, the compiler assumes that the intrinsic is an external function. Instead of generating an inline instruction, the compiler generates a call to an external symbol with the same name as the intrinsic. When the linker tries to find the definition of this missing function, it generates LNK2019. Make sure you only use intrinsics and types supported by your target architecture.

You mix code that uses native wchar_t with code that doesn’t

C++ language conformance work that was done in Visual Studio 2005 made wchar_t a native type by default. If not all files have been compiled by using the same /Zc:wchar_t settings, type references may not resolve to compatible types. Make sure wchar_t types in all library and object files are compatible. Either update from a wchar_t typedef, or use consistent /Zc:wchar_t settings when you compile.

You get errors for *printf* and *scanf* functions when you link a legacy static library

A static library that was built using a version of Visual Studio before Visual Studio 2015 may cause LNK2019 errors when linked with the UCRT. The UCRT header files , , and now define many *printf* and *scanf* variations as inline functions. The inlined functions are implemented by a smaller set of common functions. Individual exports for the inlined functions aren’t available in the standard UCRT libraries, which only export the common functions. There are a couple of ways to resolve this issue. The method we recommend is to rebuild the legacy library with your current version of Visual Studio. Make sure the library code uses the standard headers for the definitions of the *printf* and *scanf* functions that caused the errors. Another option for a legacy library that you can’t rebuild is to add legacy_stdio_definitions.lib to the list of libraries you link. This library file provides symbols for the *printf* and *scanf* functions that are inlined in the UCRT headers. For more information, see the Libraries section in Overview of potential upgrade issues.

Third-party library issues and vcpkg

If you see this error when you’re trying to configure a third-party library as part of your build, consider using vcpkg. vcpkg is a C++ package manager that uses your existing Visual Studio tools to install and build the library. vcpkg supports a large and growing list of third-party libraries. It sets all the configuration properties and dependencies required for successful builds as part of your project.

Sometimes it’s difficult to tell why the linker can’t find a particular symbol definition. Often the problem is that you haven’t included the code that contains the definition in your build. Or, build options have created different decorated names for external symbols. There are several tools and options that can help you diagnose LNK2019 errors.

The /VERBOSE linker option can help you determine which files the linker references. This option can help you verify whether the file that contains the definition of the symbol is included in your build.

The /EXPORTS and /SYMBOLS options of the DUMPBIN utility can help you discover which symbols are defined in your .dll and object or library files. Make sure the exported decorated names match the decorated names the linker searches for.

The UNDNAME utility can show you the equivalent undecorated external symbol for a decorated name.

Examples

Here are several examples of code that causes LNK2019 errors, together with information about how to fix the errors.

A symbol is declared but not defined

In this example, an external variable is declared but not defined:

Here’s another example where a variable and function are declared as extern but no definition is provided:

Unless i and g are defined in one of the files included in the build, the linker generates LNK2019. You can fix the errors by including the source code file that contains the definitions as part of the compilation. Alternatively, you can pass .obj files or .lib files that contain the definitions to the linker.

A static data member is declared but not defined

LNK2019 can also occur when a static data member is declared but not defined. The following sample generates LNK2019, and shows how to fix it.

Declaration parameters don’t match the definition

Code that invokes function templates must have matching function template declarations. Declarations must include the same template parameters as the definition. The following sample generates LNK2019 on a user-defined operator, and shows how to fix it.

Inconsistent wchar_t type definitions

This sample creates a DLL that has an export that uses WCHAR , which resolves to wchar_t .

The next sample uses the DLL in the previous sample, and generates LNK2019 because the types unsigned short* and WCHAR* aren’t the same.

To fix this error, change unsigned short to wchar_t or WCHAR , or compile LNK2019g.cpp by using /Zc:wchar_t- .

See also

For more information about possible causes and solutions for LNK2019, LNK2001, and LNK1120 errors, see the Stack Overflow question: What is an undefined reference/unresolved external symbol error and how do I fix it? .

Источник

title description ms.date f1_keywords helpviewer_keywords no-loc

Linker Tools Error LNK2019

All about the Microsoft Visual Studio Linker error LNK2019 and how to diagnose and correct it in C and C++ code.

09/07/2022

LNK2019

nochkclr.obj

LNK2019

_check_commonlanguageruntime_version

main

WinMain

wmain

wWinMain

__cdecl

__stdcall

__fastcall

__vectorcall

extern

static

const

ARCH

AVX2

wchar_t

VERBOSE

EXPORTS

SYMBOLS

DUMPBIN

UNDNAME

unresolved external symbol ‘symbol‘ referenced in function ‘function

The compiled code for function makes a reference or call to symbol, but the linker can’t find the symbol definition in any of the libraries or object files.

This error message is followed by fatal error LNK1120. To fix error LNK1120, you must fix all LNK2001 and LNK2019 errors first.

Possible causes

There are many ways to get this error. All of them involve a reference to a function or variable that the linker couldn’t resolve, or find a definition for. The compiler can identify when a symbol isn’t declared, but it can’t tell when the symbol isn’t defined. It’s because the definition may be in a different source file or library. If a symbol is referred to but never defined, the linker generates an unresolved external symbol error.

Here are some common problems that cause LNK2019:

The source file that contains the definition of the symbol isn’t compiled

In Visual Studio, make sure the source file that defines the symbol gets compiled as part of your project. Check the intermediate build output directory for a matching .obj file. If the source file isn’t compiled, right-click on the file in Solution Explorer, and then choose Properties to check the properties of the file. The Configuration Properties > General page should show an Item Type of C/C++ Compiler. On the command line, make sure the source file that contains the definition is compiled.

The object file or library that contains the definition of the symbol isn’t linked

In Visual Studio, make sure the object file or library that contains the symbol definition is linked as part of your project. On the command line, make sure the list of files to link includes the object file or library.

The declaration of the symbol isn’t spelled the same as the definition of the symbol

Verify you use the correct spelling and capitalization in both the declaration and the definition, and wherever the symbol is used or called.

A function is used but the type or number of the parameters don’t match the function definition

The function declaration must match the definition. Make sure the function call matches the declaration, and that the declaration matches the definition. Code that invokes function templates must also have matching function template declarations that include the same template parameters as the definition. For an example of a template declaration mismatch, see sample LNK2019e.cpp in the Examples section.

A function or variable is declared but not defined

LNK2019 can occur when a declaration exists in a header file, but no matching definition is implemented. For member functions or static data members, the implementation must include the class scope selector. For an example, see Missing Function Body or Variable.

The calling convention is different between the function declaration and the function definition

Some calling conventions (__cdecl, __stdcall, __fastcall, and __vectorcall) are encoded as part of the decorated name. Make sure the calling convention is the same.

A symbol is defined in a C file, but declared without using extern "C" in a C++ file

A file that’s compiled as C creates decorated names for symbols that are different from the decorated names for the same symbols declared in a C++ file, unless you use an extern "C" modifier. Make sure the declaration matches the compilation linkage for each symbol. Similarly, if you define a symbol in a C++ file that will be used by a C program, use extern "C" in the definition.

A symbol is defined as static and then later referenced outside the file

In C++, unlike C, global constants have static linkage. To get around this limitation, you can include the const initializations in a header file and include that header in your .cpp files, or you can make the variable non-constant and use a constant reference to access it.

A static member of a class isn’t defined

A static class member must have a unique definition, or it will violate the one-definition rule. A static class member that can’t be defined inline must be defined in one source file by using its fully qualified name. If it isn’t defined at all, the linker generates LNK2019.

A build dependency is only defined as a project dependency in the solution

In earlier versions of Visual Studio, this level of dependency was sufficient. However, starting with Visual Studio 2010, Visual Studio requires a project-to-project reference. If your project doesn’t have a project-to-project reference, you may receive this linker error. Add a project-to-project reference to fix it.

An entry point isn’t defined

The application code must define an appropriate entry point: main or wmain for console applications, and WinMain or wWinMain for Windows applications. For more information, see main function and command-line arguments or WinMain function. To use a custom entry point, specify the /ENTRY (Entry-Point Symbol) linker option.

You build a console application by using settings for a Windows application

If the error message is similar to unresolved external symbol WinMain referenced in function function_name, link by using /SUBSYSTEM:CONSOLE instead of /SUBSYSTEM:WINDOWS. For more information about this setting, and for instructions on how to set this property in Visual Studio, see /SUBSYSTEM (Specify Subsystem).

You attempt to link 64-bit libraries to 32-bit code, or 32-bit libraries to 64-bit code

Libraries and object files linked to your code must be compiled for the same architecture as your code. Make sure the libraries your project references are compiled for the same architecture as your project. Make sure the /LIBPATH or Additional Library Directories property points to libraries built for the correct architecture.

You use different compiler options for function inlining in different source files

Using inlined functions defined in .cpp files and mixing function inlining compiler options in different source files can cause LNK2019. For more information, see Function Inlining Problems.

You use automatic variables outside their scope

Automatic (function scope) variables can only be used in the scope of that function. These variables can’t be declared extern and used in other source files. For an example, see Automatic (Function Scope) Variables.

You call intrinsic functions or pass argument types to intrinsic functions that aren’t supported on your target architecture

For example, if you use an AVX2 intrinsic, but don’t specify the /ARCH:AVX2 compiler option, the compiler assumes that the intrinsic is an external function. Instead of generating an inline instruction, the compiler generates a call to an external symbol with the same name as the intrinsic. When the linker tries to find the definition of this missing function, it generates LNK2019. Make sure you only use intrinsics and types supported by your target architecture.

You mix code that uses native wchar_t with code that doesn’t

C++ language conformance work that was done in Visual Studio 2005 made wchar_t a native type by default. If not all files have been compiled by using the same /Zc:wchar_t settings, type references may not resolve to compatible types. Make sure wchar_t types in all library and object files are compatible. Either update from a wchar_t typedef, or use consistent /Zc:wchar_t settings when you compile.

You get errors for *printf* and *scanf* functions when you link a legacy static library

A static library that was built using a version of Visual Studio before Visual Studio 2015 may cause LNK2019 errors when linked with the UCRT. The UCRT header files <stdio.h>, <conio.h>, and <wchar.h>now define many *printf* and *scanf* variations as inline functions. The inlined functions are implemented by a smaller set of common functions. Individual exports for the inlined functions aren’t available in the standard UCRT libraries, which only export the common functions. There are a couple of ways to resolve this issue. The method we recommend is to rebuild the legacy library with your current version of Visual Studio. Make sure the library code uses the standard headers for the definitions of the *printf* and *scanf* functions that caused the errors. Another option for a legacy library that you can’t rebuild is to add legacy_stdio_definitions.lib to the list of libraries you link. This library file provides symbols for the *printf* and *scanf* functions that are inlined in the UCRT headers. For more information, see the Libraries section in Overview of potential upgrade issues.

Third-party library issues and vcpkg

If you see this error when you’re trying to configure a third-party library as part of your build, consider using vcpkg. vcpkg is a C++ package manager that uses your existing Visual Studio tools to install and build the library. vcpkg supports a large and growing list of third-party libraries. It sets all the configuration properties and dependencies required for successful builds as part of your project.

Diagnosis tools

Sometimes it’s difficult to tell why the linker can’t find a particular symbol definition. Often the problem is that you haven’t included the code that contains the definition in your build. Or, build options have created different decorated names for external symbols. There are several tools and options that can help you diagnose LNK2019 errors.

  • The /VERBOSE linker option can help you determine which files the linker references. This option can help you verify whether the file that contains the definition of the symbol is included in your build.

  • The /EXPORTS and /SYMBOLS options of the DUMPBIN utility can help you discover which symbols are defined in your .dll and object or library files. Make sure the exported decorated names match the decorated names the linker searches for.

  • The UNDNAME utility can show you the equivalent undecorated external symbol for a decorated name.

Examples

Here are several examples of code that causes LNK2019 errors, together with information about how to fix the errors.

A symbol is declared but not defined

In this example, an external variable is declared but not defined:

// LNK2019.cpp
// Compile by using: cl /EHsc /W4 LNK2019.cpp
// LNK2019 expected
extern char B[100];   // B isn't available to the linker
int main() {
   B[0] = ' ';   // LNK2019
}

Here’s another example where a variable and function are declared as extern but no definition is provided:

// LNK2019c.cpp
// Compile by using: cl /EHsc LNK2019c.cpp
// LNK2019 expected
extern int i;
extern void g();
void f() {
   i++;
   g();
}
int main() {}

Unless i and g are defined in one of the files included in the build, the linker generates LNK2019. You can fix the errors by including the source code file that contains the definitions as part of the compilation. Alternatively, you can pass .obj files or .lib files that contain the definitions to the linker.

A static data member is declared but not defined

LNK2019 can also occur when a static data member is declared but not defined. The following sample generates LNK2019, and shows how to fix it.

// LNK2019b.cpp
// Compile by using: cl /EHsc LNK2019b.cpp
// LNK2019 expected
struct C {
   static int s;
};

// Uncomment the following line to fix the error.
// int C::s;

int main() {
   C c;
   C::s = 1;
}

Declaration parameters don’t match the definition

Code that invokes function templates must have matching function template declarations. Declarations must include the same template parameters as the definition. The following sample generates LNK2019 on a user-defined operator, and shows how to fix it.

// LNK2019e.cpp
// compile by using: cl /EHsc LNK2019e.cpp
// LNK2019 expected
#include <iostream>
using namespace std;

template<class T> class
Test {
   // The operator<< declaration doesn't match the definition below:
   friend ostream& operator<<(ostream&, Test&);
   // To fix, replace the line above with the following:
   // template<typename T> friend ostream& operator<<(ostream&, Test<T>&);
};

template<typename T>
ostream& operator<<(ostream& os, Test<T>& tt) {
   return os;
}

int main() {
   Test<int> t;
   cout << "Test: " << t << endl;   // LNK2019 unresolved external
}

Inconsistent wchar_t type definitions

This sample creates a DLL that has an export that uses WCHAR, which resolves to wchar_t.

// LNK2019g.cpp
// compile with: cl /EHsc /LD LNK2019g.cpp
#include "windows.h"
// WCHAR resolves to wchar_t
__declspec(dllexport) void func(WCHAR*) {}

The next sample uses the DLL in the previous sample, and generates LNK2019 because the types unsigned short* and WCHAR* aren’t the same.

// LNK2019h.cpp
// compile by using: cl /EHsc LNK2019h LNK2019g.lib
// LNK2019 expected
__declspec(dllimport) void func(unsigned short*);

int main() {
   func(0);
}

To fix this error, change unsigned short to wchar_t or WCHAR, or compile LNK2019g.cpp by using /Zc:wchar_t-.

See also

For more information about possible causes and solutions for LNK2019, LNK2001, and LNK1120 errors, see the Stack Overflow question: What is an undefined reference/unresolved external symbol error and how do I fix it?.

  • Remove From My Forums
  • Question

  • I am new to msvc 2008.  This is not my code and I am trying to build this strange project.  I receive the following:
    1>Linking…
    1>Autoshell.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __thiscall SAASOFEPSocket::~SAASOFEPSocket(void)» (__imp_??1SAASOFEPSocket@@QAE@XZ) referenced in function «public: void * __thiscall SAASOFEPSocket::`scalar deleting destructor'(unsigned int)» (??_GSAASOFEPSocket@@QAEPAXI@Z)
    1>Autoshell.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: int __thiscall SAASOFEPSocket::Login(char const *)» (__imp_?Login@SAASOFEPSocket@@QAEHPBD@Z) referenced in function «public: int __thiscall CAutoShell::Run(bool)» (?Run@CAutoShell@@QAEH_N@Z)
    1>Autoshell.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: int __thiscall SAASOFEPSocket::ConnectToSystem(char const *,int &)» (__imp_?ConnectToSystem@SAASOFEPSocket@@QAEHPBDAAH@Z) referenced in function «public: int __thiscall CAutoShell::Run(bool)» (?Run@CAutoShell@@QAEH_N@Z)
    1>Autoshell.obj : error LNK2019: unresolved external symbol __imp__pDecWin@8 referenced in function «public: int __thiscall CAutoShell::Run(bool)» (?Run@CAutoShell@@QAEH_N@Z)
    1>Autoshell.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __thiscall SAASOFEPSocket::SAASOFEPSocket(void)» (__imp_??0SAASOFEPSocket@@QAE@XZ) referenced in function «public: int __thiscall CAutoShell::Run(bool)» (?Run@CAutoShell@@QAEH_N@Z)
    1>Autoshell.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: int __thiscall SAASOFEPSocket::GetLastError(void)const » (__imp_?GetLastError@SAASOFEPSocket@@QBEHXZ) referenced in function «private: int __thiscall CAutoShell::DoTransactionToFile(char const *,class std::basic_ofstream<char,struct std::char_traits<char> > &)» (?DoTransactionToFile@CAutoShell@@AAEHPBDAAV?$basic_ofstream@DU?$char_traits@D@std@@@std@@@Z)
    1>Autoshell.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: int __thiscall SAASOFEPSocket::DoTransaction(char const *,char *,int)» (__imp_?DoTransaction@SAASOFEPSocket@@QAEHPBDPADH@Z) referenced in function «private: int __thiscall CAutoShell::DoTransactionToFile(char const *,class std::basic_ofstream<char,struct std::char_traits<char> > &)» (?DoTransactionToFile@CAutoShell@@AAEHPBDAAV?$basic_ofstream@DU?$char_traits@D@std@@@std@@@Z)
    1>DebugAutoshell.exe : fatal error LNK1120: 7 unresolved externals
    1>Build log was saved at «file://f:vissual_cpp_projectsAutoShellDebugBuildLog.htm»
    1>Autoshell — 8 error(s), 4 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    I have googled/bing’d and what have you, but just don’t understand the problem…
    Thank You,

Answers

  • The error means the class SAASOFEPSocket implementation was not found by the linker.  It seems likely this is in a DLL you are using.  In that case you must find the .lib file associated with that DLL and add the .lib file into your project settings:

    Project->Properties->Linker->Input->Additional Dependencies

    Type the name of the lib file there, and make sure it is in one of the directories where the linker searches for libs.

    • Marked as answer by

      Friday, September 11, 2009 2:48 AM

  • Your code is trying to link to an external dll, look for «__declspec(dllimport)» in your code to see where.  To do this this you need the header from the dll and the dll.  The fact that you are getting this message indicates that you have the header, but cannot find the dll referenced.

    Question/Check:

    1] First thing to check is that you have the dll project and it compiles.
    2] Then check that your main project has the dll project set as dependency.
    3] If these are OK, then you should check that the dll is exporting iteself «__declspec(dllexport)» .
    4] Is this a MS2008 project originally, or is is being ported from something else.

    ie. You need:

    the dll sub-project to export the dll class
    the main project to import the dll class (with the dll header present)
    the main project to contain the dll sub-project as a dependency

    Depending on the answers to these, someone may be able to help further.

    • Marked as answer by
      Wesley Yao
      Friday, September 11, 2009 2:48 AM

I want to link the library as shared (static linking has same trouble either).

I have:

  • Windows 10
  • Cmake 3.15
  • Visual studio 19 (or Clion)
  • Clang compiler (VS based, and from MSYS2 package)

What I do:

  • Download SFML 2.5.1 for MinGW 64bit
  • Unpack to D:/dev/SFML-2.5.1
  • Create minimal test main.cpp:

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), «SFML works!»);
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

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

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

  • Create CMakeLists.txt with following:

# ….
find_package(SFML 2.5 COMPONENTS system window network graphics audio REQUIRED)

if (NOT ${SFML_FOUND})
    message(FATAL_ERROR «SFML couldn’t be located»)
endif()

set(SFML_LIBRARIES
        sfmlgraphics
        sfmlnetwork
        sfmlwindow
        sfmlaudio
        sfmlsystem)

# …

add_executable(TrueEngine
        ${TRUEENGINE_CORE_SRCS})

target_link_libraries(TrueEngine
        ${SFML_LIBRARIES}
        ${LUA_LIBRARIES})
# ….
# P.S. find_package(…) found them

  • Generate Visual Studio CMake project with following settings(1. VS clang, 2. Clang from MSYS2):
       

{
    «name»: «x64-Clang-Debug»,
    «generator»: «Ninja»,
    «configurationType»: «Debug»,
    «buildRoot»: «${projectDir}\out\build\${name}»,
    «installRoot»: «${projectDir}\out\install\${name}»,
    «cmakeCommandArgs»: «-DSFML_DIR=«D:/dev/SFML-2.5.1/lib/cmake/SFML« -DLUA_LIBRARY=«D:/dev/lua/liblua53.a« -DLUA_INCLUDE_DIR=«D:/dev/lua/include««,
    «buildCommandArgs»: «-v»,
    «ctestCommandArgs»: «»,
    «inheritEnvironments»: [ «clang_cl_x64» ],
    «variables»: []
},
{
    «name»: «x64-Clang-Debug-8.X.X»,
    «generator»: «Ninja»,
    «configurationType»: «Debug»,
    «buildRoot»: «${projectDir}\out\build\${name}»,
    «installRoot»: «${projectDir}\out\install\${name}»,
    «cmakeCommandArgs»: «-DSFML_DIR=«D:/dev/SFML-2.5.1/lib/cmake/SFML« -DLUA_LIBRARY=«D:/dev/lua/liblua53.a« -DLUA_INCLUDE_DIR=«D:/dev/lua/include««,
    «buildCommandArgs»: «-v»,
    «ctestCommandArgs»: «»,
    «inheritEnvironments»: [ «clang_cl_x64» ],
    «variables»: [
        {
            «name»: «CMAKE_C_COMPILER»,
            «value»: «C:/msys64/mingw64/bin/clang-cl.exe»,
            «type»: «FILEPATH»
        },
        {
            «name»: «CMAKE_CXX_COMPILER»,
            «value»: «C:/msys64/mingw64/bin/clang-cl.exe»,
            «type»: «FILEPATH»
        }
    ]
}
 

  • Generate cmake cashe and build

After I have this errors from both compiler:

>—— Build All started: Project: embercore-client, Configuration: x64-Clang-Debug ——
  [1/1] cmd.exe /C «cd . && «C:Program Files (x86)Microsoft Visual Studio2019CommunityCommon7IDECommonExtensionsMicrosoftCMakeCMakebincmake.exe» -E vs_link_exe —intdir=srcTECMakeFilesTrueEngine.dir —rc=C:WINDOW~110bin100177~1.0x64rc.exe —mt=C:WINDOW~110bin100177~1.0x64mt.exe —manifests  — C:PROGRA~2MICROS~12019COMMUN~1VCToolsMSVC1421~1.277binHostx64x64link.exe /nologo srcTECMakeFilesTrueEngine.dirCoremain.cpp.obj srcTECMakeFilesTrueEngine.dirCoreTrueEngine.cpp.obj srcTECMakeFilesTrueEngine.dirCoreAppTraits.cpp.obj srcTECMakeFilesTrueEngine.dirCoreVideoSettings.cpp.obj srcTECMakeFilesTrueEngine.dirCoreApplication.cpp.obj srcTECMakeFilesTrueEngine.dirCoreInput.cpp.obj srcTECMakeFilesTrueEngine.dirCoreEventHandler.cpp.obj  /out:……binTrueEngine.exe /implib:srcTETrueEngine.lib /pdb:……binTrueEngine.pdb /version:0.0  /machine:x64 /debug /INCREMENTAL /subsystem:console  D:devSFML-2.5.1liblibsfml-graphics-d.a D:devSFML-2.5.1liblibsfml-network-d.a D:devSFML-2.5.1liblibsfml-window-d.a D:devSFML-2.5.1liblibsfml-audio-d.a D:devSFML-2.5.1liblibsfml-system-d.a D:devlualiblua53.a kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cd .»
  FAILED: ../../../bin/TrueEngine.exe
  cmd.exe /C «cd . && «C:Program Files (x86)Microsoft Visual Studio2019CommunityCommon7IDECommonExtensionsMicrosoftCMakeCMakebincmake.exe» -E vs_link_exe —intdir=srcTECMakeFilesTrueEngine.dir —rc=C:WINDOW~110bin100177~1.0x64rc.exe —mt=C:WINDOW~110bin100177~1.0x64mt.exe —manifests  — C:PROGRA~2MICROS~12019COMMUN~1VCToolsMSVC1421~1.277binHostx64x64link.exe /nologo srcTECMakeFilesTrueEngine.dirCoremain.cpp.obj srcTECMakeFilesTrueEngine.dirCoreTrueEngine.cpp.obj srcTECMakeFilesTrueEngine.dirCoreAppTraits.cpp.obj srcTECMakeFilesTrueEngine.dirCoreVideoSettings.cpp.obj srcTECMakeFilesTrueEngine.dirCoreApplication.cpp.obj srcTECMakeFilesTrueEngine.dirCoreInput.cpp.obj srcTECMakeFilesTrueEngine.dirCoreEventHandler.cpp.obj  /out:……binTrueEngine.exe /implib:srcTETrueEngine.lib /pdb:……binTrueEngine.pdb /version:0.0  /machine:x64 /debug /INCREMENTAL /subsystem:console  D:devSFML-2.5.1liblibsfml-graphics-d.a D:devSFML-2.5.1liblibsfml-network-d.a D:devSFML-2.5.1liblibsfml-window-d.a D:devSFML-2.5.1liblibsfml-audio-d.a D:devSFML-2.5.1liblibsfml-system-d.a D:devlualiblua53.a kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cd .»
  LINK Pass 1: command «C:PROGRA~2MICROS~12019COMMUN~1VCToolsMSVC1421~1.277binHostx64x64link.exe /nologo srcTECMakeFilesTrueEngine.dirCoremain.cpp.obj srcTECMakeFilesTrueEngine.dirCoreTrueEngine.cpp.obj srcTECMakeFilesTrueEngine.dirCoreAppTraits.cpp.obj srcTECMakeFilesTrueEngine.dirCoreVideoSettings.cpp.obj srcTECMakeFilesTrueEngine.dirCoreApplication.cpp.obj srcTECMakeFilesTrueEngine.dirCoreInput.cpp.obj srcTECMakeFilesTrueEngine.dirCoreEventHandler.cpp.obj /out:……binTrueEngine.exe /implib:srcTETrueEngine.lib /pdb:……binTrueEngine.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:console D:devSFML-2.5.1liblibsfml-graphics-d.a D:devSFML-2.5.1liblibsfml-network-d.a D:devSFML-2.5.1liblibsfml-window-d.a D:devSFML-2.5.1liblibsfml-audio-d.a D:devSFML-2.5.1liblibsfml-system-d.a D:devlualiblua53.a kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:srcTECMakeFilesTrueEngine.dir/intermediate.manifest srcTECMakeFilesTrueEngine.dir/manifest.res» failed (exit code 1120) with the following output:
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::String::String(char const *,class std::locale const &)» (__imp_??0String@sf@@QEAA@PEBDAEBVlocale@std@@@Z) referenced in function main
D:ProjectsAppTraits.cpp.obj : error LNK2001: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::String::String(char const *,class std::locale const &)» (__imp_??0String@sf@@QEAA@PEBDAEBVlocale@std@@@Z)
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::VideoMode::VideoMode(unsigned int,unsigned int,unsigned int)» (__imp_??0VideoMode@sf@@QEAA@III@Z) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::RenderWindow::RenderWindow(class sf::VideoMode,class sf::String const &,unsigned int,struct sf::ContextSettings const &)» (__imp_??0RenderWindow@sf@@QEAA@VVideoMode@1@AEBVString@1@IAEBUContextSettings@1@@Z) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::String::~String(void)» (__imp_??1String@sf@@QEAA@XZ) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::CircleShape::CircleShape(float,unsigned __int64)» (__imp_??0CircleShape@sf@@QEAA@M_K@Z) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: static class sf::Color const sf::Color::Green» (__imp_?Green@Color@sf@@2V12@B) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: void __cdecl sf::Shape::setFillColor(class sf::Color const &)» (__imp_?setFillColor@Shape@sf@@QEAAXAEBVColor@2@@Z) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: bool __cdecl sf::Window::isOpen(void)const » (__imp_?isOpen@Window@sf@@QEBA_NXZ) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: bool __cdecl sf::Window::pollEvent(class sf::Event &)» (__imp_?pollEvent@Window@sf@@QEAA_NAEAVEvent@2@@Z) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: void __cdecl sf::Window::close(void)» (__imp_?close@Window@sf@@QEAAXXZ) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::Color::Color(unsigned char,unsigned char,unsigned char,unsigned char)» (__imp_??0Color@sf@@QEAA@EEEE@Z) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: void __cdecl sf::RenderTarget::clear(class sf::Color const &)» (__imp_?clear@RenderTarget@sf@@QEAAXAEBVColor@2@@Z) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: static class sf::RenderStates const sf::RenderStates::Default» (__imp_?Default@RenderStates@sf@@2V12@B) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: void __cdecl sf::RenderTarget::draw(class sf::Drawable const &,class sf::RenderStates const &)» (__imp_?draw@RenderTarget@sf@@QEAAXAEBVDrawable@2@AEBVRenderStates@2@@Z) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: void __cdecl sf::Window::display(void)» (__imp_?display@Window@sf@@QEAAXXZ) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: virtual __cdecl sf::CircleShape::~CircleShape(void)» (__imp_??1CircleShape@sf@@UEAA@XZ) referenced in function main
D:Projectsmain.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: virtual __cdecl sf::RenderWindow::~RenderWindow(void)» (__imp_??1RenderWindow@sf@@UEAA@XZ) referenced in function main
D:ProjectsTrueEngine.cpp.obj : error LNK2001: unresolved external symbol «__declspec(dllimport) public: virtual __cdecl sf::RenderWindow::~RenderWindow(void)» (__imp_??1RenderWindow@sf@@UEAA@XZ)
D:ProjectsApplication.cpp.obj : error LNK2001: unresolved external symbol «__declspec(dllimport) public: virtual __cdecl sf::RenderWindow::~RenderWindow(void)» (__imp_??1RenderWindow@sf@@UEAA@XZ)
D:ProjectsAppTraits.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::String::String(class sf::String const &)» (__imp_??0String@sf@@QEAA@AEBV01@@Z) referenced in function «public: __cdecl te::AppTraits::AppTraits(class sf::String const &,unsigned int,struct sf::ContextSettings const &)» (??0AppTraits@te@@QEAA@AEBVString@sf@@IAEBUContextSettings@3@@Z)
D:ProjectsVideoSettings.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::VideoMode::VideoMode(void)» (__imp_??0VideoMode@sf@@QEAA@XZ) referenced in function «public: __cdecl te::VideoSettings::VideoSettings(void)» (??0VideoSettings@te@@QEAA@XZ)
D:ProjectsApplication.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: __cdecl sf::RenderWindow::RenderWindow(void)» (__imp_??0RenderWindow@sf@@QEAA@XZ) referenced in function «public: __cdecl te::Application::Application(class te::AppTraits const &,class te::VideoSettings const &)» (??0Application@te@@QEAA@AEBVAppTraits@1@AEBVVideoSettings@1@@Z)
D:ProjectsApplication.cpp.obj : error LNK2019: unresolved external symbol «__declspec(dllimport) public: void __cdecl sf::Window::create(class sf::VideoMode,class sf::String const &,unsigned int,struct sf::ContextSettings const &)» (__imp_?create@Window@sf@@QEAAXVVideoMode@2@AEBVString@2@IAEBUContextSettings@2@@Z) referenced in function «public: __cdecl te::Application::Application(class te::AppTraits const &,class te::VideoSettings const &)» (??0Application@te@@QEAA@AEBVAppTraits@1@AEBVVideoSettings@1@@Z)
D:binTrueEngine.exe : fatal error LNK1120: 21 unresolved externals
  ninja: build stopped: subcommand failed.

Build All failed.

I see that libraries are not linked to the project, but I dont know why.

If I try to compile from a terminal, then all is fine, for example:

$ cmake .. -G «MinGW Makefiles» -DCMAKE_SH=«CMAKE_SH-NOTFOUND» -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DSFML_DIR=«D:/dev/SFML-2.5.1/lib/cmake/SFML» -DLUA_LIBRARY=«D:/dev/lua/liblua53.a» -DLUA_INCLUDE_DIR=«D:/dev/lua/include» -DCMAKE_BUILD_TYPE=debug
Found SFML 2.5.1 in D:/dev/SFML-2.5.1/lib/cmake/SFML
Configuring done
Generating done
Build files have been written to: D:/Projects/embercore-client/testbuild

 $ cmake —build .
Scanning dependencies of target TrueEngine
[ 12%] Building CXX object src/TE/CMakeFiles/TrueEngine.dir/Core/main.cpp.obj
[ 25%] Building CXX object src/TE/CMakeFiles/TrueEngine.dir/Core/TrueEngine.cpp.obj
[ 37%] Building CXX object src/TE/CMakeFiles/TrueEngine.dir/Core/AppTraits.cpp.obj
[ 50%] Building CXX object src/TE/CMakeFiles/TrueEngine.dir/Core/VideoSettings.cpp.obj
[ 62%] Building CXX object src/TE/CMakeFiles/TrueEngine.dir/Core/Application.cpp.obj
[ 75%] Building CXX object src/TE/CMakeFiles/TrueEngine.dir/Core/Input.cpp.obj
D:Projectsembercore-clientsrcTECoreInput.cpp:17:12: warning: 19 enumeration values not handled in switch: ‘Closed’, ‘Resized’, ‘LostFocus’[-Wswitch]
    switch(inputEvent.type) {
           ^
1 warning generated.
[ 87%] Building CXX object src/TE/CMakeFiles/TrueEngine.dir/Core/EventHandler.cpp.obj
[100%] Linking CXX executable ……binTrueEngine.exe
[100%] Built target TrueEngine

And it works.

What I do wrong in VS?

« Last Edit: July 02, 2019, 04:31:15 pm by LazyMechanic »


Logged

  • Remove From My Forums
  • Question

  • I am using OpenCASCADE (open source) to build some application under VC++ environment (VC++2008 Express Edition). I am facing a lot of problem due to the errors like:

    error LNK2001: unresolved external symbol «__declspec(dllimport)

    error LNK2019: unresolved external symbol «__declspec(dllimport)

    My code was working properly earlier but now from past few day I am getting the above errors.. Please tell me whats wrong??

    Thanks a lot….

    • Moved by

      Tuesday, August 9, 2011 7:29 AM
      off-topic (From:Visual C++ General)

Понравилась статья? Поделить с друзьями:
  • Error lnk2005 fortran
  • Error lnk2005 already defined in libcmtd lib
  • Error lnk2001 неразрешенный внешний символ main
  • Error lnk2001 неразрешенный внешний символ cxxframehandler3
  • Error lnk2001 unresolved external symbol winmain 16