c++ qt undefined reference to `_imp

25,571

You are compiling a static library (config += staticlib), but you are using the Q_DECL_EXPORT and Q_DECL_IMPORT macros. These macros are only used when compiling shared libraries because they imply DLL linkage (on Windows, at least).

When the app tries to compile against your static library, it attempts to link it as if it were a shared library because the headers specify DLL linkage. This breaks, and the result is a linker error.

The solution is to either build a shared library, or leave off the MYLIBSHARED_EXPORT (heck, it even says SHARED right there in the macro name!)

Share:
25,571
ahawkthomas
Author by

ahawkthomas

Updated on August 10, 2020

Comments

  • ahawkthomas
    ahawkthomas almost 4 years

    I use Qt Creator to make static C++ library and a Qt application for it.

    My lib includes MyLib_global.h:

    #if defined(MYLIB_LIBRARY)
    #  define MYLIBSHARED_EXPORT Q_DECL_EXPORT
    #else
    #  define MYLIBSHARED_EXPORT Q_DECL_IMPORT
    #endif
    

    myclass.h file:

    #include "MyLib_global.h"
    
    class MYLIBSHARED_EXPORT MyClass : public QObject
    {
        Q_OBJECT
        public:            
            enum Log
            {
                SomeValue,
                NotARealValue
            };
            MyClass(double var, Log e);
            ~MyClass();
    }
    

    And myclass.cpp file:

    #include "myclass.h"
    
    MyClass::MyClass(double var, Log e)
    {
    }
    MyClass::~MyClass()
    {
    }
    

    This block I wrote in .pro file:

    QT       -= gui
    QMAKE_CXXFLAGS += -std=c++0x
    TARGET = MyLib
    TEMPLATE = lib
    CONFIG += staticlib
    

    So I build this project using MinGW 4.7 32bit on Windows. Then I tried to include library in Qt GUI app by writing this in .pro file:

    LIBS += -Ld:/l -lAgemarkerCore
    INCLUDEPATH += d:/l/includes
    

    "l" is a folder on my "D:" drive where I placed "libMyLib.a" file. In "d:/l/includes" folder I placed all headers from MyLib project.

    Now I'm trying to create a new instance of MyClass in mainwindow.cpp file:

    #include "myclass.h"
    
    void MainWindow::someFunction()
    {
        double var = 3.5;
        MyClass::Log enum_value = MyClass::SomeValue;
        MyClass* c = new MyClass(var, enum_value);
    }
    

    And there is a problem. After I compile this GUI project using the same computer placed in the same room running on the same system, the same IDE and the same compiler I used with MyLib, I get this error:

    mainwindow.cpp:29: error: undefined reference to `_imp___ZN12MyClassC1EPdS0_S0_xiNS_3LogEi'
    

    I searched lots of forums and tried few solutions that I've found, but they didn't help. Most of this errors are concerned with GCC compiler, and simply changing the order of project files and libs helped with it, but I use MinGW with only one lib, therefore there isn't any order of libs.

    What can I do to link my library successful?