Last active
February 2, 2023 06:36
-
-
Save thatisuday/e9d402a889d26a9b88e034027b27f76b to your computer and use it in GitHub Desktop.
C++ Shared Library (Dynamically Linked Library) Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <dlfcn.h> // https://pubs.opengroup.org/onlinepubs/7908799/xsh/dlfcn.h.html | |
#include "shared.h" | |
int main() { | |
// declaration (template) of add function | |
// function typedef: http://www.iso-9899.info/wiki/Typedef_Function_Type | |
typedef int add_t(int, int); | |
// load shared library | |
// https://pubs.opengroup.org/onlinepubs/7908799/xsh/dlopen.html | |
void *handler = dlopen("./shared.so", RTLD_LAZY); | |
// extract `add` symbol (pointer) and convert it to function pointer | |
// https://pubs.opengroup.org/onlinepubs/7908799/xsh/dlsym.html | |
add_t *add = (add_t*) dlsym( handler, "add" ); | |
// execute function | |
std::cout << (*add)(5, 2) << std::endl; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# compilation process: https://en.wikibooks.org/wiki/C%2B%2B_Programming/Programming_Languages/C%2B%2B/Code/Compiler/Linker | |
# Shared library concept: http://ehuss.com/shared/ | |
# 1. Creating the shared library | |
# Command reference: https://www.oreilly.com/library/view/c-cookbook/0596007612/ch01s05.html | |
g++ -dynamiclib -fPIC shared.cpp -o shared.so # MacOS | |
# 2. Creating the main executable file | |
g++ main.cpp -o main.exe | |
# 3. Running main executable | |
./main.exe | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment