Explicit invocation and implicit invocation of dynamic link libraries (. so) under Linux

Source: Internet
Author: User
Tags function prototype

Before entering the subject, take a look at the two-point preparatory knowledge.

The difference between an explicit call and an implicit call

We know that the difference between a dynamic library and a static library is that the static library is loaded into the executable when it is compiled, and the dynamic library is loaded when the program is run, so the volume of the program using the dynamic library is smaller than the volume of the Static library, and the program that uses the dynamic library must depend on the dynamic library file used (. So files, and when a program that uses a static library is compiled, it is no longer necessary to rely on a static library file (. a file).

The call of the dynamic library is divided into two ways: display and implicit, the difference is as follows.

1. Implicit invocation requires the caller to write less code, which is called as direct as the function under the current project, whereas an explicit call requires the programmer to indicate the name of the dynamic library to be loaded and the name of the function to invoke when called.

2, implicit call by the system loading complete, transparent to the programmer, the explicit call by the programmer when needed to use their own load, no longer in use, they are responsible for unloading.

        3, due to type The call is loaded and unloaded by the programmer, like dynamically requesting memory space, applying when needed, releasing, so

        4, when dynamic link library only provides function interface, call method is specified by the parameters of the Dlsym function, and when using an implicit call, the caller inevitably adds a header file in the Dynamic Library, and g++ compiles with the parameter-I to indicate the containing requires Note that when an interface function in a dynamic-link library Class inside, even if you use explicit invoke the way , the caller must also include the corresponding header file in the dynamic library ( see five, show call dynamic Link class member function in ).

5, explicit call more flexible, can simulate polymorphic effects (see later).


Ii. the role of extern "C"

In a C + + program (or library, destination file), all non-static (non-static) functions appear as "symbol" in the binary file. These symbols are unique strings that differentiate functions in programs, libraries, and destination files. In C, the symbol name is the function name, which is exactly the same. C + + allows overloads (different functions have the same name but different parameters, even const overloads), and there are many features that C does not have-such as classes, member functions, exception descriptions-that are almost impossible to use directly with the function name. To solve this problem, C + + uses the so-called name mangling. It is a mixture of function names and some information, such as the number and size of parameters, to create strange shapes, only the compiler understands the symbolic name. For example, Foo after being mangle may look like [email protected]%6^, or even "foo" is not included in the symbol name.

One of the problems is that the C + + standard does not define how names must be mangle, so each compiler does the name mangling its own way. Some compilers even replace the mangling algorithm (especially g++ 2.x and 3.x) between different versions. As I said earlier, when you display a function called a dynamic library, you need to indicate the function name of the call, even if you know exactly how your compiler is mangling, knowing that the function name being called is being converted by the C + + compiler to what form, but it may be limited to the compiler you have at hand. and cannot work under the next version of the compiler.

extern "C" is the solution to this problem. functions declared with extern "C" will use a function name, just like a C function. Therefore, only non-member functions can be declared as extern "C" and cannot be overloaded. Despite the limitations, extern "C" functions are useful because they can be dynamically loaded like C functions by Dlopen. with the extern "C" qualifier, it does not mean that C + + code is not available in the function, but instead it is still a complete C + + function that can use any C + + attribute and various types of parameters. So the extern "C" just tells the compiler to compile and link to the time of the C-way function name, the contents of the function can be C code can also be C + +.


with the above two prerequisites, the following examples illustrate two different dynamic library invocation modes. The structure of the example is organized as follows:

So1.h and so1.cc are the first files in the dynamic library that will compile links to Libso1.so;so2.h and so2.cc are the first files in the dynamic library, compiling the link to libso2.so;test.cc is a program that calls two dynamic libraries.


Third, explicit invocation

So1.h:

extern "C" void FCN ();
so1.cc:

#include <iostream> #include "so1.h" void Fcn () {std::cout << "This was FCN in So1" << Std::endl;}

SO1 's Makefile:

LIBSO1.SO:SO1.O    g++ so1.o-shared-o libso1.soso1.o:so1.cc so1.h    g++-C so1.cc-fpic-o so1.o.phony:cleanclean:< C2/>RM SO1.O libso1.so
After make, copy the generated libso1.so to the directory where test.cc is located.


So2.h:

extern "C" void FCN ();
so2.cc:
#include <iostream> #include "so2.h" void Fcn () {std::cout << "This was FCN in SO2" << Std::endl;}
SO2 's Makefile:

libso2.so:so2.og++ So2.o-shared-o libso2.soso2.o:so2.cc so2.hg++-C so2.cc-fpic-o so2.o.phony:cleanclean:rm SO2.O Libs O2.so
After make, copy the generated libso2.so to the directory where test.cc is located.


test.cc:

#include <iostream> #include <cstdlib> #include <dlfcn.h>using namespace std;int main (int argc, char * * argv) {if (argc! = 2) {cout << "argument error!" << endl;exit (1);} Pointer to functiontypedef Void (*pf_t); char *err = Null;//open the libvoid *handle = Dlopen (argv[1], rtld_now); if (!ha Ndle) {cout << "load" << argv[1] << "failed!" << dlerror () << endl;exit (1);} Clear Error Infodlerror ();p f_t pf  = (pf_t) dlsym (handle, "FCN"); err = Dlerror (); if (err) {cout << "can ' t find sy Mbol fcn! "<< Err << endl;exit (1);} Call function by POINTERPF ();d lclose (handle); return 0;}
Test's Makefile:

test:test.og++ test.o-lso1-l.-lso2-l.-ldl-wl,-rpath=. -O testtest.o:test.cc g++-C test.cc-o TEST.O

After make, the terminal operation results are as follows:

You can see here, by entering different parameters, call the different shared library of the FCN function, is a polymorphic performance, many software plug-ins are implemented.

It is important to note that to use the explicit invocation method, you must add the parameter-ldl in the link command in the header file Dlfcn.h,makefile, otherwise error.

The API descriptions provided in Dlfcn.h are as follows:

1) Dlopen

Function prototype: void *dlopen (const char *libname,int flag);

Function Description: Dlopen must be called before Dlerror,dlsym and Dlclose, indicating that the library is to be loaded into memory and ready for use. If the library you are loading depends on other libraries, you must first load the dependent libraries. Returns a null value if the Dlopen operation fails, or Dlopen returns the same handle if the library has already been loaded.

The libname in the parameter is generally the full path of the library, so that Dlopen will load the file directly, and if only the library name is specified, the Dlopen will follow the following mechanism to search:

A. Search by environment variable Ld_library_path

B. Search by/etc/ld.so.cache

C. Find the/lib and/usr/lib directories in turn.

The flag parameter indicates how the function is handled without a definition, and can use Rtld_lazy or Rtld_now. Rtld_lazy means to temporarily not deal with undefined functions, first load the library into memory, and so on the undefined function, and so on; Rtld_now means to check for undefined functions immediately, and if so, Dlopen fails.

2) Dlerror

Function prototype: char *dlerror (void);

Function Description: Dlerror can get an error message for the most recent dlopen,dlsym or dlclose operation, and return null indicates no error. Dlerror also clears the error message when it returns an error message.

3) Dlsym

Function prototype: void *dlsym (void *handle,const char *symbol);

Function Description: After Dlopen, the library is loaded into memory. Dlsym can get the position (pointer) of the specified function (symbol) in memory. If the specified function is not found, DLSYM returns a null value. But the best way to determine if a function exists is to use the Dlerror function,

4) Dlclose

Function prototype: int dlclose (void *);

Function Description: Subtract one of the loaded library handles, and if the handle is reduced to 0, the library is unloaded. If there is a destructor, the destructor is called after Dlclose.


Iv. Implicit invocation

Implicit calls do not need to include the header file Dlfcn.h, only the header files in the dynamic-link library, and the functions in the dynamic library do not need to be as complex as the display call.


V. Explicitly invoking a class member function in a dynamic link

Shows the class member functions that call the dynamic-link library, with a separate notation, but less. The recommended notation is to design a common excuse function for each class member function to be called externally, using the class's member function inside an interface function. This, of course, requires that the class be designed as a singleton pattern, because it is not possible to construct an object of a class in each interface function.


Explicit invocation and implicit invocation of dynamic link libraries (. so) under Linux

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.