Examples of compiling and using dynamic link libraries under Ubuntu

Source: Internet
Author: User

The environment for the following instances is AMD64 + ubuntu10.10 + g++ 4.4.5 test is successful and may be a little different on other configured machines.

Dynamic libraries are used in two ways, the first is similar to the use of static libraries, another I call the real dynamic load dynamic library, mainly because this way in the process of running the program load the link library, after use in the Unload link library.first of all.      Create our Experiment program under directory/home/owner/test/:         //dll_ fun.c         #include <stdio.h>         void dll_function (const char* szstring)         {                 printf ("%s\n",  szstring);        }     compile generate dynamic link library          gcc-c-FPIC&NBSP;DLL_FUN.C//You must add the-fpic option here, or the next compilation fails          gcc-shared-fpic-o LIBDLLFUN.SO&NBSP;DLL_FUN.O//Generate dynamic link library libdllfun.so      Create call to Dynamic library method:        //main.c         void dll_function (const char* szstring);         int Main () &NBSP;&NBsp;      {                dll_function ("This is the words of the DLL function!!!!!!");                return 0;          }     compile main.c Generate executables          gcc-o main main.c-l.-ldllfun//The Dllfun library that was just generated is provided here      if executed at this time./main, The following error will appear:         cannot open Shared object file:no such file or directory      this is because the system did not find the dynamic library libdllfun.so.

The default search path for the Linux dynamic link library is/lib and/usr/lib, so when a dynamic library is created, it is generally copied to both directories, and when the program executes, a dynamic library is required and the dynamic library is not loaded into memory. The system will automatically go to the two default search paths to find the corresponding dynamic library file, and then load the file into memory, so that the program can use the functions in the dynamic library and other resources in the dynamic library. In Linux, the search path of a dynamic library can be specified in three other ways in addition to the default search path, and this is only one of them: Specify the dynamic library search path through the environment variable Ld_library_path.

When multiple dynamic-link library search paths are specified through the environment variable, the paths are separated by a colon ":". Use the following command to configure the environment mkdir/home/owner/test/lib//set this directory as the storage directory for the dynamic library mkdir/home/owner/test/libdllfun.so/home/owner/test/li       b/libdllfun.so export ld_library_path=/home/owner/test/lib All command commands after this environment variable are set, the environment variable is valid:/main The following results can be obtained. This is the words of the DLL function!!!!!!The second loading of the dynamic Library instance:       //dll_fun.c        #include < Stdio.h>        void dll_function (const char* szString)         {              printf ("%s\n",  szstring);       }     compiles the file:  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;GCC-WALL-FPIC-C&NBSP;DLL_FUN.C&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;GCC-SHARED-W1, -soname,libdllfun.so.1-o libdllfun.so.1.0 *.o      sudo mv libdllfun.so.1.0/ Usr/lib      sudo ln-sf/usr/lib/libdllfun.so.1.0/usr/lib/libdllfun.so       sudo ln-sf/usr/lib/libdllfun.so.1.0/usr/lib/libdllfun.so.1      Detailed parameters:       -wall: Contains warning information       - FPIC: required to compile the dynamic library, the output does not depend on the location of the code        -shared: compiling dynamic libraries must be options        &NBSP;-W1: Pass some parameters to the connector, the parameters passed here are "-soname", "Libdllfun.so.1"        -o: The name of the dynamic library, In this example, the final generation of the dynamic library libdllfun.so.1.0     The meaning of the two symbolic links:          First: Allow application code to compile with-dllfun syntax          Second: Allow applications to invoke dynamic libraries at run time       Below is an example of a simple dynamic call so:         add dll_fun.h:         //dll_fun.h         #ifndef _dll_fun_h_          #define  _DLL_FUN_H_          #ifdef __cplusplus        extern "C" {          #endif         void dll_function (const char * szstring);         #ifdef __cplusplus        }          #endif          #endif       Here we still use the previously generated libdllfun.so.1.0 to add a new application cprog.c        // cprog.c         #include <stdio.h>          #include <dlfcn.h>//dlopen, Dlsym, Dlerror, Dlclose's header file           #include <stdlib.h>         #include "dll_fun.h"         //This example to dynamically load dynamic libraries          int main ()         {                typedef void (*dll_function) (const char*):                void* Hhandle = null;                dll_function Fpfun = null;                 hhandle = Dlopen ("libdllfun.so", RTLD_LAZY);                if (HHandle = = NULL)                           print ("%s\n",  dlerror ());                else                {                         fpfun = (dll_function) dlsym (HHandle, "Dll_ function ");                          char* szerrinfo = Dlerror ();                         if (SzErrInfo = = NULL)                                   fpfun ("This is the words of the DLL function!!!!!! ");                          else                                  printf ("Error:load Dynamic library failed!\n");                           Dlclose (Hhandle);                 }                  Return 0;        }     compile the run:    with the following command      gcc-wall Cprog.c-ldllfun -ldl -o cprog      Introduction to     ./cprog     Methods:         Dlopen ("libdllfun.so", Rtld_lazy): Loads the dynamic library, if the load fails to return NULL, the second parameter may have:             rtld_lazy:lazy mode until the program runs to the line before attempting to load              rtld_now: Load             rtld_ now Global:make symbol LibRaries Visible        dlsym (Hhandle, "Dll_function"): Returns the address of the function, If the lookup function fails then return null     in this way do not know how to modify the dynamic link Library search path, one way is to use modified/etc/ ld.so.conf, I tried a bit, as if the effect is not very good, and to modify this file, feel is not too good, and the same trouble, I hope that the kind person can provide a better way, let me also learn, thank you:).      related Knowledge:         command LDD appname can see the dynamic libraries on which the application depends. Run the following command:            ldd cprog          may have the following results:             linux-vdso.so.1 =>  (0x00007fff831ff000)              libdllfun.so =/usr/lib/libdllfun.so (0x00007fa1798df000)              libdl.so.2 =/lib/libdl.so.2 (0x00007fa1796db000)              libc.so.6 =/lib/libc.so.6 (0x00007fa179357000)             /lib64/ Ld-linux-x86-64.so.2 (0x00007fa179afc000)          use command nm to view the output function:             nm libdllfun.so     Introduction to compiling commands:         assuming that the C file is the cprog.c,c++ call file is Cppprog.cpp, the compilation script is:         c language:             gcc-wall-i/path/to/include/headers-l/path/to/libraries Cprog.c-ldllfun-ldl-o cprog         c++ Language:             g++-Wall -i/path/to/include/headers-l/path/to/libraries Cppprog.cpp-ldllfun-ldl-o cppprog          parameter Details:             -i: Specify header file directory              -l: Specify Library directory              -ldllfun: Call Dynamic Library libdllfun.so.1.0, if you do not create the first symbolic link when you package so, this parameter causes compilation to fail    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;-LDL: Compile dynamic library must, otherwise link not to Dlopen method      c++ developing a dynamic library with class      the following files         //myclass.h          #ifndef __myclass_h__         #define __ Myclass_h__         class myclass         {        public:                 myclass ();                 //use virtual otherwise linker would try to perform static Linkage                virtual void DoSomething ();        private:                int x;        };          #endif          // myclass.cpp         #include "myclass.h"           #include <iostream>         using namespace Std;         extern "C" myclass* create_object ()          {                 return New myclass;        }          extern "C" void Destroy_object (Myclass* object)          {                 Delete object;        }          myclass:: MyClass ()         {                 x = 20;        }          void MyClass::D osomething ()          {                 cout << x << endl;        }          //classuser.cpp         #include <dlfcn.h>          #include <iostream>          #include "myclass.h"          using namespace std;          int Main (int argc, char **argv)         &nbsp {                //on Linux, use "./myclass.so"                   void* handle = Dlopen ("./myclass.so", Rtld_lazy);                  myclass* (*create) ();                 void (*destroy) (myclass*);                  create = (MyClass* (*) ()) Dlsym (Handle, " Create_object ");/div>                 destroy = (void (*) (myclass*)) Dlsym (handle, Destroy_object ");/div>                  myclass* MyClass = (MyClass*) create ();                myClass-> DoSomething ();                  destroy (MyClass);        }     compile and run          g++-fpic-shared Myclass.cpp-o myclass.so         g++ Classuser.cpp-ldl-o Classuser        ./classuser

Examples of compiling and using dynamic-link libraries under Ubuntu

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.