Thursday, December 23, 2010

Creating Static and Shared Libraries using GCC

There are two types of libraries in C/C++:
1. Static libraries (.a on Linux or .lib on Windows): the library of object code that is linked with becomes part of the application.
2. Shared libraries (.so on Linux or .dll on Windows): the library of object code that is linked with does not become part of the application.

In this blog, I am going to show you how to create static and shared libraries using GCC on Linux. Although the the example shown below uses C++, but the same concept is applicable to C. Simply replace g++ with gcc.

Hello.h
#include <iostream>

class Hello
{
public:
    void sayHello() const;
}; 

Hello.cc
#include "Hello.h"
using namespace std;

void Hello::sayHello() const
{
    cout << "Hello World" << endl;
} 

Main.cc
#include "Hello.h"

int main()
{   
    Hello hello;
    hello.sayHello();

    return 0;
} 

To create a static library, do the following:
1. Compile the library code.
g++ -Wall -c Hello.c
This will produce Hello.o object file.
2. Create a static library.
ar -cvq libhello.a Hello.o
This will produce libhello.a static library.
3. Compile the Main.cc code and link it against the libhello.a static library.
g++ -o Main libhello.a Main.cc
This will produce the Main executable file. When you do ldd, you won't see the dependency to libhello library since it's a static library.
ldd Main
4. Execute the Main program.
./Main

To create a shared library, do the following:
1. Compile the library code.
g++ -Wall -fPIC -c Hello.c
This will produce Hello.o object file. The -fPIC flag is required for creating a shared library. See man g++ or man gcc for more information.
2. Create a shared library.
g++ -shared -o libhello.so Hello.o
This will produce libhello.so shared library.
3. Compile the Main.cc code and link it against the libhello.so shared library.
g++ -o Main libhello.so Main.cc
This will produce the Main executable file. When you do ldd, you will see the dependency to libhello library.
ldd Main
4. Execute the Main program.
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:."
./Main

No comments:

Post a Comment