Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between dynamic linking and dynamic loading

As i understand Dynamic loading means loading the library (or any other binary for that matter) into the memory during load or run-time. so in program below when dlopen() called dynamic loader will come in to picture and it will load the lib in to the memory if library is not loaded already.

Dynamic linking refers to the linking that is done during load or run-time. and it resolves external references. So in program below dlsym() function will ask for cosine function and dynamic linking will come in picture and symbols will be resolved.

int main(int argc, char **argv) {
    void *handle;
    double (*cosine)(double);
    char *error;

    handle = dlopen ("/lib/libm.so.6", RTLD_LAZY);
    if (!handle) {
        fputs (dlerror(), stderr);
        exit(1);
    }

    cosine = dlsym(handle, "cos");
    if ((error = dlerror()) != NULL)  {
        fputs(error, stderr);
        exit(1);
    }
like image 671
gauramit87 Avatar asked Jan 19 '14 09:01

gauramit87


1 Answers

Both of these terms are similar in that they refer to postponing the determination of the exact library to use until the program runs but have come to signify different aspects.

Dynamic loading occurs when a library is loaded explicitly (e.g. using dlopen()) while dynamic linking occurs when an executable that is dynamically linked gets loaded and is handled implicitly by the OS. The purposes are different.

In the first case, dynamically loading a library is used to resolve symbols from different libraries that are optional or have symbols that are mutually exclusive and which library to use can not be determined until the program is running.

For example, a program can determine based on the contents of a configuration file that it will need to interact with a particular database and need to load the database specific library only after it has read he configuration file. It would need to wait until the configuration file was parsed at run time and then call dlopen().

Alternately, a dynamically linked executable (as most executables are) will have its list of required libraries determined at link time, and those libraries will be automatically resolved before the program begins to execute at run time. This option is opposed to loading a statically linked executable and is primarily meant to conserve kernel memory and executabe size because the library only need be loaded once by the kernel for all the executables that use that library. You can run the program ldd on a dynamically linked executable to determine all of the necessary libraries.

like image 135
waTeim Avatar answered Jan 01 '23 23:01

waTeim