Number Class in a Statically Linked Library

Learn to create a class stored in a static library.

We'll cover the following

Problem

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

Solution

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 static library using the given commands.

Create static library using command-line

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

  1. Compile Number.cpp to create the object file.

    g++ -c Number.cpp -o Number.o
    
  2. Group the Number.o object file in a static library lib_NumberStaticLib.a with .a extension. Now this static library is ready to use.

    ar rcs lib_NumberStaticLib.a Number.o
    
  3. Let’s compile main.cpp to create its object file.

    g++ -c main.cpp -o main.o
    
  4. In this step, we’ll link our main.o object file with our static library using the given command. This would have created the executable main.out file.

    g++ -o main.out main.o -L. -l_NumberStaticLib
    
  5. Execute it using the following command:

    ./main.out
    

Get hands-on with 1200+ tech skills courses.