Link error lnk2001 неразрешенный внешний символ winmain

The following code compiles on VS Express Edition 2008, yet I get the following errors when trying to debug/release: 1>Linking... 1>MSVCRT.lib(crtexew.obj) : error LNK2001: unresolved external

The following code compiles on VS Express Edition 2008, yet I get the following errors when trying to debug/release:

1>Linking...
1>MSVCRT.lib(crtexew.obj) : error LNK2001: unresolved external symbol _WinMain@16
1>E:Documents and SettingsAdministratorDesktopProyecto 2 gràficastestingReleasetesting.exe : fatal error LNK1120: 1 unresolved externals

is it because it’s unable to link a library? How can I solve this?

#include <windows.h>   // use as needed for your system

#include <gl/Gl.h>
#include <gl/glut.h>
#include <iostream>
#include <fstream>

using namespace std;

//**************Global Data
char ifileName[30];
char oFileName[30];
fstream inFile;
fstream outFile;

//************ Data structure 
struct GLfloatPoint
{ GLfloat x,y;
};

const int MAX = 100;
class GLfloatPointArray
{
public:
  int num;
  GLfloatPoint pt[MAX];
};

//***************** subprograms
typedef GLfloat colorType[3];
// subprogram used to draw the control points separately
void drawDot (GLfloat x, GLfloat y, GLfloat r, GLfloat g, GLfloat b)
{ glColor3f(r,g,b);
  glBegin (GL_POINTS);
      glVertex2f (x,y);
  glEnd();
}
// Drawing subprogram - this will draw the curve from a set of points
void drawFloatPolyLine (GLfloatPointArray P, colorType c)
{ glColor3fv (c);
  glBegin(GL_LINE_STRIP);
   for (int i=0; i < P.num; i++)
     glVertex2f (P.pt[i].x,P.pt[i].y);
  glEnd();
}

//******************** myInit 
 void myInit(void)
 {
    glClearColor(1.0,1.0,1.0,0.0);  // set white background color
    glColor3f (0.0f,0.0f,0.0f);    //default color
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity();
    gluOrtho2D(0.0, 640.0, 0.0, 480.0);
    // get data files
    cout << "Enter the input file name: ";
    cin >> ifileName;
    inFile.open (ifileName,ios::in);
    if (inFile.fail())
      return;
    // if want to see points for debugging add output
    // cout << "Enter the output file name: ";
    // cin >> oFileName;
    // outFile.open (oFileName,ios::out);
    // if (outFile.fail())
    //   return;
}

//***************** BEZIER Curve subprograms
// Read the control points 
void readControlPoints (GLfloatPointArray &P)
{
  inFile >> P.num;
  for (int j = 0; j < P.num; j++)
    inFile >> P.pt[j].x >> P.pt[j].y;
}
// output control points to a text file - if you want to see the 
// computations
void printPointArray (GLfloatPointArray P)
{
  outFile << "Size: " << P.num << endl << "Points:" << endl;
  for (int j = 0; j < P.num; j++)
    outFile << "(" << P.pt[j].x << "," << P.pt[j].y << ")" << endl;
}

const int MAXCONTPTS = 100;
int c[MAXCONTPTS];   // the binomial coefficients
//helper routines - compute the coefficient
void ComputeCoeff (int n)
{ int j,k;
  for (k=0;k<=n;k++)
  { //compute n! / (k!*(n-k)!)
    c[k] = 1;
    for (j = n;j>=k+1;j--)
      c[k] *=j;
    for (j = n-k;j>=2;j--)
      c[k] /= j;
  }
}
// compute the blending value
float BlendingValue (int n, int k, float t)
{ int j;
  float bv;
  // compute  c[k]*t^k * (1-t)^(n-k)
  bv = c[k];
  for (j=1; j<=k;j++)
    bv *= t;
  for (j = 1;j<=n-k;j++)
    bv *= (1-t);
  return bv;
}

