C++関数動的リンクライブラリおよび静的リンク

2952 ワード

           ,          (      )     ,      (      )     。

  ( )     ,           
       :lib         ,                EXE   ,         。
       :dll         EXE ,                      EXE   ,                              ,       EXE                 DLL  。
    ,                       ,                    。
  
  ( )    VC++   DLL:
  DLL                 ,         ,VC++    DLL: MFC   、MFC  DLL MFC  DLL。DLL    (   、 )        ;DLL       DLL     ,          。
  
  ( )         :
                   “_declspec(dllexport)”。
            (.def)    ,             ,    :
  LIBRARY      
  EXPORTS      
  
  ( )DLL     :
       ,        DLL           DLL   。
       ,     API       DLL(DLL  —DLL      —DLL  )  。

                      。

   、   ----       (MFC  DLL)
  1. New--projects--MFC AppWizard(dll)--Regular DLL using shared MFC DLL //   MFC_dll
  2. def     :   (Add_new)
  3. h     :      //    ,    Add_new
  extern "C" __declspec(dllexport) int __stdcall Add_new(int a,int b);
  4. cpp     :       
  extern "C" __declspec(dllexport) int __stdcall Add_new(int a,int b)
  {
  return a+b;
  }
  5. build--set active configuration--win32 release--ok
  6.   
  7.     release    dll,lib     h      

   、   ----       ( MFC_dll.dll MFC_dll.lib        )
  //    (.h    .cpp   )
  1. new--projects--win32 console application--an empty project
  2.   h  :(test.h)
  #pragma comment(lib,"MFC_dll.lib") //     DLL    lib          
  extern "C" _declspec(dllimport) int _stdcall Add_new(int a,int b);//      
  3.   cpp  :(main.cpp)
  #include "test.h"
  int main()
  {
  cout<
  #include 
  typedef int (* lpAddFun)(int ,int);//     Add_new                      
  int main()
  {
  HINSTANCE hDll;//  
  lpAddFun addFun;//    
  hDll=LoadLibrary("dllTest.dll");//    DLL    
  if(hDll)
  {
  addFun=(lpAddFun) GetProcAddress(hDll,"Add_new");//     DLL        
  if(addFun)
  {
  int result=addFun(2,3);
  printf("%d",result); } FreeLibrary(hDll);//       DLL  
  }
  return 0;
  }

   、   ----       ( MFC DLL)
  1. new---projects---win32 dynamic-link library----an empty project(Sample)
  2.   sample.h
  #ifndef SAMPLE_H
  #define SAMPLE_H
  extern int dllGlobalVar;
  #endif
  3.    sample.cpp
  #include "sample.h"
  #include 
  int dllGlobalVar;
  bool APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
  //windows   DLL ,        ,       DOS    main  、win32    winmain    。               DllMain     。 DLL     。
  
  
        ,         
  #ifdef KSCANBAR_EXPORTS
  #define KSCANBAR_API __declspec(dllexport)
  #else
  #define KSCANBAR_API __declspec(dllimport)
  #endif
                          ,       DLL             。  DLL                  KSCANBAR_EXPORTS     。     DLL                。  ,                   KSCANBAR_API        DLL    ,   DLL                  。