Search code examples
c++dllcmakedynamic-loading

c++ dynamically loading dll error


I am trying to generate a .dll and then with another application I check if it can be used correctly.

However, LoadLibrary gives me error, and when I check the .dll with dependency walker, it gives me this error:

"At least one module has an unresolved import due to a missing export function in an implicitly dependent module."

This happens when I try to use one object. Actually, I am totally lost and do not know how to do that. Let me explain:

  • I have some sources of codes in C++ that I can not modify. They are compiled as STATIC libraries.
  • Then, my task is, to generate a .dll, and one .h so that the clients could use the .dll.

So, the idea isn't that I need to put functions in .h, export it, and declare them in .cpp of my project that generate .dll using other codes that I can not modify?

What I have done for my very first try is:

Let say that I have:

Project 1: someApi.hpp (class SomeAPI), someApi.cpp

DLL Project: interace.h, interface.cpp, + include Project 1.

Client Project to test DLL: main.cpp, interface.h

/** interface.h **/

#include <windows.h>

#ifdef MY_DLL_lib_EXPORTS
#define DLL_API extern "C" __declspec(dllexport)
#else
#define DLL_API extern "C" __declspec(dllimport)
#endif

DLL_API int WINAPI myfirsttry();

/** interface.cpp **/

#include "interface.h"
#include "someApi.hpp"

BOOL APIENTRY DllMain(HANDLE h, DWORD r, LPVOID l) {
    switch (r) {
        case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
        break;
    }
    return true;
}

DLL_API int WINAPI myfirsttry() { 
    SomeAPI someAPI;  // When I comment this, LoadLibrary does not give error.

    return 0; 
}


/** main.cpp **/

#include <iostream>
#include <windows.h>
#include "interface.h"

int main() {
    HINSTANCE dll;
    dll = LoadLibrary(L"D:\\myLib.dll"); // Sure that route is correct as other valid dll can be loaded
    if (!dll) {
        std::cout << "NOT OK" << endl;
    }
    return 0;
}

/*******************************/
Output: NOT OK
/*******************************/

I compile my dll with cmake using add_library(${NAME} SHARED ${SOURCES} ${HEADERS})

I know that I miss lots of things here as I have told that I am lost. Could you please have a look?


Solution

  • Finally, it was because the application was loading different version of libstdc++-6 than the .dll needed. Copying that the right version of it manually in the folder of executable solved the problem. I have used dumpbin to see all dependencies.