avatar

Andres Jaimes

Creating a simple dynamic library

By Andres Jaimes

- 2 minutes read - 219 words

This article describes how to create a simple shared library using C++. A shared library is a collection of object files that are linked with and loaded into a target application at runtime. The resulting executable contains only the object code that is needed to load the shared library, for this reason, the library has to be distributed with the executable.

Shared library

Let’s start by creating a simple sum.c program using C.

int sum(int a, int b) {
    return a + b;
}

We can compile it with the following command:

cc -dynamiclib -o libsum.dylib sum.c

Note the use of the -dynamiclib parameter. It instructs the compiler to create a dynamic library. gcc uses the same parameter name.

The lib part of the output filename is a standard in Unix/Linux/OSX. If we’re on Mac, we should use libsum.dylib, on Linux libsum.so and on Windows sum.dll.

Calling program

Create a program to call our dynamic library:

#include <stdio.h>
#include <dlfcn.h>

typedef int (*sumfunc)(int, int);

int main() {
  void* handle = dlopen("./libsum.dylib", RTLD_LAZY);
  if (handle != NULL) {
    sumfunc sum = (sumfunc) dlsym(handle, "sum");
    if (sum != NULL) {
      int result = sum(2, 3);
      printf("the sum is: %d", result);
    }
    dlclose(handle);
  }
  return 0;
}

Compile it using the following command:

cc -o main main.c -L. -lsum

and run it:

./main