Windows Explicit Linking: When application does not links the external symbol by import library rather it loads the DLL at runtime. It does the same mechanism as operating system does during loading of the implicit linked DLL calls.

This is done by using Win32 APIs like :

  • LoadLibrary() - loads and links a input library form the DLL path, or current path,
  • GetProcAddress() - finds the symbol/function address by its name for a loaded DLL
  • FreeLibrary() - unloads the loaded DLL instance
/*Example of Explicit Call*/
typedef (add_proc)(int a, int b);
int main(int argc, char *argv[])
{
  add_proc *add;
  HANDLE h_dll;
  int a = 1, b = 2, c;
  h_dll = LoadLibrary("math.dll");/*Explicit Load*/
  if(h_dll)
  {
    add = GetProcAddress(h_dll, "add");
    if(add)
    {
      c = add(a, b); /*Explicit Call*/
    }
    else
    {
      printf("add() not found in math.dll");
    }
    FreeLibrary(h_dll);
  }
  else
  {
    printf("Unable to load math.dll");
    exit(-1);
  }
}

Linux Explicit Linking:
Let us consider once again math.c file for explicit linking. The steps for creating a shared library are same as that of implicit linking.
First we compile it with position independent flag on(-fPIC). This is needed for dynamic/static linking.
$cc -fPIC -c math.c

Now make a shared library with the object file.
$cc -shared libmath.so math.o

To use this shared library in a application we need to load the library then find the function pointer address, invoke the function, and at last unload the library.
Linux provides some dynamic link library APIs to achieve this. Her are some useful frequently use APIs:

  • dlopen() - loads a dynamic link binary
  • dlsym() - returns the function pointer if found the function entry
  • dlclose() - unloads the dynamic link binary
Sample code:
#include<dlfcn.h>
typedef int (add_func) (int a, int b);

void *lib_handle = NULL;
add_func * add;
int main (int argc, char *argv[])
{
  lib_handle = (void *)dlopen("libmath.so", RTLD_LAZY); 
  if(lib_handle) 
  { 
    add = dlsym(lib_handle, "add");
    if(lib_func)
    {
      printf("1 + 2 = %d", add(1, 2));
    }
    else
    {
      printf("Function entry not found in DLL");
    }
    dlclose(lib_handle);
  }
  else
  {
    printf("Unable to open DLL");
  }
}

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

Libraries, static linking, dynamic linking methods, implicit dynamic linking, explicit dynamic linking, access C from VB, JNI C from Java,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan