How to make a C library

Misc Add comments

Suposse you want to create a library called ‘libhello’ that provides an ‘hello’ function to include in your program ‘main.c’.

Start by writing ‘hello.c’, e.g.:

void hello ();

int
main (int argc, char *argv[])
{
  hello ();
}

And the ‘main.c’,e.g.:

#include <stdio.h>

void
hello ()
{
  printf ("Hello!\n");
}

Compile ‘hello.c’ into an object with the ‘-c’ option to ‘gcc’:

$ gcc -c hello.c

Create the library using ar(1) e ranlib(1):

$ ar cru libhello.a hello.o
$ ranlib libhello.a

And finally compile your program using the new library you’ve created:

$ gcc -o hello main.c libhello.a
$ ./hello
Hello

References:

  • The Goat Book - Freely available book describing how to use GNU Autoconf, Automake, and Libtool.
  • The ar(1) e ranlib(1) manpages.

Comments are closed.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in