// compute one point on the Bezier curve - fixed value of t
void ComputePoint (float t, int n, GLfloatPoint & p, 
                   GLfloatPointArray ctrlPts)
{ int k;
  float b;
  p.x = 0.0;
  p.y = 0.0;
  for (k = 0; k<=n;k++)
  {  b = BlendingValue (n,k,t);
     p.x += ctrlPts.pt[k].x*b;
     p.y  += ctrlPts.pt[k].y*b;
  }
}
// compute the array of Bezier points - drawing done separately
void Bezier ( GLfloatPointArray controlPts, int numInter, 
              GLfloatPointArray & curve)
{ // there are numContPts+1 control points and numInter t values to evaluate the curve
  int k;
  float t;
  ComputeCoeff (controlPts.num-1);
  curve.num = numInter+1;
  for (k=0; k<=numInter; k++)
  { t = (float) k / (float) numInter;
    ComputePoint (t, controlPts.num-1,curve.pt[k],controlPts);
  }
}

//************************ myDisplay 
void myDisplay(void)
{  
   int numbCurves;
   GLfloatPointArray ControlPts,BezCurve;
   colorType C = {0.0f,1.0f,0.0f};

   glClear(GL_COLOR_BUFFER_BIT);     // clear the screen 

   inFile >> numbCurves;
   for (int i = 0; i < numbCurves; i++)
   { 
     // read control points and draw them in red big points
     readControlPoints (ControlPts);
     glPointSize (4.0);
     for (int j = 0; j < ControlPts.num; j++)
       drawDot (ControlPts.pt[j].x,ControlPts.pt[j].y,1,0,0);
     glPointSize (1.0);
     // Compute the Bezier curve points and draw
     Bezier (ControlPts,50,BezCurve);
       // draw the Bezier curve
     drawFloatPolyLine (BezCurve,C);
     glFlush ();
   }
}

//**************************** main
void main(int argc, char** argv)
{
    glutInit(&argc, argv);          // initialize the toolkit
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
    glutInitWindowSize(640,480);     // set window size
    glutInitWindowPosition(100, 150); // set window position on screen
    glutCreateWindow("Bezier Curve drawing"); // open the screen window
    glutDisplayFunc(myDisplay);     // register redraw function
    myInit();                   
    glutMainLoop();              // go into a perpetual loop
}

The following code compiles on VS Express Edition 2008, yet I get the following errors when trying to debug/release:

1>Linking...
1>MSVCRT.lib(crtexew.obj) : error LNK2001: unresolved external symbol _WinMain@16
1>E:Documents and SettingsAdministratorDesktopProyecto 2 gràficastestingReleasetesting.exe : fatal error LNK1120: 1 unresolved externals

is it because it’s unable to link a library? How can I solve this?

#include <windows.h>   // use as needed for your system

#include <gl/Gl.h>
#include <gl/glut.h>
#include <iostream>
#include <fstream>

using namespace std;

//**************Global Data
char ifileName[30];
char oFileName[30];
fstream inFile;
fstream outFile;

//************ Data structure 
struct GLfloatPoint
{ GLfloat x,y;
};

const int MAX = 100;
class GLfloatPointArray
{
public:
  int num;
  GLfloatPoint pt[MAX];
};

//***************** subprograms
typedef GLfloat colorType[3];
// subprogram used to draw the control points separately
void drawDot (GLfloat x, GLfloat y, GLfloat r, GLfloat g, GLfloat b)
{ glColor3f(r,g,b);
  glBegin (GL_POINTS);
      glVertex2f (x,y);
  glEnd();
}
// Drawing subprogram - this will draw the curve from a set of points
void drawFloatPolyLine (GLfloatPointArray P, colorType c)
{ glColor3fv (c);
  glBegin(GL_LINE_STRIP);
   for (int i=0; i < P.num; i++)
     glVertex2f (P.pt[i].x,P.pt[i].y);
  glEnd();
}

//******************** myInit 
 void myInit(void)
 {
    glClearColor(1.0,1.0,1.0,0.0);  // set white background color
    glColor3f (0.0f,0.0f,0.0f);    //default color
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity();
    gluOrtho2D(0.0, 640.0, 0.0, 480.0);
    // get data files
    cout << "Enter the input file name: ";
    cin >> ifileName;
    inFile.open (ifileName,ios::in);
    if (inFile.fail())
      return;
    // if want to see points for debugging add output
    // cout << "Enter the output file name: ";
    // cin >> oFileName;
    // outFile.open (oFileName,ios::out);
    // if (outFile.fail())
    //   return;
}

//***************** BEZIER Curve subprograms
// Read the control points 
void readControlPoints (GLfloatPointArray &P)
{
  inFile >> P.num;
  for (int j = 0; j < P.num; j++)
    inFile >> P.pt[j].x >> P.pt[j].y;
}
// output control points to a text file - if you want to see the 
// computations
void printPointArray (GLfloatPointArray P)
{
  outFile << "Size: " << P.num << endl << "Points:" << endl;
  for (int j = 0; j < P.num; j++)
    outFile << "(" << P.pt[j].x << "," << P.pt[j].y << ")" << endl;
}

const int MAXCONTPTS = 100;
int c[MAXCONTPTS];   // the binomial coefficients
//helper routines - compute the coefficient
void ComputeCoeff (int n)
{ int j,k;
  for (k=0;k<=n;k++)
  { //compute n! / (k!*(n-k)!)
    c[k] = 1;
    for (j = n;j>=k+1;j--)
      c[k] *=j;
    for (j = n-k;j>=2;j--)
      c[k] /= j;
  }
}
// compute the blending value
float BlendingValue (int n, int k, float t)
{ int j;
  float bv;
  // compute  c[k]*t^k * (1-t)^(n-k)
  bv = c[k];
  for (j=1; j<=k;j++)
    bv *= t;
  for (j = 1;j<=n-k;j++)
    bv *= (1-t);
  return bv;
}

// compute one point on the Bezier curve - fixed value of t
void ComputePoint (float t, int n, GLfloatPoint & p, 
                   GLfloatPointArray ctrlPts)
{ int k;
  float b;
  p.x = 0.0;
  p.y = 0.0;
  for (k = 0; k<=n;k++)
  {  b = BlendingValue (n,k,t);
     p.x += ctrlPts.pt[k].x*b;
     p.y  += ctrlPts.pt[k].y*b;
  }
}
// compute the array of Bezier points - drawing done separately
void Bezier ( GLfloatPointArray controlPts, int numInter, 
              GLfloatPointArray & curve)
{ // there are numContPts+1 control points and numInter t values to evaluate the curve
  int k;
  float t;
  ComputeCoeff (controlPts.num-1);
  curve.num = numInter+1;
  for (k=0; k<=numInter; k++)
  { t = (float) k / (float) numInter;
    ComputePoint (t, controlPts.num-1,curve.pt[k],controlPts);
  }
}

//************************ myDisplay 
void myDisplay(void)
{  
   int numbCurves;
   GLfloatPointArray ControlPts,BezCurve;
   colorType C = {0.0f,1.0f,0.0f};

   glClear(GL_COLOR_BUFFER_BIT);     // clear the screen 

   inFile >> numbCurves;
   for (int i = 0; i < numbCurves; i++)
   { 
     // read control points and draw them in red big points
     readControlPoints (ControlPts);
     glPointSize (4.0);
     for (int j = 0; j < ControlPts.num; j++)
       drawDot (ControlPts.pt[j].x,ControlPts.pt[j].y,1,0,0);
     glPointSize (1.0);
     // Compute the Bezier curve points and draw
     Bezier (ControlPts,50,BezCurve);
       // draw the Bezier curve
     drawFloatPolyLine (BezCurve,C);
     glFlush ();
   }
}

//**************************** main
void main(int argc, char** argv)
{
    glutInit(&argc, argv);          // initialize the toolkit
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
    glutInitWindowSize(640,480);     // set window size
    glutInitWindowPosition(100, 150); // set window position on screen
    glutCreateWindow("Bezier Curve drawing"); // open the screen window
    glutDisplayFunc(myDisplay);     // register redraw function
    myInit();                   
    glutMainLoop();              // go into a perpetual loop
}

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

Определение

Данная ошибка означает, что в процессе компоновки программы, компоновщик не смог найти определение некоторой сущности, на которую есть ссылка (попытка использования) в программе.

К таким сущностям может относиться, например, функция или переменная.


Причины и решения

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


Используются сторонние библиотеки

  • Не указана необходимая (статическая) библиотека для компоновщика.

    Например, к проекту подключен только *.h файл с объявлениями, но отсутствует код реализации, обычно это *.lib или *.a файлы (в зависимости от используемой системы).
    Требуется явно подключить библиотеку к проекту.

  • Для Visual C++ это можно сделать добавлением следующей строки прямо в код:

    #pragma comment(lib, "libname.lib")
    
  • Для gcc/clang требуется указать файл через ключ -l (эль)

  • Для Qt в .pro файле нужно использовать переменную LIBS:

    LIBS += -L[путь_к_библиотеке] -l[имя_библиотеки]
    
  • Для системы сборки cmake есть target_link_libraries.

  • Библиотека указана, но необходимая сущность, например, класс или функция фактически не экспортируется из библиотеки. Под Windows это может возникать из-за отсуствия __declspec(dllexport) перед сущностью. Обычно это решается макросами. Данная ситуация чаще всего характерна именно для библиотек, находящихся в процессе разработки, и доступных для модификации самому разработчику, нежели для каких-то стабильных версий действительно внешних для проекта библиотек. После разрешения экспортирования библиотеку, конечно же, нужно пересобрать перед непосредственным использованием проблемной сущности.

  • Библиотека указана, но не совпадает разрядность библиотеки и компилируемого кода.

    В общем случае, разрядность собираемого проекта (приложения или библиотеки) должна совпадать с разрядностью используемой сторонней библиотеки. Обычно производители библиотек предоставляют возможность выбора 32 или 64 бит версию использовать. Если библиотека поставляется в исходных кодах и собирается отдельно от текущего проекта, нужно также выбрать правильную разрядность.

  • Библиотека указана, но она собрана для другой (не совместимой) ОС.

    Например при сборке проекта в Windows осуществляется попытка использовать бинарный файл, собранный для Linux. В данном случае нужно использовать файлы, подходящие для вашей ОС.

  • Библиотека указана, но она собрана другим компилятором, не совместимым с используемым.

    Объектные файлы, полученные путем сборки C++ кода разными компиляторами для одной и той же ОС могут быть бинарно несовместимы друг с другом. Требуется использовать совместимые (скорее всего и вовсе одинаковые) компиляторы.

  • Библиотека указана, и собрана тем же компилятором, что и основной проект, но используются разные версии Run-Time библиотек.

    Например, для Visual C++ возможна ситуация, когда библиотека собрана с ключом /MDd, а основной проект с /MTd. Требуется задать ключи так, чтобы использовались одинаковые версии Run-Time библиотек.


Сторонние библиотеки не используются

  • Просто отсутствует определение функции.

    void f(int); // всего лишь объявление. Нет `тела` функции
    int main(){  
        f(42);   // undefined reference to `f(int)'
    }  
    

    Требуется добавить определение функции f:

    void f(int) {
        // тело функции
    }
    

    Может быть ещё частный случай с ошибкой вида:

    undefined reference to `vtable for <имя_класса>`
    

    Такая ошибка возникает, если объявленная виртуальная функция класса, не являющаяся чистой (=0), не содержит реализации.

    class C {
        virtual void f(int);
    };
    

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

    void C::f(int) { // виртуальная функция-член вне определения класса
        // тело функции  
    } 
    
    void f(int) { // свободная функция, не устраняющая проблему
        // тело функции 
    } 
    

    Аналогичная ситуация может возникать при использовании пространств имён, когда объявлении функции находится в пространстве имён:

    // В заголовочном файле
    namespace N {
        void f(int);
    };    
    

    а при реализации указать это пространство имён забыли:

    // В файле реализации
    void f(int) { // функция в глобальном пространстве имён, не устраняющая проблему
        // тело функции  
    }
    
    namespace N {
    void f(int) { // функция в нужном пространстве имён
        // тело функции  
    }
    } // конец пространства имён
    

    Стоит заметить, что C++ разрешает перегрузку функций (существование одноимённых функций, но с разным набором параметров), и в этом случае важно, чтобы сигнатуры функций при объявлении и определении совпадали. Например, вместо объявленной void f(int) была реализована другая:

    void f(const char*) { // const char* вместо int
        // тело функции     
    }
    

    При вызове f(42) будет ошибка:

    undefined reference to `f(int)'
    

    Наличие связки шаблонного класса и дружественной функции также может приводить к ошибке. Например:

    template <class T>
    struct C {
        friend void f(C<T>);   // объявляет *НЕ*шаблонную дружественную функцию
    };
    
    template <class T>         // определяет шаблонную функцию 
    void f(C<T>) { }
    
    int main() {
        C<int> c;
        f(c);                  // undefined reference to `f(C<int>)'
    }
    

    Чтобы объявить шаблонную дружественную функцию, требуется добавить указание шаблонности:

    template <class T>
    struct C {
        template <class V>     // добавили шаблонность для friend функции
        friend void f(C<T>);
    };
    

    Важно, что имя шаблонного параметра для дружественной функции должно отличаться от имени параметра шаблонного класса T, т.к. иначе будет ошибка о сокрытии имени. В частном случае имя класса можно вовсе не указывать, и оставить template <class>. Но это не всегда будет правильным решением, т.к. фактически могла потребоваться дружественная специализация шаблона функции, а не сама шаблонная функция. Подробнее об использовании дружественных функций в шаблонном классе можно ознакомиться здесь.

  • Отсутствует определение статической переменной класса.

    struct S {
        static int i;
    };
    
    int main() {
        S s;
        s.i = 42;  // undefined reference to `S::i'
    }
    

    Нужно добавить определение (выделить память) переменной:

    int S::i;
    
  • Неправильная реализация шаблонного кода.

    Например, реализация шаблонного кода помещена в *.cpp файл, хотя она должна находиться полностью в подключаемом *.h файле. Это требуется по той причине, что компилятор обрабатывает каждый модуль независимо, и в момент инстанцирования шаблона (подстановки конкретного типа) код его реализации должен быть виден. При этом если возможные типы шаблона известны заранее, можно произвести инстанцирование сразу рядом с телом шаблона и не предоставлять его наружу в исходном коде заголовочного файла. Пример:

    // unit.h
    #pragma once
    
    template <class T>
    T f(T);                    // объявление шаблона без реализации
    
    // unit.cpp
    #include "unit.h"
    
    template <class T>
    T f(T t) { return t + t; } // реализация шаблона
    
    template
    int f<int>(int);           // явное инстанцирование для int
    
    template
    double f<double>(double);  // явное инстанцирование для double
    
    // main.cpp
    #include "unit.h"
    
    int main() { 
        f(2);   // ok int
        f(1.5); // ok double
        f('a'); // undefined reference to `char f<char>(char)'
    }
    
  • Файл с кодом не был скомпилирован.

    Например, в случае использования make-файла не было прописано правило построения файла, а в случае использования IDE типа Visual Studio *.cpp файл не добавлен в список файлов проекта.

  • Виртуальная функция в базовом классе не объявлена как = 0 (pure-virtual).

    struct B {
        void virtual f();
    };
    
    struct D : B {
        void f() {}
    };
    
    int main() {
        D d;
    }
    

    При использовании иерархии классов функция в базовом классе, не имеющая реализации должна быть помечена как «чистая»:

    struct B {
        void virtual f() = 0;
    };
    
  • Имя не имеет внешнего связывания.

    Например, есть объявление функции f в модуле А и даже ее реализация в модуле B, но реализация помечена как static:

    // A.cpp
    void f();
    int main() {
        f();   // undefined reference to `f()'
    }
    
    // B.cpp
    static void f() {}
    

    Аналогичная ситуация может возникнуть при использовании безымянного пространства имен:

    // B.cpp
    namespace {
       void f() {}
    }
    

    Или даже при наличии inline у функции:

    // B.cpp
    inline void f() {}
    

names1995

12 / 13 / 6

Регистрация: 13.11.2012

Сообщений: 295

1

12.05.2013, 21:13. Показов 2190. Ответов 12

