0

In a DLL, I would like to call a function defined outside the DLL. Alternatively, I can add the function to the DLL, but it would use variables defined outside the DLL. I've tried both approaches, but they generate the "unresolved external" linker error. The external symbols, either a function or variables, are defined in the main program using the DLL.

Is there a way to have, in a DLL, symbols that are external to the DLL?

A simple example of the problem could be as follows:

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"

void ExternalFunction();

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

extern "C" __declspec(dllexport)
LRESULT CALLBACK DummyFunction()
{
    ExternalFunction();
    return 0;
}

EDIT: There is a related problem called "circular dependencies between dlls with Visual Studio." However, this question doesn't concern the "unresolved external" linker error; the OP had apparently solved this problem. There are ten answers, varying strongly. Four answers claim no solution, two show code in other languages, two suggest solutions outside Visual Studio, one contains a sole article link, and one presents a seemingly incomplete solution. None of the answers is marked as an accepted solution. I don't see how the answers may be applied to solve my problem, unless there is no solution at all. I think my question deserves an answer.

I've now implemented the proposal of Alan Birtles. The pointer to ExternalFunction() is passed to the DLL using a new function exported from the DLL and then used in the DLL as required. It works fine. This would be a very good and unique answer.

Kalle Svensson
  • 353
  • 1
  • 10
  • 1
    It'd make more sense for the application to pass a function pointer to the dll – Alan Birtles Mar 25 '23 at 08:16
  • @Alan Birtles: It could be correct, but I don't see this solution. A DLL exports things; how can it import? Could you add some details? – Kalle Svensson Mar 25 '23 at 08:38
  • export a function from your dll that your application will call when loading the dll, pass any parameters that the dll needs from the application to that function e.g. `extern "C" __declspec(dllexport) void dll_initialise(void (*ExternalFunction)()) {}` – Alan Birtles Mar 25 '23 at 12:56
  • @Alan Birtles: Thank you, Alan. I'll give it a try. – Kalle Svensson Mar 25 '23 at 15:15
  • @Alan Birtles: I've implemented it. It's kind of tricky with the function pointers but it works now. It's definitely the best solution (used PostMessage before but its timing is unsafe). It's a pity the question is closed because it could be a good answer. – Kalle Svensson Mar 26 '23 at 06:46

0 Answers0