Error lnk2001 unresolved external symbol main

C++ Documentation. Contribute to MicrosoftDocs/cpp-docs development by creating an account on GitHub.
description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Linker Tools Error LNK2001

Linker Tools Error LNK2001

10/22/2021

LNK2001

LNK2001

dc1cf267-c984-486c-abd2-fd07c799f7ef

unresolved external symbol «symbol«

The compiled code makes a reference or call to symbol. The symbol isn’t defined in any libraries or object files searched by the linker.

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

There are many ways to get LNK2001 errors. All of them involve a reference to a function or variable that the linker can’t resolve, or find a definition for. The compiler can identify when your code doesn’t declare a symbol, but not when it doesn’t define one. That’s because the definition may be in a different source file or library. If your code refers to a symbol, but it’s never defined, the linker generates an error.

What is an unresolved external symbol?

A symbol is the internal name for a function or global variable. It’s the form of the name used or defined in a compiled object file or library. A global variable is defined in the object file where storage is allocated for it. A function is defined in the object file where the compiled code for the function body is placed. An external symbol is one referenced in one object file, but defined in a different library or object file. An exported symbol is one that’s made publicly available by the object file or library that defines it.

To create an application or DLL, every symbol used must have a definition. The linker must resolve, or find the matching definition for, every external symbol referenced by each object file. The linker generates an error when it can’t resolve an external symbol. It means the linker couldn’t find a matching exported symbol definition in any of the linked files.

Compilation and link issues

This error can occur:

  • When the project is missing a reference to a library (.LIB) or object (.OBJ) file. To fix this issue, add a reference to the required library or object file to your project. For more information, see lib Files as linker input.

  • When the project has a reference to a library (.LIB) or object (.OBJ) file that in turn requires symbols from another library. It may happen even if you don’t call functions that cause the dependency. To fix this issue, add a reference to the other library to your project. For more information, see Understanding the classical model for linking: Taking symbols along for the ride.

  • If you use the /NODEFAULTLIB or /Zl options. When you specify these options, libraries that contain required code aren’t linked into the project unless you’ve explicitly included them. To fix this issue, explicitly include all the libraries you use on the link command line. If you see many missing CRT or Standard Library function names when you use these options, explicitly include the CRT and Standard Library DLLs or library files in the link.

  • If you compile using the /clr option. There may be a missing reference to .cctor. For more information on how to fix this issue, see Initialization of mixed assemblies.

  • If you link to the release mode libraries when building a debug version of an application. Similarly, if you use options /MTd or /MDd or define _DEBUG and then link to the release libraries, you should expect many potential unresolved externals, among other problems. Linking a release mode build with the debug libraries also causes similar problems. To fix this issue, make sure you use the debug libraries in your debug builds, and retail libraries in your retail builds.

  • If your code refers to a symbol from one library version, but you link a different version of the library. Generally, you can’t mix object files or libraries that are built for different versions of the compiler. The libraries that ship in one version may contain symbols that can’t be found in the libraries included with other versions. To fix this issue, build all the object files and libraries with the same version of the compiler before linking them together. For more information, see C++ binary compatibility between Visual Studio versions.

  • If library paths are out of date. The Tools > Options > Projects > VC++ Directories dialog, under the Library files selection, allows you to change the library search order. The Linker folder in the project’s Property Pages dialog box may also contain paths that could be out of date.

  • When a new Windows SDK is installed (perhaps to a different location). The library search order must be updated to point to the new location. Normally, you should put the path to new SDK include and lib directories in front of the default Visual C++ location. Also, a project containing embedded paths may still point to old paths that are valid, but out of date. Update the paths for new functionality added by the new version that’s installed to a different location.

  • If you build at the command line, and have created your own environment variables. Verify that the paths to tools, libraries, and header files go to a consistent version. For more information, see Use the MSVC toolset from the command line.

Coding issues

This error can be caused by:

  • Mismatched case in your source code or module-definition (.def) file. For example, if you name a variable var1 in one C++ source file and try to access it as VAR1 in another, this error is generated. To fix this issue, use consistently spelled and cased names.

  • A project that uses function inlining. It can occur when you define the functions as inline in a source file, rather than in a header file. Inlined functions can’t be seen outside the source file that defines them. To fix this issue, define the inlined functions in the headers where they’re declared.

  • Calling a C function from a C++ program without using an extern "C" declaration for the C function. The compiler uses different internal symbol naming conventions for C and C++ code. The internal symbol name is what the linker looks for when resolving symbols. To fix this issue, use an extern "C" wrapper around all declarations of C functions used in your C++ code, which causes the compiler to use the C internal naming convention for those symbols. Compiler options /Tp and /Tc cause the compiler to compile files as C++ or C, respectively, no matter what the filename extension is. These options can cause internal function names different from what you expect.

  • An attempt to reference functions or data that don’t have external linkage. In C++, inline functions and const data have internal linkage unless explicitly specified as extern. To fix this issue, use explicit extern declarations on symbols referred to outside the defining source file.

  • A missing function body or variable definition. This error is common when you declare, but don’t define, variables, functions, or classes in your code. The compiler only needs a function prototype or extern variable declaration to generate an object file without error, but the linker can’t resolve a call to the function or a reference to the variable because there’s no function code or variable space reserved. To fix this issue, make sure to define every referenced function and variable in a source file or library you link.

  • A function call that uses return and parameter types or calling conventions that don’t match the ones in the function definition. In C++ object files, Name decoration encodes the calling convention, class or namespace scope, and return and parameter types of a function. The encoded string becomes part of the final decorated function name. This name is used by the linker to resolve, or match, calls to the function from other object files. To fix this issue, make sure the function declaration, definition, and calls all use the same scopes, types, and calling conventions.

  • C++ code you call, when you include a function prototype in a class definition, but don’t include the implementation of the function. To fix this issue, be sure to provide a definition for all class members you call.

  • An attempt to call a pure virtual function from an abstract base class. A pure virtual function has no base class implementation. To fix this issue, make sure all called virtual functions are implemented.

  • Trying to use a variable declared within a function (a local variable) outside the scope of that function. To fix this issue, remove the reference to the variable that isn’t in scope, or move the variable to a higher scope.

  • When you build a Release version of an ATL project, producing a message that CRT startup code is required. To fix this issue, do one of the following,

    • Remove _ATL_MIN_CRT from the list of preprocessor defines to allow CRT startup code to be included. For more information, see General property page (Project).

    • If possible, remove calls to CRT functions that require CRT startup code. Instead, use their Win32 equivalents. For example, use lstrcmp instead of strcmp. Known functions that require CRT startup code are some of the string and floating point functions.

Consistency issues

There’s currently no standard for C++ name decoration between compiler vendors, or even between different versions of the same compiler. Object files compiled with different compilers may not use the same naming scheme. Linking them can cause error LNK2001.

Mixing inline and non-inline compile options on different modules can cause LNK2001. If a C++ library is created with function inlining turned on (/Ob1 or /Ob2) but the corresponding header file describing the functions has inlining turned off (no inline keyword), this error occurs. To fix this issue, define the functions inline in the header file you include in other source files.

If you use the #pragma inline_depth compiler directive, make sure you’ve set a value of 2 or greater, and make sure you also use the /Ob1 or /Ob2 compiler option.

This error can occur if you omit the LINK option /NOENTRY when you create a resource-only DLL. To fix this issue, add the /NOENTRY option to the link command.

This error can occur if you use incorrect /SUBSYSTEM or /ENTRY settings in your project. For example, if you write a console application and specify /SUBSYSTEM:WINDOWS, an unresolved external error is generated for WinMain. To fix this issue, make sure you match the options to the project type. For more information on these options and entry points, see the /SUBSYSTEM and /ENTRY linker options.

Exported .def file symbol issues

This error occurs when an export listed in a .def file isn’t found. It could be because the export doesn’t exist, is spelled incorrectly, or uses C++ decorated names. A .def file doesn’t take decorated names. To fix this issue, remove unneeded exports, and use extern "C" declarations for exported symbols.

Use the decorated name to find the error

The C++ compiler and linker use Name Decoration, also known as name-mangling. Name decoration encodes extra information about the type of a variable in its symbol name. The symbol name for a function encodes its return type, parameter types, scope, and calling convention. This decorated name is the symbol name the linker searches for to resolve external symbols.

A link error can result if the declaration of a function or variable doesn’t exactly match the definition of the function or variable. That’s because any difference becomes part of the symbol name to match. The error can happen even if the same header file is used in both the calling code and the defining code. One way it may occur is if you compile the source files by using different compiler flags. For example, if your code is compiled to use the __vectorcall calling convention, but you link to a library that expects clients to call it using the default __cdecl or __fastcall calling convention. In this case, the symbols don’t match because the calling conventions are different.

To help you find the cause, the error message shows you two versions of the name. It displays both the «friendly name,» the name used in source code, and the decorated name (in parentheses). You don’t need to know how to interpret the decorated name. You can still search for and compare it with other decorated names. Command-line tools can help to find and compare the expected symbol name and the actual symbol name:

  • The /EXPORTS and /SYMBOLS options of the DUMPBIN command-line tool are useful here. They can help you discover which symbols are defined in your .dll and object or library files. You can use the symbols list to verify that the exported decorated names match the decorated names the linker searches for.

  • In some cases, the linker can only report the decorated name for a symbol. You can use the UNDNAME command-line tool to get the undecorated form of a decorated name.

Additional resources

