A shared library is a library required by an executable to run properly. Such executables are called incomplete executables as they call routines present in the shared library code. The executables generated from the shared library are smaller in size than the ones generated from a static library
When an executable built with shared library is run, the dynamic loader
identifies the list of dependent libraries to be loaded and searches for them in the standard default locations and the locations pointed to by the environment variable LD_LIBRARY_PATH
(Linux), SHLIB_PATH
(HP-UX), LIBPATH
(AIX)
Shown below is the Employee class which we will use to generate the shared library libemployee.so
1 #ifndef _Employee_H_
2 #define _Employee_H_
3
4
5
6 #include <iostream>
7
8 class Employee
9 {
10 public:
11 Employee();
12 Employee(const std::string name, int age);
13 virtual ~Employee();
14
15
16 void setName(const std::string name);
17 void setAge(int age);
18
19
20 const char* getName() const;
21 int getAge() const;
22
23 private:
24 std::string m_name;
25 int m_age;
26 };
27
28 #endif
1 #include "Employee.h"
2
3
4 Employee::Employee()
5 {
6 }
7
8 Employee::Employee(const std::string name, int age)
9 {
10 m_name = name;
11 m_age = age;
12 }
13
14 Employee::~Employee()
15 {
16 }
17
18 void Employee::setName(const std::string name)
19 {
20 m_name = name;
21 }
22
23 void Employee::setAge(int age)
24 {
25 m_age = age;
26 }
27
28 const char* Employee::getName() const
29 {
30 return m_name.c_str();
31 }
32
33 int Employee::getAge() const
34 {
35 return m_age;
36 }
Compiling the Employee source files to object files
g++ -Wall -c -fPIC -O -I. -o Employee.o Employee.cpp
Linking the object files to generate the shared library libemployee.so
gcc -o libemployee.so Employee.o -shared -fPIC -Wl,-rpath,. -L. -lstdc++
Read more ...