Error link2019 c

C++ Documentation. Contribute to MicrosoftDocs/cpp-docs development by creating an account on GitHub.
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?.

I get this error, but I don’t know how to fix it.

I’m using Visual Studio 2013. I made the solution name MyProjectTest
This is the structure of my test solution:

The structure

function.h

#ifndef MY_FUNCTION_H
#define MY_FUNCTION_H

int multiple(int x, int y);
#endif

-function.cpp

#include "function.h"

int multiple(int x, int y){
    return x*y;
}

main.cpp

#include <iostream>
#include <cstdlib>
#include "function.h"

using namespace std;

int main(){
    int a, b;
    cin >> a >> b;
    cout << multiple(a, b) << endl;

    system("pause");
    return 0;
}

I’m a beginner; this is a simple program and it runs without error.
I read on the Internet and became interested in the unit test, so I created a test project:

Menu FileNewProject…InstalledTemplatesVisual C++TestNative Unit Test Project

Name: UnitTest1
Solution: Add to solution

Then the location auto-switched to the path of the current open solution.

This is the folder structure of the solution:

Folder structure

I only edited file unittest1.cpp:

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../MyProjectTest/function.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace UnitTest1
{
    TEST_CLASS(UnitTest1)
    {
    public:

        TEST_METHOD(TestEqual)
        {
            Assert::AreEqual(multiple(2, 3), 6);
            // TODO: Your test code here
        }

    };
}

But I get:

error LNK2019: unresolved external symbol.

I know that the implementation of function multiple is missing.
I tried to delete the function.cpp file and I replaced the declaration with the definition, and it ran. But writing both declaration and definition in the same file is not recommended.

How can I fix this error without doing that? Should I replace it with #include "../MyProjectTest/function.cpp" in file unittest.cpp?

Содержание

  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? .

Источник

15.07.2012, 16:53. Показов 60475. Ответов 13


Попытался скомпилировать программу из книги (DerectX — это просто. Программируем графику на С++) в Visual C++ 2010 Express, получил ошибки компиляции.

Вот вывод

1>—— Построение начато: проект: DX10Text, Конфигурация: Debug Win32 ——
1> main.cpp
1>main.obj : error LNK2019: ссылка на неразрешенный внешний символ _D3DX10CreateFontW@48 в функции «long __cdecl InitDirect3D10(void)» (?InitDirect3D10@@YAJXZ)
1>main.obj : error LNK2019: ссылка на неразрешенный внешний символ _D3D10CreateDeviceAndSwapChain@32 в функции «long __cdecl InitDirect3D10(void)» (?InitDirect3D10@@YAJXZ)
1>C:ПрогиПроги на C++DrectX 10Glava4TextDebugDX10Text.exe : fatal error LNK1120: 2 неразрешенных внешних элементов
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

Если понадобится, тогда вот код

Код

[CPP]//--------------------------------------------------------------------------------------
//  Вывод текста на экран
//--------------------------------------------------------------------------------------

#include <windows.h>
#include <d3d10.h>
#include <d3dx10.h>

// Ширина и высота окна
#define WINDOW_WIDTH  640
#define WINDOW_HEIGHT 480

//--------------------------------------------------------------------------------------
// Глобальные переменные
//--------------------------------------------------------------------------------------
HWND        g_hWnd = NULL;
D3D10_DRIVER_TYPE       g_driverType = D3D10_DRIVER_TYPE_NULL;
ID3D10Device*           g_pd3dDevice = NULL;
IDXGISwapChain*         g_pSwapChain = NULL;
ID3D10RenderTargetView* g_pRenderTargetView = NULL;

LPD3DX10FONT			g_pFont = NULL;

//--------------------------------------------------------------------------------------
// Прототипы функций
//--------------------------------------------------------------------------------------
HRESULT             InitWindow( HINSTANCE hInstance, int nCmdShow );
HRESULT				InitDirect3D10();
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
void                Cleanup();
void                RenderScene();

//--------------------------------------------------------------------------------------
// С этой функции начинается выполнение программы
//--------------------------------------------------------------------------------------
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
    // Создаем окно приложения
	if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
        return 0;
    // Инициализируем Direct3D
	if( FAILED( InitDirect3D10() ) )
    {
        Cleanup();
        return 0;
    }

    // Цикл обработки сообщений
    MSG msg = {0};
    while( WM_QUIT != msg.message  )
    {
		if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
		{
        TranslateMessage( &msg );
        DispatchMessage( &msg );
		}
		else
		{
			RenderScene();
		}

    }

    return (int) msg.wParam;
}

