I have a VS solution with an executable and a DLL.
In the executable (MAIN):
__declspec(dllexport) void testExe()
{
printf("Hello from EXE");
}
__declspec(dllimport) void DoStuff();
int main()
{
DoStuff();
}
while in the .dll (DLL)
__declspec(dllimport) void testExe();
__declspec(dllexport) void testDll()
{
printf("Hello from Dll");
}
__declspec(dllexport) void DoStuff()
{
testExe();
testDll();
}
I linked Dll.lib in MAIN.exe, but I still get a linking error:
error LNK2019: unresolved external symbol "__declspec(dllimport) void __cdecl testExe(void)" referenced in function "void __cdecl DoStuff(void)"
How can I achieve this?
CodePudding user response:
Don't export functions from EXEs. Export a function from the DLL that accepts a function pointer as input, then have the EXE call that function at runtime.
EXE:
__declspec(dllimport) void SetFunc(void (*)());
__declspec(dllimport) void DoStuff();
void testExe()
{
printf("Hello from EXE");
}
int main()
{
SetFunc(testExe);
DoStuff();
}
DLL:
typedef void (*lpFuncType)();
lpFuncType pExeFunc = NULL;
void testDll()
{
printf("Hello from Dll");
}
__declspec(dllexport) void SetFunc(lpFuncType func)
{
pExeFunc = func;
}
__declspec(dllexport) void DoStuff()
{
if (pExeFunc) pExeFunc();
testDll();
}
CodePudding user response:
Circular dependency is a problem here. You have to break this cycle or you will have complex and fragile build process to create this cycle.
One way to break this cycle is Remy Lebeau answer.
Other way is to introduce another dll which will contain testExe()
and this dll will be linked to executable and your initial dll, which contains testDll()
. Advantage is you do not have to change code at all, just split executable to executable and extra dll.