Compile a shared object library that also calls a call function

I have a f2.cpp file

// f2.cpp #include <iostream> void f2() { std::cout << "It a call of f2 function" << std::endl; } 

I am using cygwin with the crosstool gcc compiler.

 g++ -fPIC -c f2.cpp g++ -shared -o libf2.so f2.o 

I have a libf2.so file. Now I want to call the f2 function in the f1 library (shared object) libf1.so.

This is f1.cpp and I want to take f1.so

 // f1.cpp #include <iostream> void f1() { std::cout << "f1 function is calling f2()..." << std::endl; f2(); } 

How should I compile f1.cpp? I don't want to use dlclose, dlerror, dlopen, dlsym ... In the end, I want to use f1.so in main.cpp as a library of shared objects too ... without using dlclose, dlerror, dlopen, dlsym. How should I compile main.cpp when I have f1.so?

 // main.cpp #include <iostream> int main() { f1(); return 0; } 
+4
source share
3 answers

declare f2 () in the header file. and compile libf1.so similar to libf2.

Now compile the main link to f1 and f2. It should look something like this g++ -lf2 -lf1 -L /path/to/libs main.o

+3
source

You can simply link them together (if f2 compiled in libf2.so , you pass -lf2 to the linker). The component will monitor the connection of calls from f1 to f2 . Naturally, at run time f1 it is expected to find f2 in the SO boot path, and the dynamic loader will load it.

Here's a more complete sample taken from the part of the Makefile that I found. Here mylib stands for your f2 , and main_linked f1 :

 mylib: mylib.c mylib.h gcc $(CFLAGS) -fpic -c mylib.c gcc -shared -o libmylib.so mylib.o main_linked: main_linked.c mylib.h mylib.c gcc $(CFLAGS) -L. -lmylib main_linked.c -o main_linked 

Note:

  • mylib compiled to shared library with -shared
  • main_linked then created with a single gcc run passing -lmylib to specify the library for the link and -L. to say where to find it (in this case, the current directory)
+2
source

Check the -L and -l flags in g ++.

+1
source

Source: https://habr.com/ru/post/1381690/


All Articles