Skip to content
Advertisement

How can I LD_PRELOAD my own compiled library?

I was wondering how this works, creating a library and preloading it so a program can use it instead of the one in the include statement.

here is what I am doing and is not working so far .

//shared.cpp
int rand(){
    return 33;
}

//prograndom.cpp
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
    srand(time(NULL));
    int i = 10;
    while(i--) printf("%dn", rand()%100);
    return 0;
}

Then in the terminal:

$ gcc -shared -fPIC shared.cpp -o libshared.so
$ gcc prograndom.cpp -o prograndom
$ export LD_PRELOAD=/home/bob/desarrollo/libshared.so

and finally

$ LD_PRELOAD=/home/bob/desarrollo/libshared.so ./prograndom

which doesnt print 33, just random numbers…

Advertisement

Answer

Your programs are C programs, but the cpp file extension implies C++, and GCC will interpret it that way.

That’s an issue because it means that your function rand (in shared.cpp) will be compiled as a C++ function, with its name mangled to include its type-signature. However, in main you #include <stdlib.h>, which has the effect of declaring:

extern "C" int rand();

and that is the rand that the linker will look for. So your PRELOAD will have no effect.

If you change the name of the file from shared.cpp to shared.c, then it will work as expected.

Other alternatives, of dubious value, are:

  • Declare rand to be extern "C" in your shared.cpp file. You can then compile it as C++.

  • Force compilation as C by using the GCC option -x c.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement