Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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("%d\n", 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...

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda