Skip to content

Instantly share code, notes, and snippets.

@stengoes
Last active July 4, 2020 17:51
Show Gist options
  • Save stengoes/e67a71b2f3cecc87e29afbd6171d0af2 to your computer and use it in GitHub Desktop.
Save stengoes/e67a71b2f3cecc87e29afbd6171d0af2 to your computer and use it in GitHub Desktop.
A minimal example for creating, compiling and using a dynamic library in C++.

A minimal example for creating, compiling and using a dynamic library in C++.

1. Create a test library

// test.h
#pragma once 
int add(int a, int b);
int mult(int a, int b);
// test.cc
int add(int a, int b){ return a+b; }
int mult(int a, int b){ return a*b; }

2. Compile the test library

$ g++ -shared -fPIC -o libtest.so test.cc

3. Use the test library in a test project

// main.cc
#include <iostream>
#include "test.h"
int main()
{
    std::cout << "1 + 3 = " << add(1, 3) << std::endl;
    std::cout << "1 * 3 = " << mult(1, 3) << std::endl;
}

4. Compile the test project

$ g++ -o main libtest.so main.cc

5. Run the test project

$ ./main
1 + 3 = 4
1 * 3 = 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment