Writing static library and dynamic library in C language under UNIX environment

Source: Internet
Author: User

Static libraries, dynamic libraries in UNIX terms, or archive files (archive often end with. A) and shared objects (share object often starts with lib. So end) more accurately. A static library, a dynamic library may be a term under windows, but the concept is the same. The following unified said static library and dynamic library.

Static library, is a lot of object (CC, CC in Linux is actually the software link to gcc, compiled by default. O end of the) collection. A static library is a collection of tools such as AR. At compile time, the connector will embed this part of the code into the target code.

A dynamic library is also a collection of objects (compiled into dynamic or static, just different from compilation options). At different times, at compile time, the connector does not embed this part of the code into the target code, but at run time, the code is loaded.

Thus, the general use of static libraries is generally larger than the dynamic library.

First, Static library writing

For the sake of simplicity, write a very simple example.

Hello.h

#ifndef _hello_h

#define _hello_h

void SayHello (const char* msg);

void Saygoodbye (const char* msg);

#endif

hello.c

#include "hello.h"

#include <unistd.h>

#include <string.h>

#include <stdio.h>

void SayHello (const char* msg)

{

Char wel[] = "Welcome to invoke SayHello function/n";

Char Hellomsg[bufsiz] = "Hello,";

Write (Stdout_fileno, wel, strlen (wel) +1);

strcat (hellomsg, msg);

strcat (Hellomsg, "/n");

Write (Stdout_fileno, hellomsg, strlen (hellomsg) +1);

}

void Saygoodbye (const char* msg)

{

Char wel[] = "Welcome to invoke Saygoodbye function/n";

Char Goodbyemsg[bufsiz] = "Goodbye,";

Write (Stdout_fileno, wel, strlen (wel) +1);

strcat (goodbyemsg, msg);

strcat (Goodbyemsg, "/n");

Write (Stdout_fileno, goodbyemsg, strlen (goodbyemsg) +1);

}

Compile first

[Email protected] hellolib]$ gcc-wall-c hello.c

The above command will produce the hello.o obj file. PS: Did you notice the Bogon? You can guess my network environment). -wall indicates that all compilation warnings are turned on. -C means that only compilation is not connected.

Create a static library again

[Email protected] hellolib]$ Ar-cru libhello.a hello.o

The general library file starts with Lib, and you do not have to specify the LIB prefix when linking. -cru represents the creation and replacement of the latest. Refer to the man page of AR for each parameter. For convenience, plagiarism some come, Lu Xun said take doctrine.

Option Name Example

-D Delete ar-d <archive> <objects>

-R Replace ar-r <archive> <objects>

-T Table list ar-t <archive>

-X Extract ar-x <archive> <objects>

-V Verbose ar-v

-C Create ar-c <archive>

-ru Update Object Ar-ru <archive> <objects>

At this point, the file

[[email protected] hellolib]$ ls

HELLO.C hello.h hello.o LIBHELLO.A

Test

Statictest.c

#include "hello.h"

int main (int argc, CHAR**ARGV)

{

Char msg[] = "Heidong";

SayHello (msg);

Saygoodbye (msg);

return 0;

}

Compile

[Email protected] hellolib]$ gcc-o statictest.o statictest.c-l.-lhello

-L. Indicates that the current directory is added to the library lookup directory. The System standard library directory is/usr/lib,/lib,/usr/local/lib and so on. -lhello represents the static library that connects Libhello.

Test

[Email protected] hellolib]$./STATICTEST.O

Welcome to invoke SayHello function

Hello, Heidong.

Welcome to invoke Saygoodbye function

Goodbye, Heidong

Work out.

Second, dynamic library

The code is still used above, but the options for compiling are different.

Compile

[Email protected] hellolib]$ gcc-c hello.c-fpic

[Email protected] hellolib]$ gcc-shared hello.o-o libhello.so

[Email protected] hellolib]$ gcc-o statictest.o statictest.c-l.-lhello

The-fpic represents a position independent. The abbreviation of what is specific is not known. The first line generates HELLO.O, and the second row generates the dynamic library libhello.so. The third line means what I said above.

Test

[Email protected] hellolib]$./STATICTEST.O

./statictest.o:error while loading shared libraries:libhello.so:cannot open Shared object file:no such file or Directo Ry

Gee, the error, because the libhello.so this dynamic library. There are two solutions. First, the simplest is to copy the library files to the system library directory. Root user permissions are required. The second option is to add the LD_LIBRARY_PATH environment variable to the directory where the library is located.

Test again

[Email protected] hellolib]$ export ld_library_path=./

[Email protected] hellolib]$./STATICTEST.O

Welcome to invoke SayHello function

Hello, Heidong.

Welcome to invoke Saygoodbye function

Goodbye, Heidong

Ok, okay.

You can use LDD to see which libraries depend on them.

[Email protected] hellolib]$ LDD STATICTEST.O

Linux-gate.so.1 = (0x00ddf000)

libhello.so =/libhello.so (0x00e98000)

libc.so.6 =/lib/libc.so.6 (0x00b2a000)

/lib/ld-linux.so.2 (0x00232000)

In addition to our library, there are an additional three. Libc.so.6 is a library of standard C, and Lib/ld-linux.so.2 is a dynamically connected/loaded library. As for the first, it is not clear that the Internet is said to be "linux-gate.so.1 files are not currently supported in the file system at all ; It's just a virtual DSO (Translator note virtual DSO:dynamically shared object), an address point specified in each process's storage space (process' memory) is exposed by the kernel to the shared objects "

Third, load dynamic Library at runtime

is to dynamically load dynamic libraries (like LoadLibrary under Windows) while the program is running. Four key functions:

#include <dlfcn.h>

void *dlopen (const char *filename, int flag);

const char *dlerror (void);

void *dlsym (void *handle, char *symbol);

int dlclose (void *handle);

Example:

#include <unistd.h>

#include <stdio.h>

#include <dlfcn.h>

#include <stdlib.h>

int main (int argc, CHAR**ARGV)

{

void (*sayhello) (const char*);

void (*saygoodbye) (const char*);

void* handle = NULL;

char* err;

Handle = Dlopen ("libhello.so", Rtld_lazy);

if (handle = = NULL) {

fprintf (stderr, "%s/n", Dlerror ());

Exit (-1);

}

SayHello = Dlsym (handle, "SayHello");

Err = Dlerror ();

if (err! = NULL) {

fprintf (stderr, "%s/n", err);

}else{

SayHello ("Heidong");

}

Saygoodbye = Dlsym (handle, "Saygoodbye");

Err = Dlerror ();

if (err! = NULL) {

fprintf (stderr, "%s/n", err);

}else{

Saygoodbye ("Heidong");

}

Saygoodbye = Dlsym (handle, "Sssssssaygoodbye");

Err = Dlerror ();

if (err! = NULL) {

fprintf (stderr, "%s/n", err);

}else{

Saygoodbye ("Heidong");

}

Dlclose (handle);

return 0;

}

Compile + test

[Email protected] hellolib]$ GCC-WALL-LDL dynamicload.c-o dynamicload.out

[Email protected] hellolib]$./dynamicload.out

Welcome to invoke SayHello function

Hello, Heidong.

Welcome to invoke Saygoodbye function

Goodbye, Heidong

./libhello.so:undefined Symbol:sssssssaygoodbye

[Email protected] hellolib]$

The last one is not, so the error.

Iv. some common tools

4.1 File, test files type:

[[Email protected] hellolib]$ file libhello.so

Libhello.so:ELF 32-bit LSB Shared object, Intel 80386, version 1 (SYSV), not stripped

[[Email protected] hellolib]$ file STATICTEST.O

Statictest.o:elf 32-bit LSB executable, Intel 80386, version 1 (SYSV), for Gnu/linux 2.6.9, dynamically linked (uses Shar Ed Libs), for Gnu/linux 2.6.9, not stripped

[Email protected] hellolib]$

4.2 Size tests the code of the executable file.

[email protected] hellolib]$ size STATICTEST.O

Text data BSS Dec hex filename

1167 8 1439 59f STATICTEST.O

Text is a code snippet, data is an already initialized variable, and BBS is an uninitialized variable. Dec and Hex are the decimal and hexadecimal representations of the first three, respectively.

4.3 nm See what export functions are available.

[Email protected] hellolib]$ nm libhello.so | grep "T"

00000784 T _fini

00000308 T _init

000005CB T Saygoodbye

0000046c T SayHello

4.4 Objdump similar to dumpbin under Windows.

[Email protected] hellolib]$ objdump-d libhello.so

Libhello.so:file format elf32-i386

Disassembly of section. Init:

00000308 <_init>:

308:55 Push%EBP

309:89 e5 mov%esp,%ebp

30b:83 EC $0x8,%esp Sub

Writing static library and dynamic library in C language under UNIX environment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.