您的位置:首页 > 编程语言 > C语言/C++

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

2016-04-24 18:22 495 查看
先说静态库。

比较简单。

一般是项目,静态库,工程。选静态库,空项目。预编译头去掉。

头文件定义函数:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: