Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!