Skip to content

Instantly share code, notes, and snippets.

@johnbartholomew
Last active December 24, 2015 14:19
Show Gist options
  • Save johnbartholomew/6811245 to your computer and use it in GitHub Desktop.
Save johnbartholomew/6811245 to your computer and use it in GitHub Desktop.
Creating statically linkable C "packages"
#define PACKAGE_PRIVATE __attribute__((__visibility__("hidden")))
#define PACKAGE_PUBLIC __attribute__((__visibility__("default")))
/* -------- a.c -------- */
static int the_thing = 42;
PACKAGE_PRIVATE int compute_thing(void) {
return the_thing;
}
/* -------- b.c -------- */
#include <stdio.h>
PACKAGE_PRIVATE print_thing(int x) {
printf("thing: %d\n", x);
}
/* -------- api.c -------- */
PACKAGE_PUBLIC void do_thing(void) {
print_thing(compute_thing());
}
/* -------- main.c -------- */
int main(void) {
do_thing();
return 0;
}
/* -------- build.sh -------- */
#!/bin/sh
# quit on error
set -e
rm -f *.o
rm -f check
printf 'building and linking package:\n'
gcc $CFLAGS -o a.o -c a.c
gcc $CFLAGS -o b.o -c b.c
gcc $CFLAGS -o api.o -c api.c
ld -r -o package.o a.o b.o api.o
objcopy --localize-hidden package.o
printf '\npackage public (extern) symbols:\n'
nm -g package.o
printf '\nbuilding and running test program:\n'
gcc $CFLAGS -o check main.c package.o && ./check
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment