How one can achieve late binding in C language ?
Symbol binding in C is always done at compile time, never runtime.
Library binding, or dynamic linking as it's called, is done via dlopen()
and dlsym()
on *nix, and LoadLibrary()
and GetProcAddress()
on Windows.
Late binding is not really a function of the C language itself, more something that your execution environment provides for you.
Many systems will provide deferred binding as a feature of the linker/loader and you can also use explicit calls such as dlopen
(to open a shared library) and dlsym
(to get the address of a symbol within that library so you can access it or call it).
The only semi-portable way of getting late binding with the C standard would be to use some trickery with system()
and even that is at least partially implementation-specific.
If you're not so much talking about deferred binding but instead polymorphism, you can achieve that effect with function pointers. Basically, you create a struct
which has all the data for a type along with function pointers for locating the methods for that type. Then, in the "constructor" (typically an init() function), you set the function pointers to the relevant functions for that type.
You still need to include all the code even if you don't use it but it is possible to get polymorphism that way.
Use Objective-C or Lua. Both are late-bound languages which can easily interface with C.
Of course you could implement your own name resolution scheme, but why re-invent the wheel?
Unfortunately you did not specify an OS. For Unix you can use shared libraries, or create a configurable (plugin) module structure. For details you may find the source code of an apache 1.3 webserver useful. http://httpd.apache.org/download.cgi