Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile shared object library, which call function from so too

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;
}
like image 515
G-71 Avatar asked Nov 17 '11 12:11

G-71


People also ask

How do you call a function in a shared library?

Dynamically calling a function from a shared library can only be accomplished in Go using 'cgo' and, even then, the function pointer returned by 'dlsym' can only be called via a C bridging function as calling C function pointers directly from Go is not currently supported.

What are shared object libraries?

A shared library or shared object is a file that is intended to be shared by multiple programs. Symbols used by a program are loaded from shared libraries into memory at load time or runtime.

What is .so file in C++?

The SO file stands for Shared Library. You compile all C++ code into the.SO file when you write it in C or C++. The SO file is a shared object library that may be dynamically loaded during Android runtime.


1 Answers

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

like image 190
balki Avatar answered Sep 29 '22 15:09

balki