For more information, 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’ve created an VC++ 2k5 DLL with CLR (but not with MFC or ATL) from existing source.  I can get this to compile and link until it produces an LNK2001: unresolved external symbol _main error.

    I’ve looked this error up in the help and tried most all of the suggestions in the help & or the KB Q291952 article to do with thise error and none make the error go away.

    That is… 
    1) I checked it was an DLL Project not a console project
    2) I checked that the /Zl command-line option is not pressent. (it’s /Zi)
    3) I added msvcrt.lib and/or msvcmrt.lib as additional dependancies
    4) I checked that _ATL_MIN_CRT is not defined in the defines.

    I don’t know what else could be the problem.  Anyone else run into this?  Seems like it should be simple to find and fix whatever the problem is, but apparently I’m missing the obvious solution.

    Thanks,

Answers

  • Actually I just tried removing the _main or DLLMain, and chose (in the IDE Project settings) to inherit from parent or project default and I got it working.

    Thanks for your time.

Your linkage consumes libraries before the object files that refer to them

  • You are trying to compile and link your program with the GCC toolchain.
  • Your linkage specifies all of the necessary libraries and library search paths
  • If libfoo depends on libbar, then your linkage correctly puts libfoo before libbar.
  • Your linkage fails with undefined reference to something errors.
  • But all the undefined somethings are declared in the header files you have
    #included and are in fact defined in the libraries that you are linking.

Examples are in C. They could equally well be C++

A minimal example involving a static library you built yourself

my_lib.c

#include "my_lib.h"
#include <stdio.h>

void hw(void)
{
    puts("Hello World");
}

my_lib.h

#ifndef MY_LIB_H
#define MT_LIB_H

extern void hw(void);

#endif

eg1.c

#include <my_lib.h>

int main()
{
    hw();
    return 0;
}

You build your static library:

$ gcc -c -o my_lib.o my_lib.c
$ ar rcs libmy_lib.a my_lib.o

You compile your program:

$ gcc -I. -c -o eg1.o eg1.c

You try to link it with libmy_lib.a and fail:

$ gcc -o eg1 -L. -lmy_lib eg1.o 
eg1.o: In function `main':
eg1.c:(.text+0x5): undefined reference to `hw'
collect2: error: ld returned 1 exit status

The same result if you compile and link in one step, like:

$ gcc -o eg1 -I. -L. -lmy_lib eg1.c
/tmp/ccQk1tvs.o: In function `main':
eg1.c:(.text+0x5): undefined reference to `hw'
collect2: error: ld returned 1 exit status

A minimal example involving a shared system library, the compression library libz

eg2.c

#include <zlib.h>
#include <stdio.h>

int main()
{
    printf("%sn",zlibVersion());
    return 0;
}

Compile your program:

$ gcc -c -o eg2.o eg2.c

Try to link your program with libz and fail:

$ gcc -o eg2 -lz eg2.o 
eg2.o: In function `main':
eg2.c:(.text+0x5): undefined reference to `zlibVersion'
collect2: error: ld returned 1 exit status

Same if you compile and link in one go:

$ gcc -o eg2 -I. -lz eg2.c
/tmp/ccxCiGn7.o: In function `main':
eg2.c:(.text+0x5): undefined reference to `zlibVersion'
collect2: error: ld returned 1 exit status

And a variation on example 2 involving pkg-config:

$ gcc -o eg2 $(pkg-config --libs zlib) eg2.o 
eg2.o: In function `main':
eg2.c:(.text+0x5): undefined reference to `zlibVersion'

What are you doing wrong?

In the sequence of object files and libraries you want to link to make your
program, you are placing the libraries before the object files that refer to
them. You need to place the libraries after the object files that refer
to them.

Link example 1 correctly:

$ gcc -o eg1 eg1.o -L. -lmy_lib

Success:

$ ./eg1 
Hello World

Link example 2 correctly:

$ gcc -o eg2 eg2.o -lz

Success:

$ ./eg2 
1.2.8

Link the example 2 pkg-config variation correctly:

$ gcc -o eg2 eg2.o $(pkg-config --libs zlib) 
$ ./eg2
1.2.8

The explanation

Reading is optional from here on.

By default, a linkage command generated by GCC, on your distro,
consumes the files in the linkage from left to right in
commandline sequence. When it finds that a file refers to something
and does not contain a definition for it, to will search for a definition
in files further to the right. If it eventually finds a definition, the
reference is resolved. If any references remain unresolved at the end,
the linkage fails: the linker does not search backwards.

First, example 1, with static library my_lib.a

A static library is an indexed archive of object files. When the linker
finds -lmy_lib in the linkage sequence and figures out that this refers
to the static library ./libmy_lib.a, it wants to know whether your program
needs any of the object files in libmy_lib.a.

There is only object file in libmy_lib.a, namely my_lib.o, and there’s only one thing defined
in my_lib.o, namely the function hw.

The linker will decide that your program needs my_lib.o if and only if it already knows that
your program refers to hw, in one or more of the object files it has already
added to the program, and that none of the object files it has already added
contains a definition for hw.

If that is true, then the linker will extract a copy of my_lib.o from the library and
add it to your program. Then, your program contains a definition for hw, so
its references to hw are resolved.

When you try to link the program like:

$ gcc -o eg1 -L. -lmy_lib eg1.o

the linker has not added eg1.o to the program when it sees
-lmy_lib. Because at that point, it has not seen eg1.o.
Your program does not yet make any references to hw: it
does not yet make any references at all, because all the references it makes
are in eg1.o.

So the linker does not add my_lib.o to the program and has no further
use for libmy_lib.a.

Next, it finds eg1.o, and adds it to be program. An object file in the
linkage sequence is always added to the program. Now, the program makes
a reference to hw, and does not contain a definition of hw; but
there is nothing left in the linkage sequence that could provide the missing
definition. The reference to hw ends up unresolved, and the linkage fails.

Second, example 2, with shared library libz

A shared library isn’t an archive of object files or anything like it. It’s
much more like a program that doesn’t have a main function and
instead exposes multiple other symbols that it defines, so that other
programs can use them at runtime.

Many Linux distros today configure their GCC toolchain so that its language drivers (gcc,g++,gfortran etc)
instruct the system linker (ld) to link shared libraries on an as-needed basis.
You have got one of those distros.

This means that when the linker finds -lz in the linkage sequence, and figures out that this refers
to the shared library (say) /usr/lib/x86_64-linux-gnu/libz.so, it wants to know whether any references that it has added to your program that aren’t yet defined have definitions that are exported by libz

If that is true, then the linker will not copy any chunks out of libz and
add them to your program; instead, it will just doctor the code of your program
so that:-

  • At runtime, the system program loader will load a copy of libz into the
    same process as your program whenever it loads a copy of your program, to run it.

  • At runtime, whenever your program refers to something that is defined in
    libz, that reference uses the definition exported by the copy of libz in
    the same process.

Your program wants to refer to just one thing that has a definition exported by libz,
namely the function zlibVersion, which is referred to just once, in eg2.c.
If the linker adds that reference to your program, and then finds the definition
exported by libz, the reference is resolved

But when you try to link the program like:

gcc -o eg2 -lz eg2.o

the order of events is wrong in just the same way as with example 1.
At the point when the linker finds -lz, there are no references to anything
in the program: they are all in eg2.o, which has not yet been seen. So the
linker decides it has no use for libz. When it reaches eg2.o, adds it to the program,
and then has undefined reference to zlibVersion, the linkage sequence is finished;
that reference is unresolved, and the linkage fails.

Lastly, the pkg-config variation of example 2 has a now obvious explanation.
After shell-expansion:

gcc -o eg2 $(pkg-config --libs zlib) eg2.o

becomes:

gcc -o eg2 -lz eg2.o

which is just example 2 again.

I can reproduce the problem in example 1, but not in example 2

The linkage:

gcc -o eg2 -lz eg2.o

works just fine for you!

(Or: That linkage worked fine for you on, say, Fedora 23, but fails on Ubuntu 16.04)

That’s because the distro on which the linkage works is one of the ones that
does not configure its GCC toolchain to link shared libraries as-needed.

Back in the day, it was normal for unix-like systems to link static and shared
libraries by different rules. Static libraries in a linkage sequence were linked
on the as-needed basis explained in example 1, but shared libraries were linked unconditionally.

This behaviour is economical at linktime because the linker doesn’t have to ponder
whether a shared library is needed by the program: if it’s a shared library,
link it. And most libraries in most linkages are shared libraries. But there are disadvantages too:-

  • It is uneconomical at runtime, because it can cause shared libraries to be
    loaded along with a program even if doesn’t need them.

  • The different linkage rules for static and shared libraries can be confusing
    to inexpert programmers, who may not know whether -lfoo in their linkage
    is going to resolve to /some/where/libfoo.a or to /some/where/libfoo.so,
    and might not understand the difference between shared and static libraries
    anyway.

This trade-off has led to the schismatic situation today. Some distros have
changed their GCC linkage rules for shared libraries so that the as-needed
principle applies for all libraries. Some distros have stuck with the old
way.

Why do I still get this problem even if I compile-and-link at the same time?

If I just do:

$ gcc -o eg1 -I. -L. -lmy_lib eg1.c

surely gcc has to compile eg1.c first, and then link the resulting
object file with libmy_lib.a. So how can it not know that object file
is needed when it’s doing the linking?

Because compiling and linking with a single command does not change the
order of the linkage sequence.

When you run the command above, gcc figures out that you want compilation +
linkage. So behind the scenes, it generates a compilation command, and runs
it, then generates a linkage command, and runs it, as if you had run the
two commands:

$ gcc -I. -c -o eg1.o eg1.c
$ gcc -o eg1 -L. -lmy_lib eg1.o

So the linkage fails just as it does if you do run those two commands. The
only difference you notice in the failure is that gcc has generated a
temporary object file in the compile + link case, because you’re not telling it
to use eg1.o. We see:

/tmp/ccQk1tvs.o: In function `main'

instead of:

eg1.o: In function `main':

See also

The order in which interdependent linked libraries are specified is wrong

Putting interdependent libraries in the wrong order is just one way
in which you can get files that need definitions of things coming
later in the linkage than the files that provide the definitions. Putting libraries before the
object files that refer to them is another way of making the same mistake.

Содержание

  1. Ошибка средств компоновщика LNK2001
  2. Что такое неразрешенный внешний символ?
  3. Проблемы компиляции и компоновки
  4. Проблемы кодирования
  5. Проблемы согласованности
  6. Ошибки экспортированного файла DEF
  7. Использовать декорированное имя для поиска ошибки
  8. Error lnk2001 unresolved external symbol boost
  9. Answered by:
  10. Question

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

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

Это сообщение об ошибке после неустранимой ошибки LNK1120. Чтобы устранить ошибку LNK1120, сначала исправьте все ошибки LNK2001 и LNK2019.

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

Что такое неразрешенный внешний символ?

Символ — это внутреннее имя функции или глобальной переменной. Это форма имени, используемая или определенная в скомпилированном объектном файле или библиотеке. Глобальная переменная определяется в объектном файле, где для него выделяется хранилище. Функция определена в объектном файле, где размещается скомпилированный код для тела функции. Внешний символ является ссылкой в одном файле объекта, но определен в другой библиотеке или объектном файле. Экспортированный символ — это открытый объект, который становится общедоступным для файлового файла или библиотеки, определяющей его.

Для создания приложения или библиотеки DLL в каждом используемом символе должно быть определено определение. Компоновщик должен Разрешитьили найти определение сопоставления для каждого внешнего символа, на который ссылается каждый файл объекта. Компоновщик создает ошибку, если не удается разрешить внешний символ. Это означает, что компоновщику не удалось найти соответствующее определение экспортированного символа в любом из связанных файлов.

Проблемы компиляции и компоновки

Эта ошибка может возникать:

Если в проекте отсутствует ссылка на библиотеку (. LIB) или Object (. OBJ-файл). Чтобы устранить эту проблему, добавьте в проект ссылку на требуемую библиотеку или файл объекта. Дополнительные сведения см. в разделе lib files as input компоновщика.

Если проект содержит ссылку на библиотеку (. LIB) или Object (. OBJ), который, в свою очередь, требуются символы из другой библиотеки. Это может произойти даже в том случае, если не вызываются функции, вызывающие зависимость. Чтобы устранить эту проблему, добавьте в проект ссылку на другую библиотеку. Дополнительные сведения см. в разделе понимание классической модели для связывания: использование символов в качестве пути.

При использовании параметров /NODEFAULTLIB или /Zl . При указании этих параметров библиотеки, содержащие требуемый код, не будут связаны с проектом, если они не включены явным образом. Чтобы устранить эту проблему, явно включите все библиотеки, используемые в командной строке компоновки. Если при использовании этих параметров отображается множество отсутствующих имен функций CRT или стандартной библиотеки, явно включите библиотеки CRT и библиотеки стандартных библиотек или файлы библиотеки в ссылку.

При компиляции с параметром /CLR . Возможно, отсутствует ссылка на .cctor . Дополнительные сведения об устранении этой проблемы см. в разделе Инициализация смешанных сборок.

Если при построении отладочной версии приложения вы связываетесь с библиотеками в режиме выпуска. Аналогично, если вы используете параметры /MTD или /MDD или определяете _DEBUG , а затем связываетесь с библиотеками выпусков, то во многих других случаях следует рассчитывать на множество потенциальных неразрешенных внешних значений. Связывание сборки в режиме выпуска с отладочными библиотеками также вызывает аналогичные проблемы. Чтобы устранить эту проблему, убедитесь, что вы используете отладочные библиотеки в отладочных сборках и розничных библиотеках в ваших розничных сборках.

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

Если пути к библиотекам устарели. диалоговое окно сервис > параметры > проекты > VC++ каталоги в области выбор файлов библиотеки позволяет изменить порядок поиска в библиотеке. Папка Компоновщик в диалоговом окне страницы свойств проекта может также содержать неактуальные пути.

при установке нового Windows SDK (возможно, в другое расположение). Необходимо обновить порядок поиска библиотеки, чтобы он указывал на новое расположение. Как правило, путь следует поместить в новый каталог include и lib для пакета SDK перед расположением Visual C++ по умолчанию. Кроме того, проект, содержащий внедренные пути, может по-прежнему указывать на старые пути, которые являются допустимыми, но устарели. Обновите пути для новых функций, добавленных новой версией, которая установлена в другое расположение.

При построении в командной строке и создании собственных переменных среды. Убедитесь, что пути к инструментам, библиотекам и файлам заголовков имеют одинаковую версию. Дополнительные сведения см. в статье Использование набора инструментов MSVC из командной строки.

Проблемы кодирования

Эта ошибка может быть вызвана следующими причинами.

Несовпадение регистра в исходном коде или файле определения модуля (DEF). Например, если вы назначите переменную var1 в одном исходном файле C++ и попытаетесь получить к ней доступ, как VAR1 в другой, возникает эта ошибка. Чтобы устранить эту проблему, используйте согласованное написание имен и имена регистров.

Проект, использующий встраивание функций. Это может произойти при определении функций inline в исходном файле, а не в файле заголовка. Встроенные функции не отображаются за пределами исходного файла, который их определяет. Чтобы устранить эту проблему, определите встроенные функции в заголовках, где они объявляются.

Вызов функции C из программы на языке C++ без использования extern «C» объявления для функции C. Компилятор использует разные внутренние соглашения об именовании символов для кода C и C++. Внутреннее имя символа — это то, что ищет компоновщик при разрешении символов. Чтобы устранить эту проблему, используйте extern «C» обертку для всех объявлений функций C, используемых в коде C++, в результате чего компилятор должен использовать внутреннее соглашение об именовании языка c для этих символов. Параметры компилятора /TP и /TC заставляют компилятор компилировать файлы как C++ или C соответственно, независимо от расширения имени файла. Эти параметры могут привести к тому, что имена внутренних функций отличаются от предполагаемых.

Попытка сослаться на функции или данные, у которых нет внешней компоновки. В C++ встроенные функции и const данные имеют внутреннюю компоновку, если явно не указано в качестве extern . Чтобы устранить эту проблему, используйте явные extern объявления для символов, которые ссылаются вне определяющего исходного файла.

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

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

Код C++, который вызывается при включении прототипа функции в определение класса, но не включает реализацию функции. Чтобы устранить эту проблему, обязательно предоставьте определение для всех членов класса, которые вы вызываете.

Попытка вызвать чисто виртуальную функцию из абстрактного базового класса. Чистая виртуальная функция не имеет реализации базового класса. Чтобы устранить эту проблему, убедитесь, что все вызванные виртуальные функции реализованы.

Попытка использовать переменную, объявленную в функции (Локальная переменная), за пределами области этой функции. Чтобы устранить эту проблему, удалите ссылку на переменную, которая не находится в области действия, или переместите переменную в область более высокого уровня.

При построении окончательной версии проекта ATL создается сообщение о том, что код запуска CRT является обязательным. Чтобы устранить эту проблему, выполните одно из следующих действий.

Удалите _ATL_MIN_CRT из списка определений препроцессора, чтобы разрешить включение кода запуска CRT. Дополнительные сведения см. в разделе Страница свойств General (Project).

Если это возможно, удалите вызовы функций CRT, требующих код запуска CRT. Вместо этого используйте эквиваленты Win32. Например, используйте lstrcmp вместо strcmp . Известными функциями, требующими код запуска CRT, являются некоторые функции строк и вычислений с плавающей запятой.

Проблемы согласованности

В настоящее время нет стандарта для декорирования имен C++ между поставщиками компиляторов или даже между разными версиями одного и того же компилятора. Объектные файлы, скомпилированные с разными компиляторами, могут не использовать одинаковую схему именования. Связывание их может вызвать ошибку LNK2001.

Смешивание встроенных и невстроенных параметров компиляции в разных модулях может вызвать ошибку LNK2001. Если библиотека C++ создается с включенной функцией встраивания функций (/Ob1 или /Ob2), но соответствующий заголовочный файл, описывающий функции, отключен (без inline ключевого слова), возникает эта ошибка. Чтобы устранить эту проблему, определите функции inline в файле заголовка, который включается в другие исходные файлы.

Если вы используете #pragma inline_depth директиву компилятора, убедитесь, что задано значение 2 или более, и убедитесь, что вы также используете параметр компилятора /Ob1 или /Ob2 .

Эта ошибка может возникать, если опустить параметр LINK/NOENTRY при создании библиотеки DLL только для ресурсов. Чтобы устранить эту проблему, добавьте параметр/NOENTRY в команду Link.

Эта ошибка может возникать, если в проекте используются неверные параметры/SUBSYSTEM или/ENTRY. Например, при написании консольного приложения и задании/SUBSYSTEM: WINDOWS создается неразрешенная внешняя ошибка для WinMain . Чтобы устранить эту проблему, убедитесь, что вы соответствуете параметрам типа проекта. Дополнительные сведения об этих параметрах и точках входа см. в разделе Параметры компоновщика /SUBSYSTEM и /entry .

