ch2-RTLD (Run-time dynamic loading)

Chapter_2     tiff Chapter_3







CONTENTS:     test.h     test.c     app.c




Note:  Compare with the test above.




test.h


int f ();





test.c


#include "test.h"

int f()
{
return 3;
}
/*
gcc -c -fPIC test.c
gcc -shared -fPIC test.o -o libtest.so
*/











app.c     ALP, p. 48-49


#include <assert.h> // for assert()
#include <stdio.h> // printf(), fprintf(), stderr, NULL
#include <stdlib.h> // for exit(), EXIT_FAILURE, EXIT_SUCCESS
#include <dlfcn.h> // for dlopen(), dlerror(), dlsym(), dlclose()
// dlfcn.h includes bits/dlfcn.h, which defines RTLD_LAZY:
// /usr/include/x86_64-linux-gnu/bits/dlfcn.h:
// #define RTLD_LAZY 0x00001 /* Lazy function call binding. */
/*
extern void *dlopen (const char *file, int mode);
extern char *dlerror (void);
extern void *dlsym (void *handle, const char *name);
extern int dlclose (void *handle);
*/
#include "test.h" // for f()

int main() // run-time dynamic loading
{
void *handle = NULL; // initialize
int (*local_f)(void);
char *error = NULL;

handle = dlopen("libtest.so", RTLD_LAZY);
if (!handle)
{
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
local_f = (int (*)(void)) dlsym(handle, "f");
error = dlerror();
if (error != NULL)
{
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
// else
assert(local_f() == 3);
printf("f() = %d\n", local_f());
dlclose(handle);
return EXIT_SUCCESS;
}
/*
gcc -c -fPIC test.c
gcc -shared -fPIC test.o -o libtest.so

gcc -c app.c
gcc app.o -o app -ldl
// We did not link libtest.so, but libdl.so
ldd app
libdl.so...
libc...

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.
echo $LD_LIBRARY_PATH
:.

./app
f() = 3

rm *.o // clean
*/




Note:  See Dynamic_loading on Wikipedia, as well as Example_1 and Example_2 on GitHub.









Chapter_2     tiff BACK_TO_TOP Chapter_3



Comments

Popular posts from this blog

Contents