Error lnk2001 unresolved external symbol public

Very simply put: I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions. Anyway, I have

Very simply put:

I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions.

Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class’ constructor, I am getting an «unresolved external symbol» error at compilation.

class test 
{
public:
    static unsigned char X;
    static unsigned char Y;

    ...

    test();
};

test::test() 
{
    X = 1;
    Y = 2;
}

I’m new to C++ so go easy on me. Why can’t I do this?

AustinWBryan's user avatar

AustinWBryan

3,2003 gold badges22 silver badges42 bronze badges

asked Oct 12, 2008 at 7:45

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

dss539's user avatar

dss539

6,7562 gold badges36 silver badges63 bronze badges

answered Oct 12, 2008 at 7:49

Colin Jensen's user avatar

Colin JensenColin Jensen

3,6511 gold badge20 silver badges17 bronze badges

1

Static data members declarations in the class declaration are not definition of them.
To define them you should do this in the .CPP file to avoid duplicated symbols.

The only data you can declare and define is integral static constants.
(Values of enums can be used as constant values as well)

You might want to rewrite your code as:

class test {
public:
  const static unsigned char X = 1;
  const static unsigned char Y = 2;
  ...
  test();
};

test::test() {
}

If you want to have ability to modify you static variables (in other words when it is inappropriate to declare them as const), you can separate you code between .H and .CPP in the following way:

.H :

class test {
public:

  static unsigned char X;
  static unsigned char Y;

  ...

  test();
};

.CPP :

unsigned char test::X = 1;
unsigned char test::Y = 2;

test::test()
{
  // constructor is empty.
  // We don't initialize static data member here, 
  // because static data initialization will happen on every constructor call.
}

2

in my case, I declared one static variable in .h file, like

//myClass.h
class myClass
{
    static int m_nMyVar;
    static void myFunc();
}

and in myClass.cpp, I tried to use this m_nMyVar. It got LINK error like:

error LNK2001: unresolved external symbol «public: static class…
The link error related cpp file looks like:

//myClass.cpp
void myClass::myFunc()
{
    myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}

So I add below code on the top of myClass.cpp

//myClass.cpp
int myClass::m_nMyVar; //it seems redefine m_nMyVar, but it works well
void myClass::myFunc()
{
    myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}

then LNK2001 is gone.

AustinWBryan's user avatar

AustinWBryan

3,2003 gold badges22 silver badges42 bronze badges

answered Sep 18, 2018 at 23:35

Penny's user avatar

PennyPenny

5861 gold badge6 silver badges15 bronze badges

Since this is the first SO thread that seemed to come up for me when searching for «unresolved externals with static const members» in general, I’ll leave another hint to solve one problem with unresolved externals here:

For me, the thing that I forgot was to mark my class definition __declspec(dllexport), and when called from another class (outside that class’s dll’s boundaries), I of course got the my unresolved external error.
Still, easy to forget when you’re changing an internal helper class to a one accessible from elsewhere, so if you’re working in a dynamically linked project, you might as well check that, too.

answered May 4, 2018 at 7:37

Johann Studanski's user avatar

1

When we declare a static variable in a class, it is shared by all the objects of that class. As static variables are initialized only once they are never initialized by a constructor. Instead, the static variable should be explicitly initialized outside the class only once using the scope resolution operator (::).

In the below example, static variable counter is a member of the class Demo. Note how it is initialized explicitly outside the class with the initial value = 0.

#include <iostream>
#include <string>
using namespace std;
class Demo{
   int var;
   static int counter;

   public:
   Demo(int var):var(var){
      cout<<"Counter = "<<counter<<endl;
      counter++;
   }
};
int Demo::counter = 0;                 //static variable initialisation
int main()
{
   Demo d(2), d1(10),d3(1);
}

Output:
Count = 0
Count = 1
Count = 2

answered Apr 17, 2021 at 12:59

Sanya Tayal's user avatar

In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to «see» implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]

answered Feb 10, 2020 at 13:23

whats_wrong_here's user avatar

  • 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

Цитата
Сообщение от nicolas2008
Посмотреть сообщение

Попробую. Может проблема в том, что я обьявляю эту переменную в header файле?

нет, не в том. вот так — все тебе понятно:

обычно в *.h файле, но не обязательно:

C++
1
2
3
4
class Something {
public:
    int m_nValue;
};

и где-то потом:

C++
1
2
Something smth;
smth.m_nValue = 2;

ты создал экземпляр класса Something, и присвоил его public переменной значение. нет экземплара — нет переменной.

теперь так как тебе непонятно:

C++
1
2
3
4
class Something {
public:
    static int s_nValue;
};

переменная объявлена как статическая. т.е. я имею право обратиться к ней, не создавая экземплара этого класса. вот так:

C++
1
Something::nValue = 2;

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

в любом *.срр файле напиши:

C++
1
int Something::s_nValue;

в принципе можешь и в *h, но тогда только одно включение этого файла допустимо, т.к. второго включения не потерпит компилятор: скажет такая переменная уже определена в другом модуле.

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

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

Цитата
Сообщение от nicolas2008
Посмотреть сообщение

Добавлено через 10 минут
Еще, извините, понимаю вопрос глупый, нужно книжки читать), но как в header файле обявить прототип этого класса?

хм… я так понял из этого:

«В header файле обьявлен класс, в котором есть статическая переменная
public: static int k;…»

, что прототип уже имеется, и только переменная нигде не создана?

This topic has been deleted. Only users with topic management privileges can see it.

  • Hi,
    I would like to create a custom class from the great lib QtAV, in a Qt lib template.
    When I compile my class directly from my app, it works well.
    But if I create my custom class in a custom qt lib ( (myStream.lib), I have the error : error LNK2001: unresolved external symbol «public: static struct QMetaObject… when I call it during compilation of my app :

    my custom class is InputStreamPreview :

    #include <QtAVWidgets/VideoPreviewWidget.h>
    
    class InputStreamPreview : public QtAV::VideoPreviewWidget
    {
    Q_OBJECT
    ...
    

    the complete error messages is :

    myStream.lib(moc_inputstreampreview.obj) : error LNK2001: unresolved symbol "public: static struct QMetaObject const QtAV::VideoPreviewWidget::staticMetaObject" (?staticMetaObject@VideoPreviewWidget@QtAV@@2UQMetaObject@@B)
    

    I compile on VS2017 with Qt5.12 and QtAV1.12.0

    Have you got an idea to solve the problem ?
    Thanks.

  • Hi and welcome to devnet,

    Can you show your .pro file ?

  • Three possibilities (in order of commonality):

    1. You haven’t specified the library for linking, or it is not found. See @SGaist’s request and provide the project file so we can inspect it.
    2. You and/or the library you’re using is missing __declspec(dllimport) and/or __declspec(dllexport) for some reason. Make sure when compiling the library that the relevant macros are defined and list the symbols from the dll so you can make sure they’re exported.
    3. You’re mixing incompatible compilers — the library is compiled with something e.g. mingw while you’re trying to link with msvc (also versions matter).
  • This post is deleted!

  • myStream lib

    TARGET = myStream
    DESTDIR = D:/Dev/Programme/myLibs/myStream/lib/ms
    TEMPLATE = lib
    CONFIG += static thread
    QT += widgets avwidgets
    
    UI_HEADERS_DIR = build/ms/h
    OBJECTS_DIR = build/ms/o
    RCC_DIR = build/ms/qrc
    MOC_DIR = build/ms/moc
    INCLUDEPATH = D:/Dev/Programme/3rdparty/ms/include
    LIBS = -LD:/Dev/Programme/3rdparty/ms/lib -lavformat
    
    HEADERS += 
        ../../src/inputstream.h 
        ../../src/dateparser.h 
        ../../src/inputstreammanager.h 
        ../../src/inputstreamcontrol.h 
        ../../src/inputscenecontrol.h 
        ../../src/inputstreamvideo.h 
        ../../src/inputstreampegasus.h 
        ../../src/inputstreaminfo.h 
        ../../src/inputstreamimages.h 
        ../../src/stabilizer.h 
        ../../src/inputstreampreviewslider.h 
        ../../src/inputstreampreview.h
     
    
    SOURCES +=      
        ../../src/inputstream.cpp 
        ../../src/dateparser.cpp 
        ../../src/inputstreammanager.cpp 
        ../../src/inputstreamcontrol.cpp 
        ../../src/inputscenecontrol.cpp 
        ../../src/inputstreamvideo.cpp 
        ../../src/inputstreampegasus.cpp 
        ../../src/inputstreamimages.cpp 
        ../../src/stabilizer.cpp 
        ../../src/inputstreampreviewslider.cpp 
        ../../src/inputstreampreview.cpp
    
    
    

    Application .pro

    QT += network widgets printsupport sql concurrent xml multimedia
    QT += webenginewidgets
    QT += avwidgets
    
    TEMPLATE = app
    DESTDIR = D:/Dev/Programme/AppTest/bin/ms
    VERSION = 4.0
    
    TARGET = AppTest
    DEFINES += TARGET_NAME=\"$$TARGET\"
    
    RC_FILE = ../../qrc/app.rc
    
    UI_HEADERS_DIR = h
    OBJECTS_DIR = o
    RCC_DIR = qrc
    MOC_DIR = moc
    
    INCLUDEPATH = D:/Dev/Programme/3rdparty/ms/include
    
    LIBS = -LD:/Dev/Programme/3rdparty/ms/lib 
            -lmyGUI 
            -lmyCharts 
            -lmyObject 
            -lmyStyleSheet 
            -lmyScene 
            -lmyStream -lswscale -lavformat -lavcodec -lavutil -lswresample -lws2_32 -lsecur32 
            -lmyGraphics 
            -lmyCore 
            -lopencv_core400 
            -lopencv_flann400 -ltbb -lzlib 
            -lgandalf 
            -lexiv2 -llibexpat 
            -llibcrypto 
            -lSMTPEmail 
            -lproj_5_2 
            -lquazip
    
    RESOURCES += 
        ../../qrc/resource.qrc
    
    SOURCES += 
        ../../src/main.cpp 
        ../../src/core/interface.cpp 
        ../../src/core/core.cpp 
        ../../src/gui/maingui.cpp 
        ../../src/view/playerwidget.cpp 
        ../../src/view/sectionview.cpp 
        ../../src/view/inputstreampreview.cpp
    
    HEADERS += 
        ../../src/core/interface.h 
        ../../src/core/core.h 
        ../../src/gui/maingui.h 
        ../../src/view/playerwidget.h 
        ../../src/view/sectionview.h 
        ../../src/view/frame.h 
        ../../src/view/inputstreampreview.h
    
  • @kshegunov

    1. QtAV is imported in Qt config, so I think all is good for that (just add QT += avwidgets)
    2. I have thinking about this problem but I don’t know how to see if it’s OK are not.
    3. I’ve checked, and it’s ok about that.
  • @OPit said in error LNK2001: unresolved external symbol «public: static struct QMetaObject .. from lib template:

    1. QtAV is imported in Qt config, so I think all is good for that (just add QT += avwidgets)

    Did you build that module yourself?

    1. I have thinking about this problem but I don’t know how to see if it’s OK are not.

    Firstly, use dependency walker to find out what the module links against, from there you could also see what kinds of symbols are exported. Then you can do the same for your library and see if everything matches.

    1. I’ve checked, and it’s ok about that.

    How did you check? Where did you get the qtav module from, or did you compiled it yourself?

  • @kshegunov Yes, I’ve built myself the QtAv lib (because the last precompile binaries not use the last version of QtAv).
    I’ve checked which compiler was used during compilation, and it was the same for each module.

    NB : if I link the moc_inputstreampreview.obj file directly in my app, it works ?!?

    LIBS += path/of/file/moc_inputstreampreview.obj
    
  • If I open QtAvWidget1.dll, I found the function :

    ?metaObject@VideoPreviewWidget@QtAV@@UEBAPEBUQMetaObject@@XZ
    

    I can’t read .lib file from dependency walker, how can I check these files ?

  • In your build output, can you see whether the QtAV libraries are currently getting linked to your application ?

  • Hi,
    I’m using QtCreator with visual studio compiler and I don’t have a lot of informations during linking :

    link /NOLOGO /DYNAMICBASE /NXCOMPAT /INCREMENTAL:NO /SUBSYSTEM:WINDOWS "/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'" /VERSION:4.0 /MANIFEST:embed /OUT:....binmsL2R_Video.exe @c:TempL2R_Video.exe.4652.31672.jom
    myStream.lib(moc_inputstreampreview.obj) : error LNK2001: symbole externe non résolu "public: static struct QMetaObject const QtAV::VideoPreviewWidget::staticMetaObject" (?staticMetaObject@VideoPreviewWidget@QtAV@@2UQMetaObject@@B)
    ....binmsL2R_Video.exe : fatal error LNK1120: 1 externes non résolus
    

    But in my Makefile.Release file, the QtAv libs are well written :

    LIBS          = /LIBPATH:D:DevProgramme3rdpartymslib 
    D:DevProgramme3rdpartymslibmyStream.lib 
    D:DevProgramme3rdpartymslibswscale.lib 
    D:DevProgramme3rdpartymslibavformat.lib 
    D:DevProgramme3rdpartymslibavcodec.lib 
    D:DevProgramme3rdpartymslibavutil.lib 
    D:DevProgramme3rdpartymslibswresample.lib 
    secur32.lib 
    D:DevProgramme3rdpartymslibmyGraphics.lib 
    ws2_32.lib shell32.lib advapi32.lib gdi32.lib User32.lib 
    /LIBPATH:D:DevEnvironnementmsQt5.12.0msvc2017_64lib D:DevEnvironnementmsQt5.12.0msvc2017_64libQt5WebEngineWidgets.lib 
    D:DevEnvironnementmsQt5.12.0msvc2017_64libQt5PrintSupport.lib 
    D:DevEnvironnementmsQt5.12.0msvc2017_64libQt5AVWidgets.lib 
    D:DevEnvironnementmsQt5.12.0msvc2017_64libQt5OpenGL.lib 
    D:DevEnvironnementmsQt5.12.0msvc2017_64libQt5Widgets.lib 
    D:DevEnvironnementmsQt5.12.0msvc2017_64libQt5Multimedia.lib 
    D:DevEnvironnementmsQt5.12.0msvc2017_64libQt5WebEngineCore.lib 
    D:DevEnvironnementmsQt5.12.0msvc2017_64libQt5Quick.lib 
    D:DevEnvironnementmsQt5.12.0msvc2017_64libQt5AV.lib 
    ...
    
  • Might be a silly question but are linking to libraries of the same type ? Meaning matching debug/release builds.

  • @OPit And both have the same architecture, i.e. 32 vs. 64 bit?

  • This:

    @OPit said in error LNK2001: unresolved external symbol «public: static struct QMetaObject .. from lib template:

    ?metaObject@VideoPreviewWidget@QtAV@@UEBAPEBUQMetaObject@@XZ
    

    Is very different from this:

    ?staticMetaObject@VideoPreviewWidget@QtAV@@2UQMetaObject@@B
    

    The former is a method, the latter is a (global) variable. Please try again. Could you also provide the content of the moc file in question (the one that fixes the issue if linked with)?

  • @aha_1980 yes, the same architecture

    @kshegunov this is a link to download the file (I can’t upload from the forum) :
    https://we.tl/t-bhEPIToZV2

    Thanks.

  • Hi, perhaps it’s a namespace problem, you could try changing to a using statement in your InputStreamPreview.h:

    #include <QtAVWidgets/VideoPreviewWidget.h>
    
    using namespace QtAV;
    
    class InputStreamPreview : public VideoPreviewWidget
    {
    Q_OBJECT
    ...
    
  • @OPit said in error LNK2001: unresolved external symbol «public: static struct QMetaObject .. from lib template:

    this is a link to download the file (I can’t upload from the forum)

    I’m sorry I wasn’t clear. I meant the generated moc_XXX.cpp file. I have no tools to inspect the object file even if I wanted to because I work exclusively on Linux.

    @hskoglund said in error LNK2001: unresolved external symbol «public: static struct QMetaObject .. from lib template:

    Hi, perhaps it’s a namespace problem, you could try changing to a using statement in your InputStreamPreview.h

    A decent idea, but I don’t think that’s it. moc, while not too smart, does recognize namespaces and generates code accordingly. I do use them and everything links fine.

  • Hi, do you have a moc_VideoPreviewWidget.cpp that’s compiled using Qt 5.12? (The one in the link is built with Qt 5.9.1)

  • Topic: LNK2001: unresolved external symbol  (Read 2308 times)

    0 Members and 1 Guest are viewing this topic.

    Hello, I am newbie :D I just installed SFML and trying to run the tutorial. I got up to the http://www.sfml-dev.org/tutorials/2.1/start-vc.php section and I got error message. I just copied directly from tutorial. Here’s error message I got:

    1>main.obj : error LNK2001: unresolved external symbol «public: static class sf::Color const sf::Color::Green» (?Green@Color@sf@@2V12@B)
    1>main.obj : error LNK2001: unresolved external symbol «public: static class sf::RenderStates const sf::RenderStates::Default» (?Default@RenderStates@sf@@2V12@B)
     

     

        I just zipped this whole project and ran the same project on my friend’s computer. and it works well without any error message.

        Does anybody know what I did wrong?


    Logged


    If the program works on someone else’s computer but not yours, it’s not the program that has the error; it must be with your setup.
    I’d suggest making sure you’re linking SFML correctly (includes, libs, DLLs), and make sure you use the correct version for your version of Visual Studio. That said, which version are you using?


    Logged


    well… I use Visual Studio 2010, and I downloaded SFML 2.1 for Visual C++ 10 (2010) at this URL : http://www.sfml-dev.org/download/sfml/2.1/.

    Before I post this question, I already download and setup again with that file, but the same error occurred.


    Logged


    Are you trying to link statically? If you are statically linking, you should be using the SFML libraries with the suffix -s and if you definitely not linking statically, you should be using the libraries without that suffix.


    Logged


    OH!!!!!! Thank you T.T

    Now It works. I just linked libraries statically ;;


    Logged


    • Home
    • Forum
    • Qt
    • Qt Programming
    • error LNK2001: unresolved external symbol «public: static struct QMetaObject

    1. 11th August 2012, 19:17


      #1

      Unhappy error LNK2001: unresolved external symbol «public: static struct QMetaObject

      Hi,

      I am trying to link an application using QGIS API. Everything works on Linux but in Windows (QT 4.8.1 + Visual Studio Express 2010) I get:

      1. 1>maptoolselect.obj : error LNK2001: unresolved external symbol "public: static struct QMetaObject const QgsVectorLayer::staticMetaObject" (?staticMetaObject@QgsVectorLayer@@2UQMetaObject@@B)

      2. 1>mapwidget.obj : error LNK2001: unresolved external symbol "public: static struct QMetaObject const QgsVectorLayer::staticMetaObject" (?staticMetaObject@QgsVectorLayer@@2UQMetaObject@@B)

      3. 1>mapwidget.obj : error LNK2001: unresolved external symbol "public: static struct QMetaObject const QgsRasterLayer::staticMetaObject" (?staticMetaObject@QgsRasterLayer@@2UQMetaObject@@B)

      4. 1>debug\nile.exe : fatal error LNK1120: 2 unresolved externals

      To copy to clipboard, switch view to plain text mode 

      my pro file is defined as:

      1. QT += core gui sql xml

      2. TARGET = nile

      3. TEMPLATE = app

      4. unix:INCLUDEPATH += /usr/local/gis/include/qgis /usr/local/gis/include ./mapviewsrc

      5. win32:INCLUDEPATH += C:/QGIS/apps/qgis/include C:/QGIS/include ./mapviewsrc

      6. unix:LIBS += -L/usr/local/gis/lib -lgdal -lgeos -lqgis_core -lqgis_gui

      7. win32:LIBS += C:/QGIS/apps/qgis/lib/qgis_core.lib C:/QGIS/apps/qgis/lib/qgis_gui.lib C:/QGIS/lib/geos_c_i.lib C:/QGIS/lib/gdal_i.lib

      8. CONFIG += release

      9. DEFINES += QGISPLUGINDIR=$${QGISPLUGINDIR} CORE_EXPORT= GUI_EXPORT=

      To copy to clipboard, switch view to plain text mode 

      I tried to generate a Visual Studio project with

      1. qmake -tp vc

      To copy to clipboard, switch view to plain text mode 

      but I get the same error.

      Any help is much appreciated!.

      Carlos


    2. 11th August 2012, 20:22


      #2

      Default Re: error LNK2001: unresolved external symbol «public: static struct QMetaObject

      I think this error typically occurs because MOC hasn’t run to generate its moc_*.cpp files, or if it has, the .cpp files have not been compiled or the resulting .obj files have not been included in the link. Try doing a clean rebuild. Also make sure that you have declared Q_OBJECT in and classes that inherit from QObject.

      You could also look at your .vcproj file. You should see entries such as this:

      1. <FileConfiguration Name="Debug|Win32">

      2. <Tool

      3. Name="VCCustomBuildTool"

      4. Description="Moc&apos;ing $(InputFileName)..."

      5. CommandLine="&quot;$(QTDIR)binmoc.exe&quot; &quot;$(InputPath)&quot; -o &quot;.GeneratedFiles$(ConfigurationName)moc_$(InputName).cpp&quot; -D_UNICODE -DQT_CORE_LIB -DQT_GUI_LIB -DQT_LARGEFILE_SUPPORT -DQT_THREAD_SUPPORT -DSACOREQT_LIB -DUNICODE -DWIN32 -DXERCES_STATIC_LIBRARY -I&quot;$(QTDIR)include&quot; -I&quot;$(QTDIR)includeActiveQt&quot; -I&quot;$(QTDIR)includeQtCore&quot; -I&quot;$(QTDIR)includeQtGui&quot; -I&quot;.&quot; -I&quot;...Include&quot; -I&quot;.GeneratedFiles&quot; -I&quot;.GeneratedFiles$(ConfigurationName)&quot; "

      6. AdditionalDependencies="&quot;$(QTDIR)binmoc.exe&quot;;$(InputPath)"

      7. Outputs="&quot;.GeneratedFiles$(ConfigurationName)moc_$(InputName).cpp&quot;"

      8. />

      9. </FileConfiguration>

      To copy to clipboard, switch view to plain text mode 

      Last edited by d_stranz; 11th August 2012 at 20:28.

      <=== The Great Pumpkin says ===>
      Please use CODE tags when posting source code so it is more readable. Click «Go Advanced» and then the «#» icon to insert the tags. Paste your code between them.


    3. 12th August 2012, 17:27


      #3

      Default Re: error LNK2001: unresolved external symbol «public: static struct QMetaObject

      Hi,

      I added those lines to the proj file but I get the same. Here it the output:

      1. 1>------ Build started: Project: nile, Configuration: Debug Win32 ------

      2. 1> MOC mapviewsrcgendockwidget.h

      3. 1> MOC genmodels.h

      4. 1> MOC gobletrunner.h

      5. 1> MOC importraster.h

      6. 1> MOC mapviewsrckeywidget.h

      7. 1> MOC mapviewsrclyrwidget.h

      8. 1> MOC mainwidget.h

      9. 1> MOC mapviewsrcmapdialog.h

      10. 1> MOC mapviewsrcmaptoolselect.h

      11. 1> MOC mapviewsrcmapwidget.h

      12. 1> MOC mapviewsrcmapwindow.h

      13. 1> MOC practice.h

      14. 1> MOC practype.h

      15. 1> MOC mapviewsrcstatswidget.h

      16. 1> MOC strategy.h

      17. 1> UIC gobletrunner.ui

      18. 1> UIC importraster.ui

      19. 1> UIC mapviewsrckeywidget.ui

      20. 1> UIC mapviewsrclyrwidget.ui

      21. 1> UIC mainwidget.ui

      22. 1> UIC mapviewsrcmapdialog.ui

      23. 1> UIC mapviewsrcmapwidget.ui

      24. 1>mapviewsrcmapwidget.ui : warning : Z-order assignment: '' is not a valid widget.

      25. 1> UIC mapviewsrcmapwindow.ui

      26. 1> UIC practice.ui

      27. 1> UIC practype.ui

      28. 1> UIC mapviewsrcstatswidget.ui

      29. 1>mapviewsrcstatswidget.ui : warning : Z-order assignment: '' is not a valid widget.

      30. 1> UIC strategy.ui

      31. 1> RCC files.qrc

      32. 1> RCC mapviewsrcmapimages.qrc

      33. 1> genFunctions.cpp

      34. 1> gendockwidget.cpp

      35. 1> genmodels.cpp

      36. 1> gobletrunner.cpp

      37. 1> importraster.cpp

      38. 1> keywidget.cpp

      39. 1> lyrwidget.cpp

      40. 1> main.cpp

      41. 1> mainwidget.cpp

      42. 1> mapdialog.cpp

      43. 1> maptoolselect.cpp

      44. 1> mapwidget.cpp

      45. 1> mapwindow.cpp

      46. 1> practice.cpp

      47. 1> practype.cpp

      48. 1> statswidget.cpp

      49. 1> strategy.cpp

      50. 1> treeitem.cpp

      51. 1> moc_gendockwidget.cpp

      52. 1> moc_genmodels.cpp

      53. 1> Generating Code...

      54. 1> Compiling...

      55. 1> moc_gobletrunner.cpp

      56. 1> moc_importraster.cpp

      57. 1> moc_keywidget.cpp

      58. 1> moc_lyrwidget.cpp

      59. 1> moc_mainwidget.cpp

      60. 1> moc_mapdialog.cpp

      61. 1> moc_maptoolselect.cpp

      62. 1> moc_mapwidget.cpp

      63. 1> moc_mapwindow.cpp

      64. 1> moc_practice.cpp

      65. 1> moc_practype.cpp

      66. 1> moc_statswidget.cpp

      67. 1> moc_strategy.cpp

      68. 1> qrc_files.cpp

      69. 1> qrc_mapimages.cpp

      70. 1> Generating Code...

      71. 1>maptoolselect.obj : error LNK2001: unresolved external symbol "public: static struct QMetaObject const QgsVectorLayer::staticMetaObject" (?staticMetaObject@QgsVectorLayer@@2UQMetaObject@@B)

      72. 1>mapwidget.obj : error LNK2001: unresolved external symbol "public: static struct QMetaObject const QgsVectorLayer::staticMetaObject" (?staticMetaObject@QgsVectorLayer@@2UQMetaObject@@B)

      73. 1>mapwidget.obj : error LNK2001: unresolved external symbol "public: static struct QMetaObject const QgsRasterLayer::staticMetaObject" (?staticMetaObject@QgsRasterLayer@@2UQMetaObject@@B)

      74. 1>debug\nile.exe : fatal error LNK1120: 2 unresolved externals

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

      To copy to clipboard, switch view to plain text mode 

      I can see that moc is generating the moc_ and the files are compiled but still the linking fails.

      This is the first time I use a .proj files. I usually use qmake and then nmake but I get the same error in the linking

      Thanks.


    4. 12th August 2012, 18:20


      #4

      Default Re: error LNK2001: unresolved external symbol «public: static struct QMetaObject

      Well, the linker is complaining about two files in particular, the ones that contain QgsVectorLayer and QgsRasterLayer. I don’t see that listed in your build output, so you either forgot to include them in the project or you are not linking to the object files or library that contains them.

      <=== The Great Pumpkin says ===>
      Please use CODE tags when posting source code so it is more readable. Click «Go Advanced» and then the «#» icon to insert the tags. Paste your code between them.


    5. 12th August 2012, 19:16


      #5

      Default Re: error LNK2001: unresolved external symbol «public: static struct QMetaObject

      Hi,

      Yes, both classes QgsVectorLayer and QgsRasterLayer are defined in external libraries

      How can I see in the project if my application is linking using:

      C:/QGIS/apps/qgis/lib/qgis_core.lib
      C:/QGIS/apps/qgis/lib/qgis_gui.lib
      C:/QGIS/lib/geos_c_i.lib
      C:/QGIS/lib/gdal_i.lib

      Many thanks,
      Carlos.


    6. 13th August 2012, 02:06


      #6

      Default Re: error LNK2001: unresolved external symbol «public: static struct QMetaObject

      If you are using Visual Studio, go to the Solution Explorer window (on the menu: View->Solution Explorer), right click on the name of your project, then select the Properties item at the bottom of the popup menu. When the Property Pages dialog appears, expand the «Linker» entry, then click the «Input» item. At the top of the properties table, you should see «Additional Dependencies». Click that, then click the «…» button that appears to the right of the second column. You will see a dialog with all of the libraries that are being linked in to your project. If the libraries you need aren’t in the list, then at the bottom of the list you can type the names of the libraries, one per line. You can type either the full name including the path (C:QGISlibgdal_i.lib) or just the name of the library file (gdal_i.lib). Click OK when you have added them all.

      If you type only the name, then you need to tell the linker where to find the library files. Go to the «General» item under «Linker». Click «Additional Library Directories» and the «…» button to the right. At the bottom of the list of directories (might be empty in your case), double-click, click the «…» button and browse to select the directory that contains the library files (C:QGISlib). Repeat for each directory. Click OK to close this dialog, click OK to close the properties dialog, and then rebuild.

      By the way, I’m using the full version of Visual Studio. I do not know if what I described in in the Express version, but I would be very surprised if it isn’t. Being able to add files and libraries to the project configuration is a pretty basic requirement.

      <=== The Great Pumpkin says ===>
      Please use CODE tags when posting source code so it is more readable. Click «Go Advanced» and then the «#» icon to insert the tags. Paste your code between them.


    7. 13th August 2012, 17:16


      #7

      Default unresolved external symbol «public: static struct QMetaObject using qobject_cast

      Hi,

      I realized that the problem arises from the use of qobject_cast in lines like:

      1. QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );

      To copy to clipboard, switch view to plain text mode 

      If I change those lines to use dynamic_cast the error disappears and the application runs properly.

      Any idea why I cannot use qobject_cast in Windows?

      Many thanks.


    8. 13th August 2012, 17:28


      #8

      Default Re: unresolved external symbol «public: static struct QMetaObject using qobject_cast

      D_stranz answer above should cover this. These linker errors occur because something is not defined:
      -meaning that a library or dll isn’t in the right spot
      -a library or dll fails to contain the same symbol (i.e. function name)
      -a .cpp file fails to contain the same symbol

      and I may be missing an instance. To fix this; you’ll need to follow his answer above and:
      -Add the correct lib file (if it exists) to the required libraries and add it’s path to the additional directories
      -Add to your PATH variable (under c/c++->debugging) the path of any .dll files you may need
      -Add the .h file to your include directory or add a path in the include directory to the .h file

      The error is not the cast itself, it’s *in* the cast. The cast is asking (implicitly) for a constructor which you seem to not have defined. It may be a standard constructor but your library isn’t linked or something. I guarantee linking the correct files into your project will fix *these* errors.


    9. 13th August 2012, 17:52


      #9

      Default Re: unresolved external symbol «public: static struct QMetaObject using qobject_cast

      Hi,

      Yes I did all that and I just did your bits.. However I get the same result with qobject_cast. Before I changed those lines to dynamic_cast I changed the .pro to release and generated the Makefile with qmake but without creating a .proj file. nmake in that instance pointed me to the lines containing qobject_cast. As I am using QGIS i don’t know if there is an issue with the QGIS API. From a set of examples in QGIS I can see that dynamic_cast is used.

      What I don’t understand is why the linker errors disappear using dynamic_cast. It might be as you said because a constructor has not been defined.

      Thanks.


    10. 13th August 2012, 17:57


      #10

      Default Re: unresolved external symbol «public: static struct QMetaObject using qobject_cast

      If I change those lines to use dynamic_cast the error disappears and the application runs properly.

      I’m betting that you aren’t getting a valid pointer to a QgsVectorLayer instance when you do this, but you’re lucky because whatever is using this pointer is probably checking for a NULL pointer before trying to dereference it.

      The reason why qobject_cast causes link errors is that, unlike dynamic_cast, it is actually checking to see that the pointer *really does* point to a QgsVectorLayer instance, and to do that it needs the Qt meta-object system to be in place and working for it.

      So, do like tescrin and I have suggested: Check the Visual Studio properties for the project and make sure your libraries *are* being linked in. Change the cast back to qobject_cast.

      <=== The Great Pumpkin says ===>
      Please use CODE tags when posting source code so it is more readable. Click «Go Advanced» and then the «#» icon to insert the tags. Paste your code between them.


    11. 13th August 2012, 18:06


      #11

      Default Re: unresolved external symbol «public: static struct QMetaObject using qobject_cast

      Check the Visual Studio properties for the project and make sure your libraries *are* being linked in. Change the cast back to qobject_cast.

      I decided to not use a Visual Studio project file but I will check the code to see if I’m not getting a valid pointer.


    12. 13th August 2012, 18:15


      #12

      Default Re: unresolved external symbol «public: static struct QMetaObject using qobject_cast

      Well, then, good luck. I don’t use .pro files; I create my projects directly in Visual Studio and use only the VS project files, so I can’t help you get it configured. If qmake is generating a makefile for you, then you should see some kind of link line in there that should include all of the .lib files you listed. If they aren’t on the link line, they aren’t being linked in.

      <=== The Great Pumpkin says ===>
      Please use CODE tags when posting source code so it is more readable. Click «Go Advanced» and then the «#» icon to insert the tags. Paste your code between them.


    13. Default Re: unresolved external symbol «public: static struct QMetaObject using qobject_cast

      This is sometimes due to the fact your class (the one with the unresolved symbols) is a QObject (using macro in header and deriving from qobject), but the linker cant find the constructor.
      This happens for example if the class is a singleton (constructor is private etc). So you must either explicity have a constructor that is visible (protected or public), or make the class a non QT object (dont derive from qobject).


    14. Default Re: unresolved external symbol «public: static struct QMetaObject using qobject_cast

      The error reported in the original post had nothing to do with the linker not being able to find a constructor. The error is due to the linker being unable to find the symbols generated by the MOC compiler when it processes the class header file. This can occur for four reasons: 1) the MOC compiler didn’t run to create the *_moc.cpp file from the class header file, 2) MOC did run, but the generated cpp file wasn’t compiled, 3) MOC did run, but the class definition was missing the Q_OBJECT macro (which defines the staticMetaObject embedded class) so the code inserted by the macro wasn’t there, or 4) the object code compiled from the cpp file wasn’t linked into the executable.

      In the linux world, there is another possibility: the object files / libraries were not linked in the correct order. Object files must be presented to the gcc / g++ linker so any object file that is dependent on another object file (.o or .lib) must appear -before- that .o or .lib in the link command. Otherwise, dependencies discovered by the linker -after- the file that defines them has been processed will remain unresolved.

      The MSVC linker is smarter; it apparently builds a table of all references contained in the object files and can resolve references anywhere they occur when processing the link command.

      This happens for example if the class is a singleton

      It does not matter if an instance of a class is declared as a singleton, as a static instance at global or file scope, on the heap, or on the stack; the compiler will generate a reference to it which the linker must resolve. If your code tries to instantiate a class with a private or protected constructor under circumstances where that constructor is inaccessible, that will generate a compile-time error, not a link error.

      <=== The Great Pumpkin says ===>
      Please use CODE tags when posting source code so it is more readable. Click «Go Advanced» and then the «#» icon to insert the tags. Paste your code between them.


    Similar Threads

    1. Replies: 4

      Last Post: 9th May 2016, 13:30

    2. Replies: 0

      Last Post: 16th May 2012, 19:16

    3. Replies: 3

      Last Post: 17th March 2012, 10:31

    4. Replies: 4

      Last Post: 5th January 2011, 16:51

    5. Replies: 16

      Last Post: 23rd May 2008, 11:12

    Bookmarks

    Bookmarks


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •  
    • BB code is On
    • Smilies are On
    • [IMG] code is On
    • [VIDEO] code is On
    • HTML code is Off

    Forum Rules

    Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.

    Понравилась статья? Поделить с друзьями:
  • 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