Search code examples
c++windowsdllextern

How to link a function declared as extern in .h file, to create a .dll file?


I want to create a dynamic library(.dll) for one of the components written in C++, used in my work. Couple of functions are declared as extern in a .h file and being refernced in the corresponding .cpp file. While linking them i'm getting Unresolved symbol error.

xxxx.obj : error LNK2019: unresolved external symbol "int __cdecl run_xxx(int,char * * const,struct st_xx *)" (?run_xxx@@YAHHQEAPEADPEAUst_xx@@@Z) referenced in function "int __cdecl start_xx(int,int,int,char * * const)" (?start_xx@@YAHHHHQEAPEAD@Z)

The usage of these functions is like, they need to be defined by any application using this library. So the definition for these functions will only be in the application using this library. Thus i could not add any other library having the definition of these APIs while linking.

How the extern APIs need to be handled while creating dll?


Solution

  • The DLL can't link to functions in the application as if the DLL and application was one big C++ program.

    A Windows DLL is more like an executable in its own right: it's not like C or C++ static library.

    The simplest approach is to let the application pass pointers to the callback/customization functions, to the DLL, in some initialization call. More high level you can pass an interface to the DLL. A third alternative is that the functions are provided by their own DLL which the application must supply.


    There is also a possible dirty low level approach based on the fact that both executables and DLLs use the Portable Executable format, so in principle an executable can export functions for consumption by a DLL, in effect acting as both executable and DLL. However it's so long ago I did things at that level that I can't guarantee that it's doable, and anyway I recommend against it.