Introduction
According to Matt Davies Stockton, libraries are indispensable tools for developers. They are pre-compiled code that offers generic functionality like binary trees or linked lists or other specific functionality that may be used in different projects by you or others. Let’s check out how you can build a Linux shared library.
Start a new project – Open the terminal by pressing the Windows or Command key and typing in “terminal”. Press Enter to open the terminal and create a new directory for your project on the Desktop. To do that type “mkdir ~/Desktop/linux-shared-library”.
Nest, use the terminal to open your new project in VS code with the bang command shortcut “!$”. Type in “code !$” to grab the shared library portion of the above-mentioned command. Now, you should see a VS code window open up with the same directory.
Write the main program – Create a new C++ file in VS Code by typing in “code main.cpp”. Next, write the following code in your file:
#include <stdio.h>
int main(void)
{
puts(“Hello Earth!”);
return 0;
}
After that, it’s time to run the code with a GCC compiler that ships with Ubuntu. To install the compiler type in “gcc main.cpp” in the terminal. The command would generate the “a.out” file with the output “Hello Earth” when you run it on the VS code terminal.
Create a shared library – While you have successfully written your code in the previous step, it’s time to share it with the world. Type “code venus.cpp” in the VS code terminal to create a new file. Proceed to write the following code in the new file:
#include <stdio.h>
void venus(void)
{
puts(“Hello Venus!”);
}
Next, it’s time to create a header file by typing in “code venus.h”. In this file, you will define the functions the shared library would expose to third parties. To do that, write the following code in venus.h:
#ifndefvenus_h__
#definevenus_h__
extern void venus(void);
#endif
Next, compile the code into your shared library so that main.cpp can use it. Use the command “gcc -c -fpic -o venus.o venus.cpp” to compile the code in main.cpp as Position Independent code. After this “venus.o” object file is created to be used in the shared library
Integrate the library – Add the following code in “main.cpp” to integrate the library:
#include <stdio.h>
+#include “venus.h”
int main(void)
{
puts(“Hello Earth!”);
+ // Call a function in our shared library
+ venus();
// Exit with a return code 0 indicating success
return 0;
}
Finally, compile the program with the command “gcc -L./ main.cpp -lvenus”. You also need to specify where to load the shared library with the command “gcc -L./ -Wl,-rpath=./ main.cpp -lvenus”.
Conclusion
Matt Davies Stockton suggests that you draw inspiration from the above-mentioned steps to create your Linux shared library and use it in future projects as required. If you’re new to programming, creating a Linux shared library can prepare you to move on to make more complex shared libraries for MySQL servers and game engines.