Jun 14, 2015

Creating C/C++ Shared and Static Library

If you work with C/C++, soon or later will need create or simply understand better how a library works, here you can see how generate a shared/dynamic and static linked library using the Linux C/C++ GNU compiler.

Let's create a library with the Sum(int x,int y) method, that takes two numbers as input and returns the sum of them. Start creating the header file named "sumlib.h":

int Sum(int x,int y);

And the implementation file named "sumlib.cpp":

#include "sumlib.h"

int Sum(int x,int y)
 return x+y;

Now compile the library:

g++ -c -fPIC sumlib.cpp

Generate the shared version (libsumlib.so):

g++ -shared -o lib/libsumlib.so sumlib.o

And the static (libsumlib.a):

ar rvs lib/static/libsumlib.a sumlib.o

Done! now let's do an application that uses it. Create a "main.cpp":

#include <iostream>
#include <sumlib.h>

using namespace std;

int main(void)
 cout <<  Sum(1,2) << endl;

 return 0;

And compile:

g++ main.cpp -Isumlib/include -Lsumlib/lib/static -lsumlib

Remember, the -I is the include directory, must point to the "sumlib.h" folder, the -L is the library path, must point to the "libsumlib.so" or "libsumlib.a" folder. The -l is the library file used, this will find for anything that starts always with "lib" then the parameter value "sumlib" followed by .so for shared or .a for static version, in this case will load the "libsumlib.a" version.

What's the difference between the shared and static library versions? look here!
Can I use the library without the header file, just with the .so or .a file? yes you can, look here!

You can download this example with scripts ready to compile the main file and library here.

About the versions
  • Linux Ubuntu 14.04.2 LTS
  • G++ 4.8.2

0 comentários :

Post a Comment