Linux Library Inroduction

節錄自 http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/

What is the static library?

Static libraries are simply a collection of ordinary object files; conventionally, static libraries end with the .a suffix. This collection is created using the ar (archiver) program, like:

ar rcs my_library.a file1.o file2.o

In theory, code in static ELF libraries that is linked into an executable should run slightly faster (by 1-5%) than a shared library or a dynamically loaded library, but in practice this rarely seems to be the case due to other confounding factors.

Once you've created a static library, you'll want to use it. You can use a static library by invoking it as part of the compilation and linking process when creating a program executable. If you're using gcc(1) to generate your executable, you can use the -l option to specify the library. Be careful about the order of the parameters when using gcc; the -l option is a linker option, and thus needs to be placed AFTER the name of the file to be compiled.

What is the shared library?

Shared libraries are libraries that are loaded by programs when they start. When a shared library is installed properly, all programs that start afterwards automatically use the new shared library.

Every shared library has a special name called the "soname". The soname has the prefix "lib", the name of the library, the phrase ".so", followed by a period and a version number that is incremented whenever the interface changes (as a special exception, the lowest-level C libraries don't start with "lib").

Every shared library also has a "real name", which is the filename containing the actual library code. The real name adds to the soname a period, a minor number, another period, and the release number.

In addition, there's the name that the compiler uses when requesting a library, (I'll call it the "linker name"), which is simply the soname without any version number.]

There is an example:
gcc -fPIC -g -c -Wall a.c
gcc -fPIC -g -c -Wall b.c
gcc -shared -Wl,-soname,libmystuff.so.1 -o libmystuff.so.1.0.1 a.o b.o -lc -o libmystuff.so.1.0.1 a.o b.o -lc

Here are a few points worth noting:
  • Don't strip the resulting library, and don't use the compiler option -fomit-frame-pointer unless you really have to. The resulting library will work, but these actions make debuggers mostly useless.
  • Use -fPIC or -fpic to generate code. Whether to use -fPIC or -fpic to generate code is target-dependent. The -fPIC choice always works, but may produce larger code than -fpic (mnenomic to remember this is that PIC is in a larger case, so it may produce larger amounts of code). Using -fpic option usually generates smaller and faster code, but will have platform-dependent limitations.
  • In some cases, the call to gcc to create the object file will also need to include the option "-Wl,-export-dynamic".

留言

這個網誌中的熱門文章

我弟家的新居感恩禮拜分享:善頌善禱

Openssl 範例程式:建立SSL連線

如何利用 Wireshark 來監聽 IEEE 802.11 的管理封包