I have a source file handleSSV.c that I would like to compile to make a custom library. How do I do that?
I'm thinking:
gcc -o handle.h handleSSV.c
and then,
#include "handle.h"
when I want to use handleSSV.c?
It varies by platform, but the header (handleSSV.h) will not be generated by the C compiler; you will create that from the information in the source. This sequence of commands is 'typical' for Unix-like platforms.
gcc -c handleSSV.c # Generates handleSSV.o
ar r libhandleSSV.a handleSSV.o # Creates static library
gcc -o ssv-prog ssv-prog.c -L . -lhandleSSV # Creates program with library
If you want to build a shared library, then you have to use something like:
gcc -fPIC -o libhandleSSV.so -shared handleSSV.c
The link line for the program doesn't change. Note that the .so suffix is widely but not universally used (.sa on older AIX; .shl on older HP-UX; .dylib on Mac OS X, etc).
The rules are similar but different in detail on Windows.
Demonstration code run on Mac OS X 10.9.2 Mavericks using GCC 4.8.2.
#ifndef HANDLER_H_INCLUDED
#define HANDLER_H_INCLUDED
extern int handler(int a, int b);
#endif /* HANDLER_H_INCLUDED */
#include "handler.h"
#include <stdio.h>
int handler(int a, int b)
{
int c = a + b;
printf("%d = %d + %d\n", c, a, b);
return c;
}
#include "handler.h"
#include <stdio.h>
int main(void)
{
int d = handler(29, 31);
printf("d = %d\n", d);
return 0;
}
$ gcc -c handler.c
$ ar r libhandler.a handler.o
ar: creating archive libhandler.a
$ gcc -o use-handler use-handler.c -L. -lhandler
$ ./use-handler
60 = 29 + 31
d = 60
$ gcc -o libhandler.dylib -shared -fPIC handler.c
$ gcc -o use-handler use-handler.c -L. -lhandler
$ otool -L use-handler
use-handler:
libhandler.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1)
/usr/gcc/v4.8.2/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
$ ./use-handler
60 = 29 + 31
d = 60
$
gcc -O3 -g -std=c11 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -Werror -c handler.c, etc.