linux c以及vs动态链接库的编写及使用

本文介绍了如何在Linux环境下使用GCC创建C语言的动态链接库,并通过示例展示动态链接库的使用。同时,也提及了在Windows下使用Visual Studio生成DLL动态链接库的过程,并进行了简单的测试调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

linux c

1.编写pr.c

int p = 1;

void sayHello(){
    printf("pr sayHello ... \n");
}


2.编写main.c

/* 
 * File:   main.c
 * Author: Vicky.H
 *
 * Created on 2011年9月19日, 下午1:36
 */

#include <stdio.h>
#include <stdlib.h>

/*
 * 
 */
int main(int argc, char** argv) {
    sayHello();
    return (EXIT_SUCCESS);
}


3.运行

gcc -O -fpic -shared  -o dl.so pr.c  生成动态链接库

gcc -o main main.c ./dl.so 编译main.c 引用动态链接库

./main
    >>pr sayHello ...

 

当动态库的位置或名称发生改变时,程序将无法正常执行;而动态库取代静态库的好处之一则是通过更新动态库而随时升级库的内容!

 

4 .动态库的显示调用

编写如main2.c的程序

/* 
 * File:   main2.c
 * Author: Vicky.H
 *
 * Created on 2011年9月19日, 下午1:43
 * 目的:动态库的显示调用
 */

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

/*
 * 
 */
int main(int argc, char** argv) {

    void *pHandle;
    void (*pFunc)();    // 指向函数的指针
    int *p;
    
    pHandle = dlopen("./dl.so",RTLD_NOW);       // 打开动态库
    
    if (!pHandle) {
        printf("can not found dl.so\n");
        return (EXIT_SUCCESS);
    }

    pFunc = (void(*)())dlsym(pHandle,"sayHello");       // 获得动态库中的函数sayHello地址
    
    if (pFunc) {
        pFunc();
    } else {
        printf("can not found function ");
        return (EXIT_SUCCESS);
    }

    p = (int *)dlsym(pHandle,"p");      // 获得动态函数库变量p的地址
    if (p) {
        printf("p = %d\n",*p);
    } else {
        printf("can not found p !\n");
    }

    dlclose(pHandle);   // 关闭动态链接库
    
    return (EXIT_SUCCESS);
}

 

5.运行

gcc -o main2 main2.c -ldl
./main2
    >>pr sayHello ...
    >>p = 1

 

---------------------------------------------------------------------------------------------------------

 

vc

1.编写dll_dynamic.h头文件

#ifndef DLL_DYNAMIC_H
#define DLL_DYNAMIC_H
extern "C" int __declspec(dllexport)add(int x,int y);
#endif


2.编写dll_dynamic.cpp

// dll_dynamic.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include "dll_dynamic.h"

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


3.右键->生成 dll_dynamic.dll

 

4.编写dll_dynamic_test.cpp 测试动态链接库

// dll_dynamic_test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <iostream>

using namespace std;

typedef int (*lpAddFunc)(int,int);

int _tmain(int argc, _TCHAR* argv[])
{
	HINSTANCE hDll;
	lpAddFunc addFunc;
	// 错误 8 error C2664: “LoadLibraryW”: 不能将参数 1 从“const char *”转换为“LPCWSTR” 
	// 解决:工程属性->配置属性-->常规--->字符集---->使用多字节符字符集
	hDll = LoadLibrary("..\\Debug\\dll_dynamic.dll");
	if (hDll != NULL)
	{
		addFunc = (lpAddFunc) GetProcAddress(hDll,"add");
		int sum = addFunc(3,4);
		cout << "sum = " << sum << endl;
	}
	getchar();
	return 0;
}

 

5.运行 sum = 7

 

 

 


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值