C++技巧(靜/動態(tài)鏈接庫使用總結(jié))

字號:

一、靜態(tài)庫編寫
    1.首先當然是開VS然后創(chuàng)建一個靜態(tài)庫工程啦
    2.格式.一般有頭文件.h和原文件.cpp,當然你也可以寫一在一個cpp里.
    mydll.h------------------------
    extends "C"
    {
    int sum(int num1,int num2);
    int mult(int num1,int num2);
    }
    mydll.cpp--------------------
    #include "Mylib.h"
    int sum(int num1,int num2)
    {
    return num1+num2;
    }
    int mult(int num1,int num2)
    {
    return num1*num2;
    }
    3.編譯得到lib,然后拿埋mydll.h就可以使用了
    二、動態(tài)庫編寫
    1.首先創(chuàng)建一個動態(tài)工程.
    2.格式.
    mydll.h------------------------
    #ifdef DLL_API
    #else
    #define DLL_API extern "C" _declspec(dllimport)
    #endif
    DLL_API int _stdcall add(int a,int b);
    mydll.cpp--------------------
    #define DLL_API extern "C" _declspec(dllexport)
    #include "mydll.h"
    #include
    int add(int a,int b)
    {
    return a+b;
    }
    3.編譯的到lib,和dll,然后拿埋編寫的mydll.h就可以使用了.
    個人想說的話:動態(tài)庫必須要用_declspec()字樣標識,但是靜態(tài)的就不用了.extends "c" 和_stdcall都是調(diào)用方式,
    詳細看這里
    使用方法
    一、靜態(tài)庫包括.lib和.h文件,在工程中使用靜態(tài)庫分為3步:
    1、在工程中加入靜態(tài)庫,考試大提示有兩種方法:
    方法一:項目設(shè)置中引用.lib,project-setting-link-object/library modules中添加.lib;(需要在tools/options設(shè)置正確的引用路徑)
    方法二:在項目中直接加入lib,project-add to project-files,選擇正確的.lib。
    方法三: #pragma comment(lib, "##/##/mine.lib")
    2、在工程中包括.h文件;(可能需要在tools/options設(shè)置正確的引用路徑)
    3、在工程中使用靜態(tài)庫中的函數(shù);
    二、 動態(tài)鏈接庫一般包括.lib(導(dǎo)出函數(shù)),.h,.dll,使用動態(tài)庫有兩種情況:
    1、隱式鏈接,同使用靜態(tài)庫相似,分為三步:引用.lib,包含頭文件,使用導(dǎo)出函數(shù);
    2、動態(tài)加載,直接使用LoadLibrary() FreeLibrary( ) GetProcAddress() 加載所需的動態(tài)庫,然后指定所需的導(dǎo)出函數(shù),效率!