6

I have got a f2.cpp file

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

I use cygwin with crosstool compiler gcc.

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

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

It's a f1.cpp and i want take f1.so

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

How i must compile f1.cpp? I don't want to use dlclose, dlerror, dlopen, dlsym... Аt last i want to use f1.so in main.cpp as a shared object library too... without using use dlclose, dlerror, dlopen, dlsym. How I must compile main.cpp, when i will have a f1.so ?

// main.cpp #include <iostream> int main() { f1(); return 0; } 

3 Answers 3

3

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

You can simply link them together (if f2 is compiled into libf2.so, you pass -lf2 to the linker). The linker will take care of connecting calls from f1 to f2. Naturally, at runtime f1 will expect to find f2 in the SO load path and the dynamic loader will load it.

Here's a more complete sample, taken from a portion of a Makefile I found lying around. Here, mylib stands for your f2, and main_linked is 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:

  1. mylib is compiled into a shared library with -shared
  2. main_linked is then built with a single gcc call passing -lmylib to specify the library to link and -L. to say where to find it (in this case - current dir)

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.