Метки нет (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "stdafx.h"
#include <GL/glut.h>
#include <windows.h>
#include <glut.h>
#include <glGL.H>
#include <glGLAUX.H>
#pragma comment (lib,"glut32.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
 
    void display ()
    {
        glClear (GL_COLOR_BUFFER_BIT);
        glutSwapBuffers ();
    }
       int main (int argc, char* argv[])
 
        { 
            glutInit (&argc, argv);
            glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
            glutInitWindowSize (9*16, 9*16);
            glutInitWindowPosition (100,700);
            glutCreateWindow ("MineSweeper");
            glClearColor (0,0,0,1);
            glMatrixMode (GL_PROJECTION);
            glOrtho (0, 9*16,9*16,0,-1.0,1.0);
            glutDisplayFunc (display);
            glutMainLoop();
 
        }

Ошибка 2 error LNK1120: неразрешенных внешних элементов: 1 C:UsersAbu Faruqdocumentsvisual studio 2012ProjectssaperReleasesaper.exe

Ошибка 1 error LNK2001: неразрешенный внешний символ «_WinMain@16» C:UsersAbu Faruqdocumentsvisual studio 2012ProjectssapersaperMSVCRT.lib(crtexew.obj)

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



0



503 / 352 / 94

Регистрация: 22.03.2011

Сообщений: 1,112

12.05.2013, 21:20

2

У вас походу проект создан как консольное приложение.



0



12 / 13 / 6

Регистрация: 13.11.2012

Сообщений: 295

12.05.2013, 21:22

 [ТС]

3

нет, проверял приложине win32



0



503 / 352 / 94

Регистрация: 22.03.2011

Сообщений: 1,112

12.05.2013, 21:31

4

Очепятка … НЕ создан. Вам нужно консольное приложение. Точкой входа в winapi приложения является WinMain



0



12 / 13 / 6

Регистрация: 13.11.2012

Сообщений: 295

12.05.2013, 21:33

 [ТС]

5

исправил, теперь пишет что нету библиотеки glut32.dll но он у меня есть



0



503 / 352 / 94

Регистрация: 22.03.2011

Сообщений: 1,112

12.05.2013, 21:43

6

А где она лежит?



0



12 / 13 / 6

Регистрация: 13.11.2012

Сообщений: 295

12.05.2013, 21:47

 [ТС]

7

в system 32



0



503 / 352 / 94

Регистрация: 22.03.2011

Сообщений: 1,112

12.05.2013, 21:48

8

Компьютер 64-х разрядный?



0



12 / 13 / 6

Регистрация: 13.11.2012

Сообщений: 295

12.05.2013, 21:51

 [ТС]

9

да 64



0



503 / 352 / 94

Регистрация: 22.03.2011

Сообщений: 1,112

12.05.2013, 21:54

10

а system32 это тот который syswow64? У вас приложение 32-х разрядное?



0



12 / 13 / 6

Регистрация: 13.11.2012

Сообщений: 295

12.05.2013, 21:55

 [ТС]

11

приложения 32-х разрядное. первый вопрос не понял



0



503 / 352 / 94

Регистрация: 22.03.2011

Сообщений: 1,112

12.05.2013, 21:56

12

Для 32-разрядных приложений идет переадресация из system32 в systemwow64. Также само как и с Program Files

Добавлено через 52 секунды
Там еще много чего есть. http://en.wikipedia.org/wiki/WoW64



0



12 / 13 / 6

Регистрация: 13.11.2012

Сообщений: 295

12.05.2013, 21:59

 [ТС]

13

т.е библиотеку кидать syswow64?

Добавлено через 1 минуту
все исправилось
спасибо



0



ive been working on my project for a while and its been working fine… i havent runned it in release mode for a few days… and today when i tried to compile it in release mode i get the following error..

error LNK2001: unresolved external symbol _WinMain@16

why?! it is a windows application

and it works fine in debug mode

[Edited by — Dragon_Strike on March 30, 2008 8:23:27 AM]

Hello Dragon_Strike,

I guess you are seeing this error because the project has become a little confused about the about whether you are building a console application or a windows application (_WinMain@16 is the entry point for a console application).

I would try the suggestions on the following link: http://www.cryer.co.uk/brian/mswinswdev/msdev_lnk2001ueswm.htm which shows how to check/ change the entry point in MSVC.

Cheers,

Tom

Assuming VC205 (Other versions will be similar): Go to project settings (Alt+F7) -> Configuration Properties -> Linker -> System, and change «Subsystem» to «Windows (/SUBSYSTEM:WINDOWS)».

I suspect that following the above link will have its own problems, since your app will still be being built as a console app.

thx but that didnt help…

i put the entry point in Linker/Advanced to wWinMainCRTStartup … no differance

Quote:Original post by Evil Steve
Assuming VC205 (Other versions will be similar): Go to project settings (Alt+F7) -> Configuration Properties -> Linker -> System, and change «Subsystem» to «Windows (/SUBSYSTEM:WINDOWS)».

I suspect that following the above link will have its own problems, since your app will still be being built as a console app.

it already had that setting… havent changed anything there…

id like to point out that it did work in release mode a few days ago..

EDIT:

could it have something to do with precompiled headers? its the only setting ive been changing the last few days

What does your WinMain() declaration look like?

Demo1.cpp

#include "Demo1.hpp"#include "Application/Win32Exception.hpp"int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow){														try													{													  return Demo1().Run();								}													catch(const drone::application::win32::Exception& e)		{													}													catch(const std::exception& e)								{													}													catch(...)											{													::MessageBox(0, TEXT("Unknown Exception"), 0, 0);		}													return 0;										} // APIENTRY

EDIT:: im using VS 2008

What if you rename _tWinMain to WinMain? That’s what the linker is expecting after all…

error C2731: ‘WinMain’ : function cannot be overloaded

It seems like you somehow have inconsistent UNICODE defines in your project; the linker is expecting a non-Unicode version of WinMain() and you’re giving it a Unicode version. If you change the tWinMain() function to WinMain() make sure that the third parameter is a LPSTR, not a LPTSTR.

  • Remove From My Forums
  • Question

  • Hello everybody,

    I’m experiencing linkage issues while trying to compile a program.

    Anyone out there wanna try to help me?

    Linking...
    CreatureSpriteTable.obj : error LNK2001: unresolved external symbol "class EditString * pdlgEditString" (?pdlgEditString@@3PAVEditString@@A)
    CreatureSpriteTable.obj : error LNK2001: unresolved external symbol "public: void __thiscall CNewEdit::AddString(char const *)" (?AddString@CNewEdit@@QAEXPBD@Z)
    InitCreatureTable.obj : error LNK2001: unresolved external symbol "public: void __thiscall CNewEdit::AddString(char const *)" (?AddString@CNewEdit@@QAEXPBD@Z)
    InitInfo.obj : error LNK2001: unresolved external symbol "public: void __thiscall CNewEdit::AddString(char const *)" (?AddString@CNewEdit@@QAEXPBD@Z)
    
    InitCreatureTable.obj : error LNK2001: unresolved external symbol "class CNewEdit * pedit" (?pedit@@3PAVCNewEdit@@A)
    InitInfo.obj : error LNK2001: unresolved external symbol "class CNewEdit * pedit" (?pedit@@3PAVCNewEdit@@A)
    Debug/ClientInfo.exe : fatal error LNK1120: 3 unresolved externals
    Error executing link.exe.
    
    ClientInfo.exe - 8 error(s), 0 warning(s)

    I’m using Visual C++

Answers

  • If you get  unresolved external symbol means, you have used the class/function in your program. But, the linker is not able to find the definition. 

    If the EditString/CNewEdit::AddString used in executable, you should define in your application.

    If you are tying to use 3rd party application
    DLL, you should link with the Libarry (*.lib) file. you can also use run time linking using

    LoadLibrary/GetProcAddress family function.

    If you want more information about Link 2001, you can check the following msdn link

    http://msdn.microsoft.com/en-us/library/f6xx1b1z(VS.80).aspx


    Thanks and Regards Selvam http://www15.brinkster.com/selvamselvam/

    • Marked as answer by

      Friday, November 25, 2011 9:30 AM

  • Hi,

    As 
    Selvam’s suggestion, LNK2001 means that the Visual Studio or Visual C+ cannot find the definition of the function or class. That mean
     you need to add the LIB or DLL to your project.

    According to your description, I suggest you can ask your friend and find out whether or not there is any other LIB or DLL. Then you can add these libraries to the
    Visual C++ by these step:

    1. 
    Select Tools menu and click option.

    2. Click Directories tab and choose the “Library Files” in Show directories for option.

    3. Double click the blank in the Directories option and add the path of the LIBs or DLLs

    4. Repeat these steps to add the Include files or other option.

    5. Select Ok to finish.

    In addition, you can also load the libraries dynamically. Please check these reference:

    1.
    http://msdn.microsoft.com/en-us/library/ms686923(v=VS.85).aspx

    2.
    http://msdn.microsoft.com/en-us/library/ms686944(v=VS.85).aspx

    Best Regards,

    Rob


    Rob Pan [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by
      Rob Pan
      Friday, November 25, 2011 9:30 AM

Как говорят, «или крест снимите, или трусы наденьте». И учите понятие «единица компиляции».
По какой схеме устроен ваш проект? «Одна единица компиляции» или «много единиц компиляции»?

Си недалеко ушёл от ассемблеров. А в ассемблерах программа компилировалась по частям и собиралась воедино линкером (компоновщиком, редактором связей) — в те времена кода было много, а данных мало. Многие из ошибок невозможно было определить, не запустив линкер. Си++ пользуется многими из архитектурных особенностей ассемблеров и Си — по крайней мере ни одно из модульных решений не стало рекомендацией (кроме костыля extern template class).

Но как говорить «переменная/функция есть, такого-то типа и в другой единице компиляции»? Для этого есть прототипы функций и extern-определения переменных. Их обычно вносят в заголовочные файлы с таким требованием: ничего, что находится в заголовочном файле, не должно производить кода. А код производят…
• Глобальные переменные (без typedef, extern).
• Нешаблонные функции (кроме inline).
• Полностью специализированные шаблонные функции (кроме inline).
• Команда «специализировать шаблон» (template class).

При этом…
• Функции в теле struct/class автоматически inline и кода не производят.
• Для неявной специализации шаблонов существуют обходы — код генерируется дважды, но ошибки не выдаёт.
• «Свой» хедер обычно включают первым, чтобы убедиться, что в нём нет недостающих зависимостей.

В системе «одна единица компиляции» всё просто: есть ровно один файл, подлежащий компиляции. Тогда в хедерных файлах вполне могут быть конструкции, производящие код.

Системы «одна единица компиляции» и «много единиц компиляции» можно комбинировать, но надо знать:
• Все хедеры, которые производят код, должны подключаться из одной-единственной единицы компиляции. Надо чётко осознавать, из какой, и не подключать из чужих.
• У библиотеки всё равно должен быть хедер-фасад, не производящий кода и предназначенный для стыковки с другими единицами компиляции.
Такая конструкция ускоряет полную перекомпиляцию и часто применяется для библиотек, но надо знать: огромные библиотеки вроде SqLite, в 5 мегабайт препроцессированного кода, мешают распараллеливанию компиляции (ибо пока откомпилируется SqLite, остальные процессоры вполне себе соберут остальную программу).

// В схеме «одна единица компиляции»: ничего не делать.
// В схеме «много единиц компиляции»: лишняя зависимость; унести в unit1.cpp
#include <cstdlib>

// В схеме «одна единица компиляции»: убрать extern.
// В схеме «много единиц компиляции»: завести unit1.cpp, там сделать MyType x;
extern MyType X;

// В схеме «одна единица компиляции»: ничего не делать.
// В схеме «много единиц компиляции»: перенести функцию в unit1.cpp, оставив в .h только прототип.
void XReset() {}

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Link error excel
  • Lines are not coplanar как исправить
  • Lineage error a jni error has occurred please check your installation and try again
  • Lineage 2 crash report как исправить windows 10
  • Line protocol is down как исправить cisco

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии