Dynamic library Static Library of C + + basic knowledge

Source: Internet
Author: User
Tags export class naming convention

I. Static library and dynamic library

library, typically an executable binary format that is loaded by the operating system into memory execution.

We usually make some common functions into libraries for other programs to use.
Function libraries are divided into static and dynamic libraries

Static Library and dynamic library differences:

The static library is connected to the target code when the program is compiled, and the static library is no longer needed when the program runs. As a result, an executable program that uses a static library is much more space stored on disk.

Dynamic libraries are not connected to the target code when the program is compiled, but are loaded only when the program is running, so a dynamic library exists when the program is run.

Static Library and Dynamic library naming conventions:

Linux:

The naming convention for Static library filenames is prefixed with LIB, followed by a static library name with a. a extension.

The naming convention for a dynamic library file name is prefixed with Lib , but its file name extension is. so

Window

The static library is a. lib file (but the. lib file for the DLL file is different, as described below).

The dynamic library is a DLL file (Linked library).

In the Windows operating system, Visual Studio uses lib.exe as the management tool for libraries and is responsible for creating static and dynamic libraries.

Ii. creating and using a static library under Windows

There are 3 ways to create a static library:

Create a static library method

1. Create a target file named "Staticmath.obj" by using the Cl.exe compiled code (CL/C StaticMath.cpp) with the compiler option/C.

2. Then use the Library Manager Lib.exe the link code (LIB staticmath.obj) to create a static library StaticMath.lib.

To create a static library method two

When creating the Win32 console program, check the static library type;

Create a static library method three

Project "Properties", "Configuration Properties", "General", ConfigurationType selected as the static Library (. lib).

There are 2 ways to use a static library:

Using the static library method one

Add the full path to the static library in the Project's Properties, linker-> Command line, Additional Options.

Using static Library method two

Add the directory where the static library resides in the General-> Additional library directories, Linker, Project's Properties

Add the file name of the static library at the Input->additional Dependencies, Linker, Project's Properties.

Note that the file name of the static library is named Xxx.lib, and the file suffix of theimport library file for the dynamic library is the same. The content of the two is certainly completely different: the static library file certainly contains the execution code and the symbol table, while the dynamic Library's import library file contains only the address symbol table.

Third, the dynamic library call mode

There are 2 ways to call a dynamic library: implicit and explicit calls.

1. Implicit invocation

Similar to calling the static library method, in addition to the header file, you also need to:

Add the directory of the import library file (i.e.. lib file) of the dynamic library to the linker-> general-Additional library directories, Project's Properties.

In Project's Properties, Linker, Input->additional Dependencies, add the file name of the import library for the dynamic library.

The advantage of implicit invocation is that you can use either an export function or an export class.

2. Explicit invocation

The application explicitly loads the DLL at run time:

A. Call LoadLibrary (or similar functions) to load the DLL and get the module handle.

B. Call GetProcAddress to get a pointer to a function that points to each exported function that the application wants to invoke. Because the application is a function of invoking a DLL through pointers, the compiler does not generate external references, so you do not need to link to the import library.

C. Call FreeLibrary when you are finished using the DLL.

An explicit invocation has a larger problem, which is that it is difficult to use an export class.

Iv. How to find the dynamic library

In the previous section, the attentive reader will find that we are only setting up and. lib related options in VS, you can use the dynamic library. But how does the executable file find the DLL file? After all,. lib files may not need to be put together with DLL files.

In fact, the order in which the DLL is searched for dynamic Library files is this:

1. The directory that contains the EXE file,

2. The current working directory of the process,

3. Windows system directory,

4. Windows directory,

5. A list of directories listed in the PATH environment variable.

V. __declspec (dllexport) and __declspec (dllimport)

These 2 macros are unique to Windows when programming and using dynamic libraries (DLLs), and these 2 macros are not required on Linux systems.

Let's take a look at their role:

1. __declspec (dllexport) can be used to modify a function or a class to indicate that it is an export function or an export class. So, this macro is used in programming the DLL for the time of implementation.

When modifying a class, the macro is written at the back of the Class keyword, preceded by its name;

When modifying a function, write it in front of the function declaration, and because of the problem of name mangling, write the extern "C" in front of the macro. Like what:

extern " C " void Say_hello ();

2. __declspec (dllimport) is used to invoke a DLL in the program, indicating that the program to invoke a function is import from a dynamic library. So, the exact location of the macro is in the header file that describes the DLL.

3. From the above can be seen, in the implementation of the DLL, we need __declspec (dllexport) to show that these functions and classes are exported and exported classes, and in the use of the DLL program, but also with the __declspec (dllimport) To indicate that the function or class it describes is from a DLL. So wouldn't it be necessary to have 2 different but very similar header files to make declarations of these functions and classes? Can you combine these 2 functions into one? The answer is yes – use a macro to determine that macro B is __declspec (dllexport) when macro A is present, or that macro B is __declspec (dllimport). The concrete examples are as follows:

    #ifdef mydll_exports    #define mydll_decl_export __declspec (dllexport)    #else     #define mydll_decl_export __declspec (dllimport)    #endif

Therefore, in the implementation of the DLL, you need to define the mydll_exports in the preprocessor definitions, and in the DLL user there is no need to define mydll_exports.


Example:
Before creating a function library, let's prepare an example source program and compile the source program of the library into an. o file.

Whether a static library or a dynamic library, it is created by an. o file. Therefore, we must first compile the source program hello.c through GCC into a hello.o file.
The 1th step: The program--hello.h, HELLO.C and main.c are given examples;
Hello.h (see program 1) is the header file for the function library.
HELLO.C (see program 2) is the source of the function library, which contains the public function hello, which will output "Hello world!" on the screen.
MAIN.C (see program 3) is the main program for the test library file, and the public function Hello is called in the main program.
Program 1:hello.h

// prevent the header file from being repeatedly referenced #define Hello_hvoid Hello (constChar *name); #endif //  ! Hello_h

Program 2:HELLO.C

" hello.h " #include<stdio.h>void Hello (constChar *name) {    printf (  "Hello%s! " , name);}

Program 3:MAIN.C

" hello.h " int Main () {    Hello ("  everyone");     return 0 ;}

2nd step: Compile the hello.c into an. o file;
At the system prompt, type the following command to get the hello.o file.
# gcc-c HELLO.C
(Note 2: The first character "#" is the system prompt, you do not need to type, the following is the same.) )
Let's start by looking at how to create a static library and use it.

3rd step: Create a static library from the. o file;

The naming convention for Static library filenames is prefixed with LIB, followed by a static library name with a. a extension.

For example: We will create a static library named Hello, then the static library file name is LIBHELLO.A. You need to be aware of this when creating and using static libraries. Create a static library with the AR command.

At the system prompt, type the following command to create a static library file, Libmyhello.a.
# ar CR libhello.a hello.o
# ls
hello.c hello.h hello.o libhello.a main.c
4th step: Use the static library in the program;

The static library is finished, how to use its internal function? You only need to include a prototype declaration of these common functions in the source program that uses these common functions, and then specify the static library name when you generate the target file with the GCC command, and GCC will connect the public function to the destination file from the static library. AttentionGCC adds the prefix lib to the static library name and appends the extension. A to the static library file name to find the static library files.

In program 3:MAIN.C, we include the header file hello.h of the static library, and then call the public function hello directly in main program main. The following Mr. into the target program Hello, then run the Hello program to see how the results.

# gcc-o Hello main.c-l.-lmyhello
#./hello
Hello everyone!
#
Let's delete the static library file and try the common function hello whether it is really connected to the target file hello.

# RM LIBMYHELLO.A
Rm:remove regular file ' libmyhello.a '? Y
#./hello
Hello everyone!
#
The program runs as usual, and the public functions in the static library are already connected to the target file.
Let's continue to look at how to create a dynamic library in Linux. Let's start with the. o file.
5th step: Create a dynamic library file from an. o file;
The dynamic library file name specification is similar to the static library file name naming specification and is alsoAdd the prefix lib to the dynamic library name, but its file extension is. so。 For example: We will create a dynamic library named Hello, then the dynamic library file name is libhello.so. Use GCC to create a dynamic library.
At the system prompt, type the following command to get the dynamic library file libhello.so.
# Gcc-shared-fpci-o libhello.so hello.o
# ls
hello.c hello.h hello.o libhello.so main.c
The 6th step: Use the dynamic library in the program;

Using a dynamic library in a program is exactly the same as using a static library, and it is also a prototype declaration that includes these common functions in the source program that uses these common functions, and then indicates that the dynamic library name is compiled when the target file is generated with the GCC command. We run the GCC command first to generate the target file, and then run it to see the results.
# gcc-o Hello main.c-l.-lhello
#./hello
./hello:error while loading shared libraries:libhello.so:cannot open Shared object file:no such file or directory
#
Oh, that's a mistake. Quick look at the error prompt, the original is not found dynamic library file libhello.so. At run time, the program looks for the required dynamic library files in directories such as/usr/lib and/lib. If found, loads the dynamic library, otherwise it will prompt similar errors to terminate the program. We'll copy the file libhello.so to the directory/usr/lib and try again.
# MV Libhello.so/usr/lib
#./hello
Hello everyone!
#
It worked. This further illustrates that a dynamic library is required when the program is running.
We looked back and found that using a static library and using a dynamic library to compile the GCC commands used by the target program is exactly the same as when the static library and the dynamic library have the same name, which library file does the GCC command use? Hold on to the problem will be to the end of the mood, to try.
Remove all files except. C and. h and revert to the state of the example program we just finished editing.
# rm-f Hello hello.o/usr/lib/libhello.so
# ls
HELLO.C hello.h MAIN.C
#
In order to create a static library file libhello.a and a dynamic library file libhello.so.
# gcc-c HELLO.C
# ar CR libhello.a hello.o
# Gcc-shared-fpci-o libhello.so hello.o
# ls
hello.c hello.h hello.o libhello.a libhello.so main.c
#
With the last ls command above, you can find that both the static library file libhello.a and the dynamic library file libhello.so have been generated and are in the current directory. We then run the GCC command to use the function library hello to generate the target file Hello and run the program hello.
# gcc-o Hello main.c-l.-lhello
#./hello
./hello:error while loading shared libraries:libhello.so:cannot open Shared object file:no such file or directory
#
It's easy to know from the results of the program Hello RunWhen the static library and the dynamic library have the same name, the GCC command takes precedence over the dynamic library

Dynamic library Static Library of C + + basic knowledge

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.