c++静态链接库和动态链接库的创建和调用

先说静态库。
比较简单。
一般是项目,静态库,工程。选静态库,空项目。预编译头去掉。
头文件定义函数:
hello.h

#pragma  once 
int Add(int op1,int op2);

hello.cpp

#include "hello.h"
int Add(int op1,int op2) 
{ 
    return (op1+op2); 

另建一个工程
LibMain.cpp

#include <iostream>
#include "../Test/hello.h"
using namespace std;
#pragma comment(lib,"../Debug/Test.lib"); 
int main()
{
    printf("%d\n",Add(1,2)); 
    getchar(); 
    return(0);
}

再说动态库
动态库有两种输入方法,然后有两种输出方法,这样就有四种方法。
第一种

#pragma once 
#ifdef DLLEXPORT 
 #define DLL_API extern "C" __declspec(dllexport) 
#else 
 #define DLL_API extern "C" __declspec(dllimport) 
#endif 
DLL_API int  INC(int op1); 

第二种方法,前面不变。我们不用动态库的宏去定义,这样我们需要定义一个模式文件def。

LIBRARY   "DTest" 
EXPORTS 
INC @1 

在动态库CPP中,我们同样要定义关键字DLLEXPORTS。这个关键字是自己定义的,表达该文件是输出的。

#include "Decl.h" 
#define  DLLEXPORT 
int INC(int op1) 
{ 
 return(++op1); 
} 

然后是主函数文件的两种输入方法。
一种是头文件,路径要定义好,然后加这句话,就是动态链接相当于静态链接,要把DLL和LIB文件放到DEBUG文件里。然后模块可以删除。

#include <stdio.h> 
#include "../DTest/Decl.h" 
#pragma comment(lib,"../Debug/DTest.lib") 

还有一种是动态加载,比较繁琐。

#include <stdio.h> 
#include <windows.h> 
#include "../DTest/Decl.h" 
typedef int(*Inc)(int op1);//函数指针 
void main() 
{ 
 HINSTANCE hDll = LoadLibrary("../Debug/DTest.dll"); 
 if(hDll ==NULL) 
 { 
 printf("Load Error\n"); 
 } 
 else 
 { 
 Inc inc = (Inc)GetProcAddress(hDll,"INC"); 
 if(inc ==NULL) 
 { 
 printf("Get Error\n"); 
 } 
 else 
 { 
 printf("%d \n",inc(7)); 
 } 
 }    
 getchar(); 
} 

https://msdn.microsoft.com/zh-cn/library/ms235636.aspx

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值