Windows下用Codeblocks建立一個最簡單的DLL動態鏈接庫


轉自:http://blog.csdn.net/wangwei_cq/article/details/8187576



來源:http://hi.baidu.com/hellosim/item/9ae4317168f4a74bee1e53cb

建立一個最簡單的只有一個get_id() 函數的DLL庫

 一、創建C語言動態鏈接庫

1.新建一個動態庫的工程

File - New - Project - DLL - Go

新建的工程原來的main.cpp和main.h刪除,新建兩個文件simple.h, simple.c添加進工程

注意默認是cpp文件,我們做C庫,要用C文件

 

simple.h

#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#ifdef BUILD_DLL

    #define DLL_EXPORT __declspec(dllexport)

#else

    #define DLL_EXPORT __declspec(dllimport)

#endif

int DLL_EXPORT get_id(void);
int DLL_EXPORT add(int,int);
#endif // SIMPLE_H_INCLUDED

simple.c

#include "simple.h"
int DLL_EXPORT get_id(void)
{
    return 10;
}

int DLL_EXPORT add(int x,int y)
{
    return x+y;
}

 

然后編譯,成功后在bin\Debug目錄下生成3個文件:libsimple.dll.a, simple.dll,libsimple.dll.def

 二、動態鏈接庫調用

1、隱式調用

1)建立一個test的工程File - New - Project - Console application - Go - 選擇 c刪除main.h,把庫的test.h復制到工程中,現在就有main.c 和test.h
main.c

#include <stdio.h>

#include "simple.h"

int main()

{

    printf("id = %d\n",  get_id() );
    printf("id = %d\n",  add(1,2) );
system("pause");
    return 0;

}

 


simple.h跟上面一樣
2)把dll庫添加到工程中

將剛剛生成的兩個文件libsimple.a,  libsimple.dll復制到test工程的bin\Debug目錄下

Project - Build options - 左上角默認是Debug,不選這個,選上面那個test - Linker settings - Add 選擇 bin\Debug\libsimple.dll.a - 確定,編譯成功即可。

2、顯示調用

 

1)建立一個test1的工程File - New - Project - Console application - Go - 選擇 編輯main.h,
main.c

#include <stdio.h>
#include <windows.h>
typedef int(*lpGet_id)(void); //定義函數類型

typedef int(*lpAdd)(int,int); //定義函數類型
HINSTANCE hDll; //DLL句柄
lpGet_id get_id;
lpAdd add;
int main()
{
    hDll = LoadLibrary("simple.dll"); //加載 dll
    get_id = (lpGet_id)GetProcAddress(hDll, "get_id");//通過指針獲取函數方法
    add = (lpAdd)GetProcAddress(hDll, "add");//通過指針獲取函數方法
    printf("id = %d\n",  get_id() );//調用函數
    printf("id = %d\n",  add(1,2) );//調用函數
    FreeLibrary(hDll);//釋放Dll句柄
    system("pause");
    return 0;

}


simple.h跟上面一樣
2)把dll庫添加到工程中

將剛剛生成的兩個文件libsimple.dll復制到test工程的bin\Debug目錄下

編譯成功即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM