An Application Program Dynamically Loading and Linking the Shared Library

Shared libraries are a modern innovation that address the disadvantages of static libraries. A shared library is an object module that, at run time, can be loaded at an arbitrary memory address and linked with a program in memory. This process is known as dynamic linking, and is performed by a program called a dynamic linker.

      Shared libraries are “shared” in two different ways. First, in any given file system, there is exactly one .so file for a particular library. The code and data in this .so file are shared by all of the executable object files that reference the library, as opposed to the contents of static libraries, which are copied and embedded in the executables that reference them. Second, a single copy of the .text section of a shared library in memory can be shared by different running processes.

      The dynamic linker loads and links shared libraries when an application is loaded, just before it executes. However, it is also possible for an application to request the dynamic linker to load and link arbitrary shared libraries while the application is running, without having to linked the applications against those libraries at compile time.

      Linux and Solaris systems provide a simple interface to the dynamic linker that allows application programs to load and link shared libraries at run time. An application program that dynamically loads and links the shared library libvector.so is presented below.

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

int x[2] = {1, 2};
int y[2] = {3, 4};
int z[2];

int main()
{
 		void *handle;
        void (*addvec)(int *, int *, int *, int);
 		char *error;

 		// Dynamically load the shared library that contains addvec()
 		handle = dlopen("./libvector.so", RTLD_LAZY);
 		if (!handle) {
 				fprintf(stderr, "%s\n", dlerror());
 				exit(1);
		}

		// Get a pointer to the addvec() function we just loaded
		addvec = dlsym(handle, "addvec");
		if ((error = dlerror()) != NULL) {	// Returns: NULL if previous call was OK
				fprintf(stderr, "%s\n", error);
				exit(1);
		}

		// Now we can call addvec() it just like any other function
		addvec(x, y, z, 2);
		printf("z = [%d %d]\n", z[0], z[1]);

		// Unload the shared library
		if (dlclose(handle) < 0) {			// Returns: 0 if OK, -1 on error
				fprintf(stderr, "%s\n", dlerror());
				exit(1);
		}
		return 0;
} 

Source:

Randal E. Bryant, David R. O'Hallaron(2011). COMPUTER SYSTEMS A Programmer's Perspective (Second Edition).Beijing: China Machine Press.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值