Skip to content

Instantly share code, notes, and snippets.

@thatisuday
Last active February 2, 2023 06:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thatisuday/e9d402a889d26a9b88e034027b27f76b to your computer and use it in GitHub Desktop.
Save thatisuday/e9d402a889d26a9b88e034027b27f76b to your computer and use it in GitHub Desktop.
C++ Shared Library (Dynamically Linked Library) Example
#pragma once
// extern: https://docs.microsoft.com/en-us/cpp/cpp/extern-cpp?view=vs-2019
// why extern "C" : https://stackoverflow.com/a/42183390/2790983
extern "C" {
// function declaration
int add(int, int);
}
#include <iostream>
#include "shared.h"
// function definition
int add(int a, int b) {
return a + b;
}
#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;
}
# 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