Let's say I have the following program (
#define NAME "ashoka"
int main(int argc, char *argv)
printf("Hello, world! My name is %s\n", NAME);
clang -E hello.c
clang -S hello.c
clang -c hello.s
clang hello.o -lm
clang hello.o hello2.o
clang), optimizing, etc.
math.hjust defines protypes for the standard math library
libm.a(which you link with
-lm). The functions themselves live in object files archived inside
ar -tlists the object files in a library). Dynamic (or shared) libraries are not included in the output binary. Instead, the symbols your code needs are loaded at runtime.
You would simply create an header file with your
#ifndef MYLIB_H #define MYLIB_H extern int mylib_something(char *foo, int baz); #endif
and ship it with your library. Of course the developer must also link (dinamically) against your library.
The advantage of static libraries is reliability: there will be no surprises, because you already linked your code against the exact version you're sure it works with. Other cases where it may be useful is when you're using uncommon or bleeding-edge libraries and you don't want to install them as shared. This comes at the cost of increased binary size.
Shared libraries produce smaller binaries (because the library is not in the binary) with smaller RAM footprint (because the OS can load the library once and share it among many processes), but they require a bit more care to make sure you're loading exactly what you want (e.g. see DLL Hell on Windows).
As @iharob notes, their advantages don't just stop at binary size. For example, if a bug is fixed in a shared library all programs will benefit from it (as long as it doesn't break compatibility). Also, shared libraries provide abstraction between the external interface and the implementation. For example, say an OS provides a library for applications to interface to it. With updates, the OS interface changes, and the library implementation tracks those changes. If it was compiled as a static library, all programs would have to be recompiled with the new version. If it was a shared library, they wouldn't even notice it (as long as the external interface stays the same). Another example are Linux libraries that wrap system/distro-specific aspects to a common interface.