//--------------------------------------------------------------------------------------
// Регистрация класса и создание окна
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
{
    // Регистрируем класс окна
    WNDCLASSEX wc;
    wc.cbSize = sizeof(WNDCLASSEX); 
    wc.style          = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc    = WndProc;
    wc.cbClsExtra     = 0;
    wc.cbWndExtra     = 0;
    wc.hInstance      = hInstance;
    wc.hIcon          = NULL;
    wc.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName   = NULL;
    wc.lpszClassName  = L"SimpleWindowClass";
    wc.hIconSm        = LoadIcon(NULL, IDI_APPLICATION);
    if( !RegisterClassEx(&wc) )
        return E_FAIL;

    // Создаем окно
    g_hWnd = CreateWindow(
		L"SimpleWindowClass", 
		L"DirectX 10: Вывод текста", 
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 
		CW_USEDEFAULT, 
		WINDOW_WIDTH,
		WINDOW_HEIGHT,
		NULL,
		NULL,
		hInstance,
		NULL);

	// Если не удалось создать окно - выходим из функции
    if( !g_hWnd )
        return E_FAIL;
	// Отображаем окно на экране
    ShowWindow( g_hWnd, nCmdShow );
	UpdateWindow(g_hWnd);
   
    return S_OK;
}

//--------------------------------------------------------------------------------------
// Инициализация Direct3D
//--------------------------------------------------------------------------------------
HRESULT InitDirect3D10()
{
	HRESULT hr = S_OK;

	// Узнаем размеры клиентской области окна
    RECT rc;
    GetClientRect( g_hWnd, &rc );
    UINT width = rc.right - rc.left;
    UINT height = rc.bottom - rc.top;

	// Список возможных типов устройства
	D3D10_DRIVER_TYPE driverTypes[] = 
    {
        D3D10_DRIVER_TYPE_HARDWARE,
        D3D10_DRIVER_TYPE_REFERENCE,
    };
    UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]);

	// Заполняем структуру 
    DXGI_SWAP_CHAIN_DESC sd;
    ZeroMemory( &sd, sizeof(sd) );
    sd.BufferCount = 1;
    sd.BufferDesc.Width = width;
    sd.BufferDesc.Height = height;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = g_hWnd;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = TRUE;

	// Пытаемся создать устройство, проходя по списку
	// как только получилось - выходим из цикла
	for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
	{
		g_driverType = driverTypes[driverTypeIndex];
		hr = D3D10CreateDeviceAndSwapChain( NULL, g_driverType, NULL, 0, 
			D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice );
		if( SUCCEEDED( hr ) )
			break;
	}
	if( FAILED(hr) )
		return hr;

	// Представление данных для
	// буфера визуализации
	ID3D10Texture2D *pBackBuffer;
	hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), (LPVOID*)&pBackBuffer );
	if( FAILED(hr) )
		return hr;
   // Создадим представление данных
	hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView );
	pBackBuffer->Release();
	if( FAILED(hr) )
		return hr;
   // Свяжем буфер визуализации с графическим конвейером
	g_pd3dDevice->OMSetRenderTargets( 1, &g_pRenderTargetView, NULL );

	// Настроим область отображения
	D3D10_VIEWPORT vp;
	vp.Width = width;
	vp.Height = height;
	vp.MinDepth = 0.0f;
	vp.MaxDepth = 1.0f;
	vp.TopLeftX = 0;
	vp.TopLeftY = 0;
	g_pd3dDevice->RSSetViewports( 1, &vp );

	// Создаем шрифтовой объект
	D3DX10CreateFont( g_pd3dDevice, 14, 8, 1, 1, FALSE, 0, 0, 0, DEFAULT_PITCH|FF_MODERN, L"Verdana", &g_pFont);

    return S_OK;
}

//--------------------------------------------------------------------------------------
// Прорисовка трехмерной сцены
//--------------------------------------------------------------------------------------
void RenderScene()
{
    // Очищаем вторичный буфер
    float ClearColor[4] = { 0.1f, 0.5f, 0.1f, 1.0f }; //компоненты красного, зеленого, синего, прозрачность
    g_pd3dDevice->ClearRenderTargetView( g_pRenderTargetView, ClearColor );

	//Размеры прямоугольника для форматирования текста
	RECT Rect;
	Rect.left=10;
	Rect.top=10;
	Rect.right=600;
	Rect.bottom=380;

	g_pFont->DrawText(NULL, L"Этот текст мы вывели на экран", -1, &Rect, DT_CENTER | DT_VCENTER , D3DXCOLOR(1.0,1.0,1.0,1.0));

	g_pSwapChain->Present( 0, 0 );
}
//--------------------------------------------------------------------------------------
// Обработка сообщений
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{    
    switch (message) 
    {
        
        case WM_DESTROY:
            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
    }

    return 0;
}

//--------------------------------------------------------------------------------------
// Очищаем память 
//--------------------------------------------------------------------------------------
void Cleanup()
{
    if( g_pd3dDevice ) g_pd3dDevice->ClearState();

    if( g_pRenderTargetView ) g_pRenderTargetView->Release();
    if( g_pSwapChain ) g_pSwapChain->Release();
    if( g_pd3dDevice ) g_pd3dDevice->Release();

	if( g_pFont ) g_pFont->Release();
}
[/CPP]

Подскажите, что сделать, чтобы убрать эти ошибки.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



1



RRS feed

  • Remove From My Forums
  • Question

  • this is the code im using, when i goto build it i works fine then as its about to finish i ge tthe LNK2019 error, why?

    #include

    <iostream>

    int main()

    {

    using namespace std;

    int carrot;

    cout << «how many carrots do you have? «;

    cin >> carrot;

    cout << endl;

    carrot = carrot — 2;

    cout << «cruch crunch, i ate somse of your carrots. you now have » << carrot << » carotts» << endl;

    return 0;

    }

Answers

All replies

  • I just tried compiling the sample you supplied nad it worked fine for me (using VS2005 beta2).

    Could you share the compilation command, you can do that by looking at the build log? Or share the steps on how you created the project?

    Thanks,
      Ayman Shoukry
      VC++

  •    

    ------- Build started: Project: asdf, Configuration: Debug|Win32 -------

       
    This edition of Visual C++ does not support the optimizing compiler. This edition of Visual C++ does not support the optimizing compiler. Creating temporary file "c:Documents and SettingsJason KennedyMy DocumentsVisual Studio ProjectsasdfDebugRSP000001.rsp" with contents [ /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Gm /EHsc /RTC1 /MLd /Fo"Debug/" /Fd"Debug/vc70.pdb" /W3 /c /Wp64 /ZI /TP ".asdf.cpp" ] Creating command line "cl.exe @"c:Documents and SettingsJason KennedyMy DocumentsVisual Studio ProjectsasdfDebugRSP000001.rsp" /nologo" Creating temporary file "c:Documents and SettingsJason KennedyMy DocumentsVisual Studio ProjectsasdfDebugRSP000002.rsp" with contents [ /OUT:"Debug/asdf.exe" /INCREMENTAL /NOLOGO /DEBUG /PDB:"Debug/asdf.pdb" /SUBSYSTEM:WINDOWS /MACHINE:X86 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ".Debugasdf.obj" ] Creating command line "link.exe @"c:Documents and SettingsJason KennedyMy DocumentsVisual Studio ProjectsasdfDebugRSP000002.rsp"" 
       
    Compiling... asdf.cpp Linking... LIBCD.lib(wincrt0.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function _WinMainCRTStartup Debug/asdf.exe : fatal error LNK1120: 1 unresolved externals 
       
    Build log was saved at "file://c:Documents and SettingsJason KennedyMy DocumentsVisual Studio ProjectsasdfDebugBuildLog.htm" asdf - 2 error(s), 0 warning(s)

    thats the build log, i have VC++ .NET 2k3 and WIN XP PRO, 2.6GHz P4, 512MB RAM

  • awsome, that was it, thanks much

  •  

    Hi all,

    I’m a newbie to Visual C++ (and C++ in general), and first I’d like to say thanks — I had multiple problems with my first program running correctly, and found most of the answers here, in previous threads.

    I did get it running, but now I have a question about the debugger.

    Like daman above, I am teaching myself using Prata’s C++ Primer Plus and tried one of those «carrots» programs like the one above.

    When I ran the debugger on the program after I got all the aforementioned problems fixed, the program would start fine but dump me back out when I input a number.  Output from the debugger is below, but what really confuses me is that when I clean the program and start it without debugging, it runs just fine.  In addition, I can only get it to run from inside VC without debugging — the executable that’s created does the same thing as the debugged version (ie crashes).

    I’m using a Win32 console rather than the Windows subsystem, so that doesn’t seem to be the problem.  My build log is massive compared to daman’s, but I included the info below. 

    Thanks in advance for your help and patience.

    The Output from the debugger:

    ‘carrots_try3.exe’: Loaded ‘D:Program FilesMicrosoft Platform SDKBincarrots_try3debugcarrots_try3.exe’, Symbols loaded.

    ‘carrots_try3.exe’: Loaded ‘C:WINNTsystem32NTDLL.DLL’, Cannot find or open a required DBG file.

    ‘carrots_try3.exe’: Loaded ‘C:WINNTsystem32msvcr80d.dll’, No symbols loaded.

    ‘carrots_try3.exe’: Loaded ‘C:WINNTsystem32msvcrt.dll’, No symbols loaded.

    ‘carrots_try3.exe’: Loaded ‘C:WINNTsystem32KERNEL32.DLL’, Cannot find or open a required DBG file.

    ‘carrots_try3.exe’: Loaded ‘C:WINNTsystem32msvcp80d.dll’, No symbols loaded.

    The program ‘[1952] carrots_try3.exe: Native’ has exited with code 0 (0x0).

     LOG:

       
    Creating temporary file "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004516842352.rsp" with contents
    [
    /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /RTC1 /MDd /Yu"stdafx.h" /Fp"Debugcarrots_try3.pch" /Fo"Debug\" /Fd"Debugvc80.pdb" /W3 /c /Wp64 /ZI /TP ".carrots_try3.cpp"
    ]
    Creating command line "cl.exe @"d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004516842352.rsp" /nologo /errorReport:prompt"
    Creating temporary file "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004616842352.rsp" with contents
    [
    /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /RTC1 /MDd /Yc"stdafx.h" /Fp"Debugcarrots_try3.pch" /Fo"Debug\" /Fd"Debugvc80.pdb" /W3 /c /Wp64 /ZI /TP ".stdafx.cpp"
    ]
    Creating command line "cl.exe @"d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004616842352.rsp" /nologo /errorReport:prompt"
    Creating temporary file "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugTMP00004716842352.tmp" with contents
    [
    1 /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ 24 /* RT_MANIFEST */ ".\Debug\carrots_try3.exe.embed.manifest"
    ]
    Creating command line "rc.exe /fo".Debugcarrots_try3.exe.embed.manifest.res" "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugTMP00004716842352.tmp""
    Creating temporary file "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004816842352.rsp" with contents
    [
    /OUT:"d:Program FilesMicrosoft Platform SDKBincarrots_try3Debugcarrots_try3.exe" /INCREMENTAL /MANIFEST /MANIFESTFILE:"Debugcarrots_try3.exe.intermediate.manifest" /DEBUG /PDB:"d:program filesmicrosoft platform sdkbincarrots_try3debugcarrots_try3.pdb" /SUBSYSTEM:CONSOLE /MACHINE:X86 kernel32.lib
    
    ".debugstdafx.obj"
    
    ".debugcarrots_try3.obj"
    
    ".Debugcarrots_try3.exe.embed.manifest.res"
    ]
    Creating command line "link.exe @"d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004816842352.rsp" /NOLOGO /ERRORREPORT:PROMPT"
    Creating temporary file "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004916842352.rsp" with contents
    [
    /out:".debugcarrots_try3.exe.embed.manifest" /notify_update /manifest
    
    ".debugcarrots_try3.exe.intermediate.manifest"
    ]
    Creating command line "mt.exe @"d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004916842352.rsp" /nologo"
    Creating temporary file "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugBAT00004A16842352.bat" with contents
    [
    @echo Manifest resource last updated at %TIME% on %DATE% > ".debugmt.dep"
    ]
    Creating command line """d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugBAT00004A16842352.bat"""
    Creating temporary file "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugTMP00004B16842352.tmp" with contents
    [
    1 /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ 24 /* RT_MANIFEST */ ".\Debug\carrots_try3.exe.embed.manifest"
    ]
    Creating command line "rc.exe /fo".Debugcarrots_try3.exe.embed.manifest.res" "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugTMP00004B16842352.tmp""
    Creating temporary file "d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004C16842352.rsp" with contents
    [
    /OUT:"d:Program FilesMicrosoft Platform SDKBincarrots_try3Debugcarrots_try3.exe" /INCREMENTAL /MANIFEST /MANIFESTFILE:"Debugcarrots_try3.exe.intermediate.manifest" /DEBUG /PDB:"d:program filesmicrosoft platform sdkbincarrots_try3debugcarrots_try3.pdb" /SUBSYSTEM:CONSOLE /MACHINE:X86 kernel32.lib
    
    ".debugstdafx.obj"
    
    ".debugcarrots_try3.obj"
    
    ".Debugcarrots_try3.exe.embed.manifest.res"
    ]
    Creating command line "link.exe @"d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugRSP00004C16842352.rsp" /NOLOGO /ERRORREPORT:PROMPT"
    
       
    Compiling...
    stdafx.cpp
    Compiling...
    carrots_try3.cpp
    Compiling manifest to resources...
    Linking...
    LINK : d:Program FilesMicrosoft Platform SDKBincarrots_try3Debugcarrots_try3.exe not found or not built by the last incremental link; performing full link
    LINK : warning LNK4067: ambiguous entry point; selected 'mainCRTStartup'
    Embedding manifest...
    
       
    Build log was saved at "file://d:Program FilesMicrosoft Platform SDKBincarrots_try3carrots_try3DebugBuildLog.htm"
    carrots_try3 - 0 error(s), 1 warning(s)
    

  • I don’t think it did dump you straight back out. I think the program worked properly, finished, and then closed down.

    If you look very very very closely at the output, you’ll probably see that it prints out the final message correctly before it quickly exits. You’ll have to be eagle-eyed to catch it (blink and you’ll miss it) because once it prints out the final number of carrots, the program will end and close down.

    We get this problem quite often… the programmers may look very very closely at the output, but they don’t look very very VERY closely at it. Hence they miss the output before the program closes, and think that their program crashed.

    If you’re not eagle-eyed enough to catch it, I suggest adding a breakpoint at the «return 0;» line before debugging. This will stop the program long enough for you to see the results.

  • Well, that’s actually funny, in a disturbing kind of way.  Thanks so much for your help—the breakpoint slowed it down just enough for me to catch the output.

  • Help.. I’m new to C++ and I have problems building this project. The source code is as follows:

    #include «stdafx.h»

    #include <string.h>

    #include <windows.h>

    #include <iostream.h>

     void main(){

    try{

    HCRYPTPROV hProv;

    BOOL didItWork = CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, NULL);

    if(!didItWork){

    if(GetLastError()==NTE_BAD_KEYSET){

    didItWork = CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_NEWKEYSET);

    if(!didItWork){

    throw GetLastError();

    }

    }else{

    throw GetLastError();

    }

    }

    HCRYPTKEY myKey = 0;

    didItWork = CryptGenKey(hProv, CALG_AES_128, CRYPT_EXPORTABLE, &myKey);

    if(!didItWork){

    throw GetLastError();

    }

    const char *plaintext = «PlainText»;

    unsigned char buffer[256];

    unsigned long strSize = strlen(plaintext)+1;

    memcpy(buffer, plaintext, strlen(plaintext)+1);

    didItWork = CryptEncrypt(myKey, NULL, TRUE, NULL, buffer, &strSize, sizeof(buffer));

    if(!didItWork){

    throw GetLastError();

    }

    CryptDestroyKey(myKey);

    CryptReleaseContext(hProv, NULL);

    }catch(DWORD error){

    LPWSTR msgbuffer;

    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), msgbuffer, sizeof(msgbuffer), NULL);

    cerr<<msgbuffer<<endl<<flush;

    }

    }

    Here is the build log file that was generated after I tried to build the project:

      

    Build started: Project: encryption, Configuration: Debug|Win32

       
    Creating temporary file "c:Documents and SettingsMichelle TeoMy DocumentsVisual Studio 2005ProjectsencryptionDebugRSP00001626162308.rsp" with contents
    [
    /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /RTC1 /MDd /Yu"stdafx.h" /Fp"Debugencryption.pch" /Fo"Debug\" /Fd"Debugvc80.pdb" /W3 /c /Wp64 /ZI /TP ".encryption.cpp"
    ]
    Creating command line "cl.exe @"c:Documents and SettingsMichelle TeoMy DocumentsVisual Studio 2005ProjectsencryptionDebugRSP00001626162308.rsp" /nologo /errorReport:prompt"
    Creating temporary file "c:Documents and SettingsMichelle TeoMy DocumentsVisual Studio 2005ProjectsencryptionDebugRSP00001726162308.rsp" with contents
    [
    /OUT:"Debugencryption.exe" /INCREMENTAL /MANIFEST /MANIFESTFILE:"Debugencryption.exe.intermediate.manifest" /DEBUG /PDB:"c:documents and settingsmichelle teomy documentsvisual studio 2005projectsencryptiondebugencryption.pdb" /SUBSYSTEM:CONSOLE /MACHINE:X86 kernel32.lib
    
    ".debugstdafx.obj"
    
    ".debugencryption.obj"
    
    ".Debugencryption.exe.embed.manifest.res"
    ]
    Creating command line "link.exe @"c:Documents and SettingsMichelle TeoMy DocumentsVisual Studio 2005ProjectsencryptionDebugRSP00001726162308.rsp" /NOLOGO /ERRORREPORT:PROMPT"
    
       
    Compiling...
    encryption.cpp
    c:program filesmicrosoft visual studio 8vcincludestreamb.h(158) : warning C4244: 'return' : conversion from '__w64 int' to 'int', possible loss of data
    c:program filesmicrosoft visual studio 8vcincludestreamb.h(159) : warning C4244: 'return' : conversion from '__w64 int' to 'int', possible loss of data
    c:program filesmicrosoft visual studio 8vcincludestreamb.h(170) : warning C4244: 'return' : conversion from '__w64 int' to 'int', possible loss of data
    c:documents and settingsmichelle teomy documentsvisual studio 2005projectsencryptionencryption.cpp(38) : warning C4267: 'initializing' : conversion from 'size_t' to 'unsigned long', possible loss of data
    c:documents and settingsmichelle teomy documentsvisual studio 2005projectsencryptionencryption.cpp(51) : warning C4700: uninitialized local variable 'msgbuffer' used
    Linking...
    encryption.obj : error LNK2019: unresolved external symbol __imp__CryptReleaseContext@8 referenced in function _main
    encryption.obj : error LNK2019: unresolved external symbol __imp__CryptDestroyKey@4 referenced in function _main
    encryption.obj : error LNK2019: unresolved external symbol __imp__CryptEncrypt@28 referenced in function _main
    encryption.obj : error LNK2019: unresolved external symbol __imp__CryptGenKey@16 referenced in function _main
    encryption.obj : error LNK2019: unresolved external symbol __imp__CryptAcquireContextW@20 referenced in function _main
    Debugencryption.exe : fatal error LNK1120: 5 unresolved externals
    
       
    Build log was saved at "file://c:Documents and SettingsMichelle TeoMy DocumentsVisual Studio 2005ProjectsencryptionDebugBuildLog.htm"
    encryption - 6 error(s), 5 warning(s)
    

    Can anyone tell me what’s going on and how to solve the problem?? Thanks.. :)

  • thank you very much. I’m embarrassed to say that i did not understand everything said. but what i did take away from everything allowed my code to work. thanks again :)

  • your «namespace» should have been put OUTSIDE of the main function:

    #include <iostream>

    using namespace std;

    int main()

    {

    …..

    }

  • I have same propblem, when I try to compile source code

    CredentialProviders2007_01.exe 

    Here is my Log

    Build started: Project: HybridCredProv, Configuration: Debug|Win32

    Creating temporary file "c:CredentialProvidersHybridCredentialProviderDebugRSP00000A66167472.rsp" with contents
    [
    /VERBOSE:LIB /OUT:"C:CredentialProvidersDebugHybridCredProv.dll" /INCREMENTAL /LIBPATH:"C:Program FilesMicrosoft SDKsWindowsv6.0Lib" /LIBPATH:"C:CredentialProvidersDebug" /LIBPATH:"C:CredentialProviders\lib" /DLL /MANIFEST /MANIFESTFILE:"DebugHybridCredProv.dll.intermediate.manifest" /NODEFAULTLIB:"msvcrtd.lib msvcrt.lib" /DEF:"..hybridcredprov.def" /ASSEMBLYMODULE:"secur32.lib" /DEBUG /ASSEMBLYDEBUG /PDB:"c:credentialprovidersdebugHybridCredProv.pdb" schelp.lib winscard.lib shlwapi.lib crypt32.lib secur32.lib kernel32.lib mgsc.lib kernel32.lib
    
    ".debugCHybridCredential.obj"
    
    ".debugCHybridProvider.obj"
    
    ".debugDll.obj"
    
    ".debugguid.obj"
    
    ".debughelpers.obj"
    
    ".debugresources.res"
    ]
    Creating command line "link.exe @c:CredentialProvidersHybridCredentialProviderDebugRSP00000A66167472.rsp /NOLOGO /ERRORREPORT:PROMPT"
    
    Linking...
    Searching libraries
      Searching C:CredentialProvidersDebugschelp.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libwinscard.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libshlwapi.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libcrypt32.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libsecur32.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libkernel32.lib:
      Searching C:CredentialProviders\libmgsc.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libuuid.lib:
      Searching C:Program FilesMicrosoft Visual Studio 8VClibLIBCMT.lib:
      Searching C:Program FilesMicrosoft Visual Studio 8VClibOLDNAMES.lib:
      Searching C:CredentialProvidersDebugschelp.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libwinscard.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libshlwapi.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libcrypt32.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libsecur32.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libkernel32.lib:
      Searching C:CredentialProviders\libmgsc.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libuuid.lib:
    Finished searching libraries
      Creating library C:CredentialProvidersDebugHybridCredProv.lib and object C:CredentialProvidersDebugHybridCredProv.exp
    Searching libraries
      Searching C:CredentialProvidersDebugschelp.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libwinscard.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libshlwapi.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libcrypt32.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libsecur32.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libkernel32.lib:
      Searching C:CredentialProviders\libmgsc.lib:
      Searching C:Program FilesMicrosoft SDKsWindowsv6.0Libuuid.lib:
      Searching C:Program FilesMicrosoft Visual Studio 8VClibLIBCMT.lib:
      Searching C:Program FilesMicrosoft Visual Studio 8VClibOLDNAMES.lib:
    Finished searching libraries
    CHybridCredential.obj : error LNK2019: unresolved external symbol __imp__CoTaskMemFree@4 referenced in function "public: virtual __thiscall CHybridCredential::~CHybridCredential(void)" (??1CHybridCredential@@UAE@XZ)
    helpers.obj : error LNK2001: unresolved external symbol __imp__CoTaskMemFree@4
    CHybridCredential.obj : error LNK2019: unresolved external symbol __imp__LoadBitmapA@8 referenced in function "public: virtual long __stdcall CHybridCredential::GetBitmapValue(unsigned long,struct HBITMAP__ * *)" (?GetBitmapValue@CHybridCredential@@UAGJKPAPAUHBITMAP__@@@Z)
    helpers.obj : error LNK2019: unresolved external symbol __imp__CoTaskMemAlloc@4 referenced in function "long __cdecl FieldDescriptorCoAllocCopy(struct _CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR const &,struct _CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR * *)" (?FieldDescriptorCoAllocCopy@@YAJABU_CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR@@PAPAU1@@Z)
    C:CredentialProvidersDebugHybridCredProv.dll : fatal error LNK1120: 3 unresolved externals
    
    Build log was saved at "file://c:CredentialProvidersHybridCredentialProviderDebugBuildLog.htm"
    HybridCredProv - 5 error(s), 0 warning(s)
    

    Thank you very much for your answer.

одним из вариантов было бы включить function.cpp в своем UnitTest1 проект, но это может быть не самая идеальная структура решения. Короткий ответ на вашу проблему заключается в том, что при создании вашего UnitTest1 проект, компилятор и компоновщик понятия не имеют, что function.cpp существует, а также не имеют ничего, чтобы связать, что содержит определение multiple. Способ исправить это-использовать библиотеки ссылок.

поскольку ваши модульные тесты находятся в другом проекте, я предполагаю, что ваше намерение состоит в том, чтобы сделайте этот проект автономной программой модульного тестирования. С функциями, которые вы тестируете, расположенными в другом проекте, можно построить этот проект в динамически или статически связанной библиотеке. Статические библиотеки связаны с другими программами во время сборки, и имеют расширение .lib, и динамические библиотеки связаны во время выполнения, и имеют расширение .dll. Для моего ответа я предпочитаю статические библиотеки.

вы можете превратить свою первую программу в статическую библиотеку изменив его в свойствах проектов. Там должна быть опция на вкладке Общие, где проект настроен на сборку в исполняемый файл (.exe). Вы можете изменить это на .lib. Элемент .lib файл будет построен в том же месте, что и .exe.

в своем UnitTest1 проект, вы можете перейти к его свойствам, и на вкладке Компоновщик в категории дополнительные каталоги библиотеки, добавить путь к которому MyProjectTest строит. Затем, для получения дополнительных зависимостей под Компоновщик — Вкладка ввода, добавьте имя вашей статической библиотеки, скорее всего MyProjectTest.lib.

это должно позволить вашему проекту построить. Обратите внимание, что, делая это, MyProjectTest не будет автономной исполняемой программой, если вы не измените ее свойства сборки по мере необходимости, что было бы менее идеальным.

Не могу разобраться в чем проблема… я написал небольшую програмку скомпилировал, а когда через некоторое время внес исправления и попытался исправить получил кучу ошибок:

error LNK2019: unresolved external symbol __imp__fread referenced in function «int __cdecl ReadKZU(struct _iobuf *,unsigned int *)» (?ReadKZU@@YAHPAU_iobuf@@PAI@Z)

и так 33 раза на разных функциях…
Теперь у меня ни один проект не компилится:(((…В чем проблема?

31 ответ

63

05 декабря 2006 года

Zorkus

2.6K / / 04.11.2006

Код давай. Надо с ключами линкера поколдовать, думаю:)

8.2K

05 декабря 2006 года

mohito

35 / / 24.11.2005

В прикрепленном файле код… там две функции одна другую вызывает…
P.S. сам код «корявый», но не в этом суть….

8.2K

06 декабря 2006 года

mohito

35 / / 24.11.2005

Если есть добрые люди, кому не жаль потратить полчасика… скиньте в каком-нибудь виде свои настройки проекта MSVS 2005… я подозреваю что проблема именно в настройках проекта… но никак не могу понять где именно… я уже сократил кол-во ошибок с 33 до 6… =)

240

06 декабря 2006 года

aks

2.5K / / 14.07.2006

)
Зайди в свойства проекта->C/C++ ->Code Generation -> Runtime Library
и скажи, что у тебя там стоит.

240

06 декабря 2006 года

aks

2.5K / / 14.07.2006

Кстати накой консольной программе мессаджбоксы? Неужели нельзя сообщение об ошибке тудаже в консоль и выдать?

8.2K

06 декабря 2006 года

mohito

35 / / 24.11.2005

1. В Runtime Library: Multi-threaded Debug DLL /MDd
2. Это кусок программы, я написал его как консольное приложение, но потом код вставлю в MFC проект. короче не важно, какая разница где-мессадж боксы вызывать=)

240

06 декабря 2006 года

aks

2.5K / / 14.07.2006

Поставь статический рантайм. Чтоб не было написанно DLL, и расскажи что произошло )

63

06 декабря 2006 года

Zorkus

2.6K / / 04.11.2006

mohito, а что соббсна пишет хелп про эту ошибку, можешь кинуть?
P.S. прошу прощения, но MSVS и msdn нету на машине…

8.2K

06 декабря 2006 года

mohito

35 / / 24.11.2005

Исправил Runtime Library: Multi-threaded Debug (/MTd)
Кол-во ошибок увеличилось с 6 до 31 =)…
в начале что-то вроде:
error LNK2005: «public: __thiscall std::_Locinfo::_Locinfo(char const *)…
и так раз 5
потом
LNK2019…
много раз…

8.2K

06 декабря 2006 года

mohito

35 / / 24.11.2005

Здесь пример сообщений об ошибках:

63

06 декабря 2006 года

Zorkus

2.6K / / 04.11.2006

Я спросил статью справки, F1 + click на сообщение об ошибке, статью про возможную причину, а не то что пишет компилятор.

8.2K

06 декабря 2006 года

mohito

35 / / 24.11.2005

А… Момент=)…. смотри в файле:

5.9K

07 декабря 2006 года

Zushenskiy

161 / / 29.06.2006

mohito ты какой проект создаешь?

279

07 декабря 2006 года

bave

456 / / 07.03.2004

Если ставить Code Generation: MultiThread надо чтоб все остальные линкуемые модули (написанные тобой) тоже были откомпилированы с
ключём /MT — иначе линковшик выдаёт кучу ошибок о конфликтах
LIBC и LIBCMT…

8.2K

07 декабря 2006 года

mohito

35 / / 24.11.2005

У меня простой консольный проект, из одного файла.

5.9K

07 декабря 2006 года

Zushenskiy

161 / / 29.06.2006

Выложи проект либо содиржимое файла vcproj

8.2K

07 декабря 2006 года

mohito

35 / / 24.11.2005

Вот vsproj:

63

07 декабря 2006 года

Zorkus

2.6K / / 04.11.2006

Попробуй ключи линкера (свойства проекта, общие, линкер, ком. строка, как-то так) /FORCE , /Zc:wchar_t- .

8.2K

07 декабря 2006 года

mohito

35 / / 24.11.2005

Ага… добавление в Linker->ComandLine опции /FORCE позволило снять ошибку 2019…. теперь прога компилируется(и линкуется) но при запуске выдает: ненайден библиотека MSVCP60D.dll =)… И прикол в том что у меня её нет=) (я искал везде)

63

07 декабря 2006 года

Zorkus

2.6K / / 04.11.2006

http://intercomp.net.ru/dll/m.php?page=82
там нужные либы есть, но все таки почитай подробнее про ключ /FORCE, он ведь многое ставит в игнор, с ним лучше осторожно (хотя, иногда,мне кажется, только он и спасает:))

8.2K

07 декабря 2006 года

mohito

35 / / 24.11.2005

Да, походу /FORCE — сильная штука=)… Т.к. я сумел скомпилировать, но ткпкрь при попытке открыть файл (fopen) уменя возникает Exception (Исключение) =))) (я не вносил изменений в код.. который когда-то запускался=) )… Должен же быть способ кроме как все «зафорсить»?… Или Винду переустанавливать??? (студию переустанавливал трижды… не помогло)

63

07 декабря 2006 года

Zorkus

2.6K / / 04.11.2006

какой именно exception?

5.9K

08 декабря 2006 года

Zushenskiy

161 / / 29.06.2006

твой vcproj настроен нормально. походу проблемы либо с виндой либо со студией. линковщик неможет найти подходящие либы. проверь настройки и переменные окружения самой студии. и погоняй свой комп на инородные прожки типа вирусы.

63

08 декабря 2006 года

Zorkus

2.6K / / 04.11.2006

линковщик неможет найти подходящие либы. проверь настройки и переменные окружения самой студии. и погоняй свой комп на инородные прожки типа вирусы.

Надо скачать dll-ку и кинуть в каталог где храняться dll -ки VS, или в system32, хидер к ней как я понимаю, есть (или он не нужен), а lib — файл для либы можно самому сделать, если надо, точно не скажу как утилитка из VS называется, implib вроде бы, и бросить его туда где все остальные находятся у студии, вот и вся настройка линкера ( это в общем, для абстрактной dll, а для динамически загр. вроде твоей нужна только сама dll и все).
Переменные окружения должны при установке ставиться сами, а вирусы — так с этого надо было начинать;)

8.2K

09 декабря 2006 года

mohito

35 / / 24.11.2005

Проблема решена… Сносом Винды и полной переустановкой системы=))).
Всем МЕГА спасибо за участие в топике…

63

09 декабря 2006 года

Zorkus

2.6K / / 04.11.2006

Проблема решена… Сносом Винды и полной переустановкой системы=))).

Это называется «решена»?:) Ты скажи, стало работать нормально, или нет? И какая именно была ошибка неустранимая? Я из твоего описания не понял.

8.2K

09 декабря 2006 года

mohito

35 / / 24.11.2005

Решана — значит ошибка больше не возникает…. После переустановки Windows и Visual Studio, соответствено все проекты стали нормально компилироваться…
Я предпологаю что проблема все таки была связана с вирусом Nashta (или что-то наподобе) который я обнаружил мой антивирус и по его(антивируса) заявлению успешно удалил…

8.2K

13 декабря 2006 года

mohito

35 / / 24.11.2005

Я нашел в чем была проблема!
Вчера запустил Студию и опять вылетела ошибка 2019…. я думал я комп разнесу=)

Потом стал прикидывать от чего это… и вспомнил… за 2 часа до этого установил себе IFS Development Kit for Windows XP и прописал в настройках Visual Studio пути к папакам Inc и Lib из DDK… и эти папки были первыми по порядку… видимо он вних пытался искать и нефига не находил=)

63

13 декабря 2006 года

Zorkus

2.6K / / 04.11.2006

Сказал бы сразу:)

Понравилась статья? Поделить с друзьями:
  • Error link 2001
  • Error line contained too many invalid tokens
  • Error line 753 error description pure virtual function call
  • Error line 748
  • Error line 502