3/100 Days of C++: Linking a Library in C++

A major project can consist of thousands of lines of code with several other libraries that are used as dependencies. The code, however, does not magically know the existence of functions or variables that are borrowed from those libraries. When we use any function from a library, the code needs to know its reference to understand how it is declared. In other words, the code wants to know what the function does and what value it returns. This process of making our code aware of these external functions is called linking.

But the question arises, why do we still need to link when we import the header file anyway? And why go through the stress of linking if we can write the function ourselves? These questions will be cleared today on this day 3 of “100 days of C++” series, where we will learn about linkers in C++ and build a small project where we will link our code to a library. So open up your IDE and let’s get started.

What is Linking?

In C++, the compiler compiles the source code by checking if the code follows the rules of programming and ultimately converts it into machine code. The resulting file is called an object. The linker is responsible for combining or linking multiple object files (created after compiling individual source files) into a single executable file.

Theoretically, one can code a function by himself/herself without using a linker. This however sounds too simplified than it actually is. In large-scale projects, the code is divided into multiple source files (each potentially part of different modules or libraries). Tracing back a particular function through all those source files will not only cost you a lot of time, but also fry your brain like a AAA game running on some basic UHD graphics.

As a beginner, I used to get confused when I saw the error “undefined reference” when I clearly imported the header file that I needed. I mean, importing the header file should tell my code where the function is right? (Python habits!) Well, a header file in C++ provides information only on the declaration of the functions and the variables, that is, “is the function a void function or does it return a value?“, or “is the variable product integer or float?” It has no idea how the function is defined. The definition of a function lies in the main file with the extension .cpp.

The linker solves this problem by ensuring that all references to functions or variables are properly resolved and that each declared symbol has a corresponding definition. Without a linker, the file would know about the existence of the symbol but not its definition.

Linker Example

Now that you understand what linker basically does, let us proceed to building a small project. In this example, we will take in the temperature input from the user and convert it into another unit, that is, if the input is in Celsius, the program will output the temperature in Kelvin and vice versa.

In the example, we will create three files namely the header file my_lib.hpp, the library my_lib.cpp and the main source file main.cpp.

We start by declaring the functions that we need in a header file my_lib.hpp.

#include<iostream>

float kelvin_to_celsius(float k);
float celsius_to_kelvin(float c);

Here, we declare the functions kelvin_to_celsius() and celsius_to_kelvin that accept float values. This is all we need in our header file. Their declaration takes place in the my_lib.cpp file that we will create next.

#include "my_lib.hpp"

float kelvin_to_celsius(float k)
{
        return k-273;
}

float celsius_to_kelvin(float c)
{
        return c+273;
}

We, first, include our header file where the functions are defined. The definitions of the functions are then defined as seen in the code. Note that this file does not contain any int main() function as this will be our library. The int main() function is mentioned in the main source file which will be our following step. But first, we will compile our library and generate the library object.

g++ -c my_lib.cpp -o my_lib.o
ar rcs libmy_lib.a my_lib.o

Here, the library is first compiled which results in the object file my_lib.o. Then, a static library libmy_lib.a is created from my_lib.o. The ar command bundles the object file into a static library.

Ultimately, we will create our main file main.cpp:

#include"my_lib.hpp"

using namespace std;

int main()
{
	float temp;
	char unit;
	cout << "Enter the temperature with unit: " << endl;
	cin >> temp >> unit;
	switch(unit)
	{
		case 'k':
			cout << "Converting kelvin to celsius: " << kelvin_to_celsius(temp) << endl;
			break;
		case 'c':
			cout << "Converting celsius to kelvin: " << celsius_to_kelvin(temp) << endl;
			break;
		default:
			cout << "Please enter a valid unit." << endl;
	}
}

This is a simple program where the temperature input is collected from the user. If the unit is in celsius, the program will output the result in kelvin and vice versa. It is now time to bring everything together. We will link our main program to the library that we created earlier:

g++ main.cpp -L. -lmy_lib -o temp_converter

There should be an executable called temp_converter existing in your workspace. Run this file and your program should accept input from the user and output the temperature in the changed unit.

Conclusion

In this blog on day 3 of 100 days of C++, we understood linkers, and it is an important concept in C++. At my work in a research institute, we are currently working on automated vehicles. As understandable, numerous codes run synchronously to successfully run the vehicle at the automated level. Many libraries are linked to the main node that makes use of the shared functions.

What’s Next?

On day 4 of the series, we will work on an example to practice more on linking libraries. As of now, you can proceed and play around with the example code that we used earlier above. If you are still reading this, it shows that you found this blog interesting and are motivated to learn more. In that case, follow me on social media where you will get access to interesting posts and funny memes on programming and machine learning at your finger tips.

Leave a Reply