Number Class in a Dynamically Linked Library

Learn to create a class stored in a dynamically linked library.

We'll cover the following


Rewrite program in “Number Class with Methods defined Inside it” so that the Number class is stored in a dynamically linked library.


Here is a solution to the above problem. You have to press the “Run” button to get the terminal window under the code widget. After that, you will be able to create a dynamic library using the given commands.

Create dynamic library using command-line

If you wish to build the project using the command-line, carry out the following steps:

  1. Compile the library to position independent code.

    g++ -c Number.cpp -fpic
  2. Create the dynamic library (shared object file).

    g++ Number.o -shared -o 
  3. Let’s compile the driver code.

    g++ main.cpp -o main.out -lNumber -L.
  4. At this stage, if you run the program with ./main.out, it wouldn’t be able to locate the library. The linker searches for dynamic libraries in an environment variable LD_LIBRARY_PATH. We need to add the path for the directory where the .so file is placed in this variable.

    export LD_LIBRARY_PATH=/usr/local/educative:$LD_LIBRARY_PATH
  5. Run the program.


Get hands-on with 1200+ tech skills courses.