How to Create a Dynamic Library in C++?
Last Updated :
07 Jun, 2024
In C++, dynamic libraries also known as shared libraries are a powerful way to modularize your code. They allow the users to build libraries that can be loaded at runtime by multiple applications at once. This approach promotes code reuse, reduces code duplication, and simplifies maintenance of the codebase. In this article, we will learn how to create and use a dynamic library in C++.
Creating Your Own Dynamic Library in C++
To create and use a dynamic library in C++ we can follow the below steps:
Step 1: Create the Header File.
First, we will create a header file that contains the declaration of the functions that are to be implemented. We can store this header file inside the new folder named include.
Folder StructureLet's name the header file as mymath.h:
C++
// mymath.h
// header guards
#pragma once
#ifndef MYMATH_H
#define MYMATH_H
// declaring functions
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);
#endif
We can add the implementation of the function here in the header file too but it is generally preferred to keep the implementation in the separate file.
Step 2: Create the Implementation File for the Header File
After declaring the header file, we must create an implementation file that will contain the actual code for the functions declared in the header file. This file will consist code for the function definitions which will be executed when the functions are called.
Let's name this file mathlib.cpp:
C++
// including header
#include "mymath.h"
// addition implementation
int add(int a, int b) { return a + b; }
// substraction implementation
int subtract(int a, int b) { return a - b; }
// multiply implementation
int multiply(int a, int b) { return a * b; }
// divide implementation
int divide(int a, int b) { return a / b; }
Step 3: Compile the Dynamic Library using GCC
Now we will have to compile our source code into a dynamic library. One thing to note here is that the dynamic library extension in windows is (.dll) and in linux is (.so). So we need to name the files according to our system.
To compiler your source code into a dynamic library execute the following command in your terminal or cmd (make sure you have GCC installed):
g++ -fpic -shared {sourceFile} -I{headerFileDirectory} -o {libraryName.extension}
Here,
- sourceFile: Source file name with relative location
- headerFileDirectory: Relative directory to header file.
- libraryName: Desired name of the library.
- extension: Relevant extension (.so or .dll)
For Example, in this case
g++ -fpic -shared src/mymath.cpp -Iinclude -o mymath.dll
This will create the dynamic library in your specified directory.
Dynamic Library - mymath.dll is created in WindowsNote: The prefix "lib" should be added in the library name in Linux.
Step 4: Using the Dynamic Library
Now as we have created the dynamic library, we can use it in our applications. Let's create a file named main.cpp and use the functions we have defined in our dynamic library.
C++
#include "mymath.h"
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 4;
// calling functions defined inside header mymath.h
cout << "Value of add(a, b): " << add(a, b) << endl;
// calling function defined inside header mymath.h
cout << "Value of multiply(a, b): " << multiply(a, b)
<< endl;
return 0;
}
After that, execute the following command in your terminal/cmd to compile the main.cpp file:
g++ src/main.cpp -o main -Iinclude -lmymath -L../
Executable - main.exe is created in WindowsThe executable file will be created for your program (.exe for windows and .out for Linux)
To execute the above code, use the following command in your terminal:
main // for windows cmd
./main // for linux terminal
If you have trouble executing main in Linux, you may first need to tell the system about the dynamic library location. You can do it using the following:
"LD_LIBRARY_PATH="{relative path to .so file}" ./main
Output
Output of the Program using Custom Dynamic Library
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read