The Wayback Machine - https://web.archive.org/web/20240920145636/https://www.geeksforgeeks.org/how-do-i-create-a-library-in-cpp/
Open In App

How Do I Create a Library in C++?

Last Updated : 18 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Libraries are reusable code packages that can be imported into our program to use the code defined in them. In C++, libraries can be either static or dynamic. A static library is a library that is linked to the program at compile-time whereas dynamic libraries in C++ are linked at runtime but they have the advantage that they don’t get included in the executable file, which keeps the executable size low. In this article, we will learn how to create a library in C++.

Creating Static Library in C++

To create a static library in a G++ compiler, follow the below steps:

1. Create Header and Library Source Code Files

First, open your preferred text editor or IDE and start off by creating a new header file with the .h a and declaring the functions that we want to have in the library.

Header File name: math_operations.h

C++
// math_operations.h
#ifndef MATH_OPERATIONS_H
#define MATH_OPERATIONS_H

int add(int a, int b);
int subtract(int a, int b);

#endif

Now, create another file that is the source code file with .cpp extension and write the function body of the function that we declared in the header file.

Source Code File: math_operations.cpp

C++
// math_operations.cpp
#include "math_operations.h"

int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

2. Compiling the Library Source Code to Object File

Compile the source code into object files. By opening the terminal in the directory containing the source code file (math_operations.cpp) and run the following command:

g++ -c math_operations.cpp -o math_operations.o

This command generates an object file (math_operations.o) from the source code.

3. Create the Static Library

Use the ar (archive) command to bundle the object files into a static library and create a static library named libmath_operations.a from the object file math_operations.o. Run the following command:

ar rcs libmath_operations.a math_operations.o

This command creates the static library, and its is now ready to use in our program.

4. Write a Main Program that Uses the Static Library

Now, we can use the created static library in another C++ program.

main.cpp:

C++
// main.cpp
#include "math_operations.h"
#include <iostream>
using namespace std;

int main()
{
    int a = 10, b = 5;

    cout << "Addition: " << add(a, b) << endl;
    cout << "Subtraction: " << subtract(a, b) << endl;

    return 0;
}

5. Compile the Main Program Using the Static Library

Run the following command to compile the main.cpp file and link it with the static library:

g++ main.cpp -L. -lmath_operations -o main_executable

This command links the main.cpp file with your static library (-lmath_operations ) and produces an executable named main_executable.

6. Execute the Program

Run the compiled program using following command:

./main_executable

Expected Output

Addition: 15
Subtraction: 5

Creating Dynamic Library in C++

To create a dynamic library in G++ compiler, follow the below steps:

1. Create Library Source Code and Header Files

Similar to the static library, we start by creating a header file with the .h extension and a source file with the .cpp extension.

Header File: myDynamicLibrary.h

C++
// myDynamicLibrary.h

#ifndef MYDYNAMICLIBRARY_H
#define MYDYNAMICLIBRARY_H

void sayHelloDynamic();
int multiplyNumbers(int a, int b);

#endif // MYDYNAMICLIBRARY_H

Source Code File: myDynamicLibrary.cpp

C++
// myDynamicLibrary.cpp 

#include "myDynamicLibrary.h" 
#include <iostream> 
using namespace std; 

// function 1 
void sayHelloDynamic() 
{ 
    cout << "Hello from the dynamic library!\n"; 
} 
// function 2 
int multiplyNumbers(int a, int b) { return a * b; }

2. Compile the Library Source Code to an Object File

Open a terminal in the directory containing myDynamicLibrary.cpp and run the following command:

g++ -fPIC -c myDynamicLibrary.cpp -o myDynamicLibrary.o

This command generates an object file (myDynamicLibrary.o) from the source code.

3. Create the Dynamic Library

Use the g++ compiler to create a dynamic library named libmyDynamicLibrary.so from the object file myDynamicLibrary.o. Run the following command:

g++ -shared -o libmyDynamicLibrary.so myDynamicLibrary.o

This command creates the dynamic library, and it is now ready to use in our program.

4. Write a Main Program that Uses the Dynamic Library

Create a new file named mainDynamic.cpp that uses the functions from the dynamic library.

mainDynamic.cpp:

C++
// mainDynamic.cpp

#include "myDynamicLibrary.h"
using namespace std;

int main()
{
    // calling sayHelloDynamic() function
    sayHelloDynamic();

    // calling multiplyNumbers function and storing the
    // result
    int result = multiplyNumbers(5, 7);
    cout << "The result is: " << result << "\n";

    return 0;
}

5. Compile the Main Program with Dynamic Library

Compile the mainDynamic.cpp file and link it with the dynamic library. For this, run the following command:

g++ mainDynamic.cpp -L. -lmyDynamicLibrary -o myDynamicProgram

