Problem
Rewrite program in “Number Class with Methods defined Inside it” so that the Number
class is stored in a dynamically linked 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 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:
-
Compile the library to position independent code.
g++ -c Number.cpp -fpic
-
Create the dynamic library (shared object file).
g++ Number.o -shared -o libNumber.so
-
Let’s compile the driver code.
g++ main.cpp -o main.out -lNumber -L.
-
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 variableLD_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
-
Run the program.
./main.out
Get hands-on with 1400+ tech skills courses.