Ошибки экспортированного файла DEF

Эта ошибка возникает, когда экспорт, указанный в DEF-файле, не найден. Это может быть вызвано тем, что экспорт не существует, написан неправильно или использует декорированные имена C++. DEF-файл не имеет декорированных имен. Чтобы устранить эту проблему, удалите ненужные экспорты и используйте extern «C» объявления для экспортированных символов.

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

Компилятор и компоновщик C++ используют декорирование имен, также называемое искажением имени. Декорирование имен кодирует дополнительные сведения о типе переменной в ее имени символа. Имя символа для функции кодирует свой возвращаемый тип, типы параметров, область и соглашение о вызовах. Это декорированное имя — это имя символа, которое компоновщик ищет для разрешения внешних символов.

Ошибка связи может возникнуть, если объявление функции или переменной не полностью соответствует определению функции или переменной. Это связано с тем, что все различия становятся частью имени символа для сопоставления. Ошибка может возникать даже в том случае, если один и тот же файл заголовка используется как в вызывающем, так и в коде, определяющем код. Это может произойти, если вы компилируете исходные файлы с помощью различных флагов компилятора. Например, если код компилируется для использования __vectorcall соглашения о вызовах, но вы связываетесь с библиотекой, которая ожидает, что клиенты будут вызывать его с помощью соглашения по умолчанию __cdecl или __fastcall вызова. В этом случае символы не совпадают, поскольку соглашения о вызовах различаются.

Чтобы помочь вам найти причину, в сообщении об ошибке отображаются две версии имени. В нем отображается «понятное имя», имя, используемое в исходном коде, и декорированное имя (в круглых скобках). Вам не нужно знать, как интерпретировать декорированное имя. Вы по-прежнему можете выполнять поиск и сравнивать его с другими декорированными именами. Программы командной строки могут помочь найти и сравнить ожидаемое имя символа и фактическое имя символа:

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

В некоторых случаях Компоновщик может сообщать только о декорированном имени символа. Для получения недекорированной формы декорированного имени можно использовать программу командной строки UNDNAME.

Источник

Error lnk2001 unresolved external symbol boost

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I’m using a these libraries DragonFireSDK.lib(from DragonFireSDK — compatible with visual studio and visual studio Express using C++) and sqlite3.lib in my project.

I built the sqlite3.lib in visual studio 2008 and i got the DragonFireSDK.lib file from the SDK team. I linked the sqlite3.lib in my project by following this link http://www.youtube.com/watch?v=BfVP7G4DJkM. When i use only the sqlite3.lib, i’m not getting any link errors. But when i use both the above libraries i get the linking errors. In the first stage i got the following errors,

1>—— Build started: Project: iphoneApp, Configuration: Debug Win32 ——

1> sqlite3.lib(sqlite3.obj) : MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance

1>LINK : warning LNK4075: ignoring ‘/INCREMENTAL’ due to ‘/LTCG’ specification

1>LIBCMT.lib(_file.obj) : error LNK2005: __lock_file already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(_file.obj) : error LNK2005: __unlock_file already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(crt0dat.obj) : error LNK2005: __initterm_e already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(crt0dat.obj) : error LNK2005: _exit already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(crt0dat.obj) : error LNK2005: __exit already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(crt0dat.obj) : error LNK2005: __cexit already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(crt0dat.obj) : error LNK2005: __amsg_exit already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(fflush.obj) : error LNK2005: _fflush already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(hooks.obj) : error LNK2005: «void __cdecl terminate(void)» (?terminate@@YAXXZ) already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(invarg.obj) : error LNK2005: __invoke_watson already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(invarg.obj) : error LNK2005: __invalid_parameter already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(crt0init.obj) : error LNK2005: ___xi_a already defined in MSVCRTD.lib(cinitexe.obj)

1>LIBCMT.lib(crt0init.obj) : error LNK2005: ___xi_z already defined in MSVCRTD.lib(cinitexe.obj)

1>LIBCMT.lib(crt0init.obj) : error LNK2005: ___xc_a already defined in MSVCRTD.lib(cinitexe.obj)

1>LIBCMT.lib(crt0init.obj) : error LNK2005: ___xc_z already defined in MSVCRTD.lib(cinitexe.obj)

1>LIBCMT.lib(mlock.obj) : error LNK2005: __unlock already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(mlock.obj) : error LNK2005: __lock already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(winxfltr.obj) : error LNK2005: __XcptFilter already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LIBCMT.lib(crt0.obj) : error LNK2005: _mainCRTStartup already defined in MSVCRTD.lib(crtexe.obj)

1>LIBCMT.lib(errmode.obj) : error LNK2005: ___set_app_type already defined in MSVCRTD.lib(MSVCR100D.dll)