This command links the mainDynamic.cpp file with your dynamic library (-lmyDynamicLibrary) and produces an executable named myDynamicProgram.

6. Run the Program

Run the compiled program.

./myDynamicProgram

Expected Output

Hello from the dynamic library!
The result is: 35




Similar Reads

How To Create Custom Arduino Library Using C++
What is the Arduino library? Libraries are a collection of precompiled, reusable code or routines which are used by developers to reduce the development time. Arduino libraries are written in C or C++. These libraries provide us with a convenient way to share code. Arduino IDE already consists of a set of standard libraries, one can use these libra
6 min read
How to Create a Static Library in C++?
C++ allows users to add their own libraries to reduce the amount of code we have to write in our program. A static library in C++ is a library that is linked to the program at compile-time. In this article, we will learn how to create a static library in C++ from scratch. Create Static Library in C++To create a static library in G++ compiler, follo
3 min read
How to Create a Dynamic Library in C++?
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 cr
4 min read
Sort in C++ Standard Template Library (STL)
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By defa
6 min read
boost::split in C++ library
This function is similar to strtok in C. Input sequence is split into tokens, separated by separators. Separators are given by means of the predicate.Syntax: Template: split(Result, Input, Predicate Pred); Parameters: Input: A container which will be searched. Pred: A predicate to identify separators. This predicate is supposed to return true if a
2 min read
Algorithm Library Functions in C++ STL
Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Find element in rangestd :: find_if_not : Find elemen
4 min read
&lt;iterator&gt; library in C++ STL
Iterators in C++ STL | Introduction Functions Iterator operations : std :: advance : Advance iteratorstd :: distance : Return distance between iteratorsstd :: begin : Iterator to beginningstd :: end : Iterator to endstd :: prev : Get iterator to previous elementstd :: next : Get iterator to next elementstd :: next vs std :: advanceAll functions in
1 min read
Factorial of Large Number Using boost multiprecision Library
We have given a large number now we can easily find out the factorial of this large number using boost multiprecision Library. Boost library has included a new multiprecision library in the current 1.53.0 release for C++ programmers who need more precision than 64 bits. Examples: Input : 100 Output : 933262154439441526816992388562667004- 9071596826
1 min read
Generating large Fibonacci numbers using boost library
In our previous post on fibonacci series, we have seen many approaches to generate fibonacci numbers. In this approach, we shall be generating fibonacci numbers with the help of boost library. The program simply uses the "boost/multiprecision/cpp_int.hpp" boost library in which big_int is defined. The fibonacci numbers beyond the range of long long
5 min read
Check all the elements in an array are even using library in C++
We are given an array of elements and we have to check the whether each element is even or not. Examples: Input : [2, 4, 6, 8, 9] Output : All the elements are not even Input : [4, 6, 8, 12, 14] Output : All the elements are even Approach: The above problem can be solved using for loop but in C++ we have all_of() algorithm which operates on whole a
2 min read
Any datatype in C++ boost library
Any datatype is used to store any type of value in a variable. Scripting languages like JavaScript, TypeScript provides any datatype functionality. C++ also provides this functionality but only with the help of boost library. Any type of value can be assigned to a variable by just making its datatype any. Below is the required syntax for declaring
2 min read
C++ Boost String Algorithms Library
The Boost String Algorithms Library provides a generic implementation of string-related algorithms which are missing in STL. It is an extension to the algorithms library of STL and it includes trimming, case conversion, predicates and find/replace functions. All of them come in different variants so it is easier to choose the best fit for a particu
3 min read
boost::algorithm::none_of_equal() in C++ library
The none_of_equal() function in C++ boost library is found under the header 'boost/algorithm/cxx11/none_of.hpp' which tests all the elements of a sequence against the value passed in the parameter and returns true if all the elements of the sequence are not equal to the value passed. It takes a sequence and a value, and returns true if none of the
2 min read
boost::algorithm::one_of_equal() in C++ library
The one_of_equal() function in C++ boost library is found under the header 'boost/algorithm/cxx11/one_of.hpp' which tests if exactly one of the elements of a sequence against the value passed is same. It takes a sequence and a value, and returns true if the exactly one of the elements are same in the sequence to the value passed. Syntax: bool one_o
2 min read
boost::algorithm::all_of() in C++ library
The all_of() function in C++ boost library is found under the header 'boost/algorithm/cxx11/all_of.hpp' which tests all the elements of a sequence and returns true if they all share a property. It takes a sequence and a predicate, and returns true if the predicate returns true when applied to every element in the sequence. Syntax: bool all_of ( Inp
2 min read
boost::algorithm::all_of_equal() in C++ library
The all_of_equal() function in C++ boost library is found under the header 'boost/algorithm/cxx11/all_of.hpp' which tests all the elements of a sequence against the value passed in the parameter and returns true if all the elements of the sequence are same. It takes a sequence and a value, and returns true if the all the elements are same in the se
2 min read
boost::algorithm::one_of() in C++ library
The one_of() function in C++ boost library is found under the header 'boost/algorithm/cxx11/one_of.hpp' which tests the elements of a sequence and returns true if exactly one of the element share the property given. It takes a sequence and a predicate, and returns true if the predicate returns true for exactly one given element in the sequence. Syn
2 min read
boost::algorithm::is_sorted() in C++ library
The is_sorted() function in C++ boost library is found under the header 'boost/algorithm/cxx11/is_sorted.hpp' which tests if the given sequence is sorted or not according to some given criteria which is specified in the predicate. If no comparison predicate is specified, then std::less is used to see if the sequence is non-decreasing. Syntax: bool
2 min read
boost::algorithm::any_of_equal() in C++ library
The any_of_equal() function in C++ boost library is found under the header 'boost/algorithm/cxx11/any_of.hpp' which tests if any of the elements of a sequence against the value passed is same. It takes a sequence and a value, and returns true if the any of the elements are same in the sequence to the value passed. Syntax: bool any_of_equal ( InputI
2 min read
boost::algorithm::any_of() in C++ library
The any_of() function in C++ boost library is found under the header 'boost/algorithm/cxx11/any_of.hpp' which tests the elements of a sequence and returns true if they any of the elements share the property given. It takes a sequence and a predicate, and returns true if the predicate returns true for any given element in the sequence. Syntax: bool
2 min read
boost::algorithm::none_of() in C++ library
The none_of() function in C++ boost library is found under the header 'boost/algorithm/cxx11/none_of.hpp' which tests all the elements of a sequence and returns true if all of them do not share a property. It takes a sequence and a predicate, and returns true if the predicate returns false when applied to every element in the sequence. Syntax: bool
2 min read
boost::algorithm::is_partitioned() in C++ library
The is_partitioned() function in C++ boost library is found under the header 'boost/algorithm/cxx11/is_partitioned.hpp' which tests if the given sequence is partitioned according to the given predicate or not. Partition here means that all the items in the sequence that satisfy the predicate are at the beginning of the sequence.Syntax: bool is_part
2 min read
boost::algorithm::clamp() in C++ library
The clamp() function in C++ boost library is found under the header 'boost/algorithm/clamp.hpp' contains two functions for "clamping" a value between a pair of boundary values. Syntax: const T&amp; clamp ( const T&amp; val, const T&amp; lo, const T&amp; hi ) or const T&amp; clamp ( const T&amp; value, const T&amp; low, const T&amp; high, Pred p ) P
2 min read
boost::algorithm::equal() in C++ library
The equal() function in C++ boost library is found under the header 'boost/algorithm/cxx11/equal.hpp' tests to see if two sequences contain equal values. It returns a boolean value which determines if both the sequences are same or not. Syntax: bool equal ( InputIterator1 first1, InputIterator1 second1, InputIterator2 first2, InputIterator2 second2
2 min read
Difference between user defined function and library function in C/C++
Library Functions These functions are the built-in functions i.e., they are predefined in the library of the C. These are used to perform the most common operations like calculations, updation, etc. Some of the library functions are printf, scanf, sqrt, etc. To use these functions in the program the user has to use a header file associated with the
3 min read
How to Manipulate cout Object using C++ IOS Library?
C++ ios_base class has its aspects to format cout object to display different formatting features. For example, the following ios_base class can format cout object to display trailing decimal points, add + before positive numbers, and several other formatting features using class scope static constants. Class Scope Static Constants: Class scope sta
5 min read
boost::algorithm::join() in C++ Library
The library Boot.StringAlgorithms provides many functions for string manipulations. The string can be of type std::string, std::wstring, or any instance of the class template std::basic_string. boost::algorithm:join(): The join() function in the C++ boost library is included in the library "boost/algorithm/string". This function is used to join two
2 min read
C++23 Library - &lt;spanstream&gt; Header
The &lt;spanstream&gt; header is a new addition to C++ 23 Standard Libraries Collection. It provides fixed character buffer streams for input and output. It is a collection of classes and function templates that let you manipulate letter stretch as if they were streams, much like &lt;stringstream&gt; or &lt;istringstream&gt;. However, it works with
3 min read
C++ 20 - Ranges Library
C++20 introduces the header, which presents a fresh method of handling ranges comprising arrays, vectors, or alternative data structures. With this header, you can take advantage of a set of standard algorithms that support activities like data filtering, transformation, and sorting. This approach enables you to perform such operations in a condens
4 min read
File System Library in C++17
In this article, we will learn about the File System library in C++17 and with examples. &lt;filesystem&gt; header was added in C++17 and introduces a set of classes, functions, and types that simplify file system operations. In simple words, we can say that the filesystem library provides tools that help us to simplify working with files and direc
6 min read
Practice Tags :