Using C++ classes in .so libraries
-
09-06-2019 - |
Question
I'm trying to write a small class library for a C++ course.
I was wondering if it was possible to define a set of classes in my shared object and then using them directly in my main program that demos the library. Are there any tricks involved? I remember reading this long ago (before I started really programming) that C++ classes only worked with MFC .dlls and not plain ones, but that's just the windows side.
Solution
C++ classes work fine in .so shared libraries (they also work in non-MFC DLLs on Windows, but that's not really your question). It's actually easier than Windows, because you don't have to explicitly export any symbols from the libraries.
This document will answer most of your questions: http://people.redhat.com/drepper/dsohowto.pdf
The main things to remember are to use the -fPIC
option when compiling, and the -shared
option when linking. You can find plenty of examples on the net.
OTHER TIPS
My solution/testing
Here's my solution and it does what i expected.
Code
cat.hh :
#include <string>
class Cat
{
std::string _name;
public:
Cat(const std::string & name);
void speak();
};
cat.cpp :
#include <iostream>
#include <string>
#include "cat.hh"
using namespace std;
Cat::Cat(const string & name):_name(name){}
void Cat::speak()
{
cout << "Meow! I'm " << _name << endl;
}
main.cpp :
#include <iostream>
#include <string>
#include "cat.hh"
using std::cout;using std::endl;using std::string;
int main()
{
string name = "Felix";
cout<< "Meet my cat, " << name << "!" <<endl;
Cat kitty(name);
kitty.speak();
return 0;
}
Compilation
You compile the shared lib first:
$ g++ -Wall -g -fPIC -c cat.cpp
$ g++ -shared -Wl,-soname,libcat.so.1 -o libcat.so.1 cat.o
Then compile the main executable or C++ program using the classes in the libraries:
$ g++ -Wall -g -c main.cpp
$ g++ -Wall -Wl,-rpath,. -o main main.o libcat.so.1 # -rpath linker option prevents the need to use LD_LIBRARY_PATH when testing
$ ./main
Meet my cat, Felix!
Meow! I'm Felix
$
As I understand it, this is fine so long as you are linking .so files which were all compiled using the same compiler. Different compilers mangle the symbols in different ways and will fail to link.
That is one of the advantages in using COM on Windows, it defines a standard for putting OOP objects in DLLs. I can compile a DLL using GNU g++ and link it to an EXE compiled with MSVC - or even VB!