1>LINK : warning LNK4098: defaultlib ‘MSVCRTD’ conflicts with use of other libs; use /NODEFAULTLIB:library

1>LINK : warning LNK4098: defaultlib ‘MSVCRT’ conflicts with use of other libs; use /NODEFAULTLIB:library

1>LINK : warning LNK4098: defaultlib ‘LIBCMT’ conflicts with use of other libs; use /NODEFAULTLIB:library

1>MSVCRTD.lib(crtexe.obj) : error LNK2001: unresolved external symbol _main

1>LIBCMT.lib(crt0.obj) : error LNK2001: unresolved external symbol _main

1>c:userspriyadocumentsvisual studio 2010ProjectsiphoneAppDebugiphoneApp.exe : fatal error LNK1120: 1 unresolved externals

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Источник

The C default library -independently if you’re using it or not- contains a function (named mainCRTstartup or similar) that is the default entry point (yes: it is not main. Who says that the program entry point in main is deliberately lying, since he wants you to don’t care about how the system internally works)
That function -after initializing all the global objects and calling their constructors- calls main.

So, even if you instruct the linker to tell the OS not to call it, that function exist and places a call to «main» in the symbol table.
As a consequence a function named «main» must exist somewhere to let the linker to resolve that name.

WARNING: What your doing, in fact, makes C++ not to behave anymore as C++, since you have forced the OS to call your function without initializing the global objects before.
If your function (or whatever you call from then on) access whatever (your or library) global object (like, for example, std::cout), may find it in an inconsistent state.
There are pieces of C++ code the must be executed before main enters and after main returns.

Здравствуйте, уважаемые форумчане!

Написал лабу в visual с++ 6.0 по предмету универа, компиляция проходит успешно, но при линковке выходят следующие ошибки:

Linking…
main.obj : error LNK2001: unresolved external symbol «public: __thiscall Group::~Group(void)» (??1Group@@QAE@XZ)
main.obj : error LNK2001: unresolved external symbol «public: class Person * __thiscall Group::FindPerson(char const *)» (?FindPerson@Group@@QAEPAVPerson@@PBD@Z)
main.obj : error LNK2001: unresolved external symbol «public: class Person * __thiscall Group::FindPerson(double)» (?FindPerson@Group@@QAEPAVPerson@@N@Z)
main.obj : error LNK2001: unresolved external symbol «class ostream & __cdecl operator<<(class ostream &,class Person const &)» (??6@YAAAVostream@@AAV0@ABVPerson@@@Z)
main.obj : error LNK2001: unresolved external symbol «public: class Person * __thiscall Group::FindPerson(int)» (?FindPerson@Group@@QAEPAVPerson@@H@Z)
main.obj : error LNK2001: unresolved external symbol «public: bool __thiscall Group::operator==(class Group const &)const » (??8Group@@QBE_NABV0@@Z)
main.obj : error LNK2001: unresolved external symbol «public: class Person & __thiscall Group::operator[](int)» (??AGroup@@QAEAAVPerson@@H@Z)
main.obj : error LNK2001: unresolved external symbol «public: unsigned int __thiscall Group::Size(void)const » (?Size@Group@@QBEIXZ)
main.obj : error LNK2001: unresolved external symbol «class ostream & __cdecl operator<<(class ostream &,class Group const &)» (??6@YAAAVostream@@AAV0@ABVGroup@@@Z)
main.obj : error LNK2001: unresolved external symbol «public: void __thiscall Group::PutPerson(int,class Person const &)» (?PutPerson@Group@@QAEXHABVPerson@@@Z)
main.obj : error LNK2001: unresolved external symbol «public: __thiscall Person::Person(int,char const *,int,double)» (??0Person@@QAE@HPBDHN@Z)
main.obj : error LNK2001: unresolved external symbol «public: __thiscall Group::Group(unsigned int)» (??0Group@@QAE@I@Z)
Debug/main.exe : fatal error LNK1120: 12 unresolved externals
Error executing link.exe.

main.exe — 13 error(s), 0 warning(s)

Погуглив и покопав различные форумы пришел к выводу. что не хватает библиотек, которые необходимо подгружать вручную в project settings. Однако в разных топиках форума пишут о подгружении различных библиотек. Пробовал, не помогает.

Так же пробовал использовать Use MFC in a Shared DLL — так же не помогает.

Помогите разобраться с ситуацией, может нужно сделать еще что-то дополнительно?? Заранее благодарен. Если необходимо выложу архив с написанным, может кто поможет слинковать.

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

Понравилась статья? Поделить с друзьями:
  • Error listen eperm operation not permitted 3000
  • Error listen eaddrnotavail address not available
  • Error listen eaddrinuse code eaddrinuse errno eaddrinuse syscall listen
  • Error listen eaddrinuse address already in use 8081
  • Error listen eaddrinuse address already in use 8080