Reputation: 11
I am trying to build, statically link and use two shared libraries one of which calls into the other. For instance lib1.so contains a function lib1_func() that calls into lib2.so's function lib2_func().
In lib1.cpp I have an extern'd function lib1_func() and a header for lib2.so's function, lib2_func().
//lib1.cpp
#include "lib2.h"
extern "C" int lib1_func()
{
return lib2_func();
}
//lib2.h
int lib2_func();
//lib2.cpp
extern "C" int lib2_func()
{
return 100;
}
My question is how do I build and link this properly? As of now I continually receive library not found errors when trying to link lib2.so to lib1.so. Is this the correct way to include lib2 in lib1?
My command line so far is to build lib2.so first then try to build lib1 and link lib2.
g++ -fpic -c lib2.cpp
g++ -shared -o lib2.so lib2.o
g++ -fpic -c lib1.cpp
g++ -shared -o lib1.so lib1.o -L. -llib2
This results in the error
ld: library not found for -llib2
I would appreciate any help on either the fault in my setup or compiler commands. Thank you all in advance.
Upvotes: 0
Views: 2070
Reputation: 229
First, you'll need to make sure your functions have the same linkage in both the declaration and definition. You can do this by using extern "C"
in both header and source files, or use it in the header file and include that in the source file. I'll do the latter here:
// lib2.h
extern "C" { int lib2_func(); }
// lib2.cpp
#include "lib2.h"
int lib2_func() { return 100; }
// lib1.h
extern "C" { int lib1_func(); }
// lib1.cpp
#include "lib1.h" // import the declaration with C linkage
#include "lib2.h"
int lib1_func() { return lib2_func(); }
// main.cpp
#include "lib1.h"
int main() { return lib1_func(); }
Link the library files with absolute names:
ls lib*.cpp | xargs g++ -c
g++ -shared -o lib2.so lib2.o
g++ -shared -o lib1.so lib1.o lib2.so
g++ -o main main.cpp lib1.so
Edit: In your question you said "I am trying to ... statically link ... two shared libraries." What I did here is not that; you will need both library files on the path to run the executable.
If you want to create a single shared library by statically linking the two libraries together then that's a different question.
ls lib*.cpp | xargs g++ -c
g++ -shared -o lib.so lib*.o
g++ -o main main.cpp lib.so
If you have two static libraries and want to make a shared library then you have to concatenate them; see Linking static libraries to other static libraries.
If you have two shared libraries and want to statically link them together, then you'll need a new approach because shared libraries do not statically link (see Static link of shared library function in gcc).
Upvotes: 1