Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda