How one can achieve late binding in C language ?
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.
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.
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
cppdev seems to be the one and only to hit the spot with his/her remark. Please, have a look at the definition itself. In a few words:
Late binding, or dynamic binding, is a computer programming mechanism in which the method being called upon an object is looked up by name at runtime.
All other answers just miss the main point, that is "look up by name".
The needed solution would be very similar to a lookup table of pointers to functions along with a function or two to select the right one by name (or even by signature). We call it a "hash table".
© 2022 - 2024 — McMap. All rights reserved.