Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Last active November 1, 2024 20:10
Show Gist options
  • Select an option

  • Save x-yuri/ded65648fb6512079a795a50625e1384 to your computer and use it in GitHub Desktop.

Select an option

Save x-yuri/ded65648fb6512079a795a50625e1384 to your computer and use it in GitHub Desktop.
Creating a shared library in C/C++

Creating a shared library in C/C++

a.c:

#include <stdio.h>
#include "a.h"

void f(void)
{
    printf("f\n");
}

a.h:

void f(void);

b.c:

#include <stdlib.h>
#include "a.h"

int main(void)
{
    f();
    return EXIT_SUCCESS;
}
# apk add gcc musl-dev
$ gcc -fPIC -c a.c -o a.o \
    -Wall -Wextra -std=c99 -pedantic -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -O3
$ gcc -shared -o liba.so a.o
$ gcc b.c -L. -la \
    -Wall -Wextra -std=c99 -pedantic -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -O3
$ LD_LIBRARY_PATH=. ./a.out
f

a.cpp:

#include <iostream>
#include "a.h"

void A::m() {
    std::cout << "hello world" << std::endl;
}

a.h:

#ifndef A_H
#define A_H

class A {
public:
    void m();
};

#endif

b.cpp:

#include "a.h"

int main() {
    A a;
    a.m();
    return 0;
}
$ g++ -fPIC -c a.cpp -o a.o
$ g++ -shared -o liba.so a.o
$ g++ b.cpp -L. -la
$ LD_LIBRARY_PATH=. ./a.out
hello world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment