当一个主程序在不同的情况下,需要链接功能不同的动态库时,我们一般的做法时,每换一个情景,我们就要让程序重新链接一个新的动态库,这样就显得很麻烦又笨拙。如果我们可以把动态库作为参数来传递,那样我们只需要在主程序中判断是哪种情景,然后由程序帮我们自动选择所需要链接的动态库即可。
下面我们用一个实例来详细讲解:
这个实例的功能是用一个主程序来使lcd液晶屏显示bmp格式或者jpg格式的图片,当接收到的参数是bmp格式的图片时,就链接bmp动态库;当接收到的参数是jpg格式的图片时,就链接jpg动态库。
制作显示bmp、JPG图片的动态库
common.h是常用的一些头文件
//common.h
#ifndef __COMMOD_H
#define __COMMOD_H
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <strings.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <math.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <time.h>
#include <errno.h>
#include <linux/input.h>
#include <linux/fb.h>
#include <dlfcn.h>
#endif
bmp.h是显示bmp图片所需要的头文件
//bmp.h
#ifndef __BMP_H_
#define __BMP_H_
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <pthread.h>
#define LCD "/dev/fb0"
#define BACKGROUND "./res/bmp/background.bmp"
#define BAR "./res/bmp/bar.bmp"
#define LOGO "./res/bmp/logo.bmp"
#define KEYON "./res/bmp/key_on.bmp"
#define KEYOFF "./res/bmp/key_off.bmp"
struct bitmap_header
{
int16_t type;
int32_t size; // 图像文件大小
int16_t reserved1;
int16_t reserved2;
int32_t offbits; // bmp图像数据偏移量
}__attribute__((packed));
struct bitmap_info
{
int32_t size; // 本结构大小
int32_t width; // 单位:像素
int32_t height;// 单位:像素
int16_t planes; // 总为零
int16_t bit_count; // 色深:24(1像素=24位=3字节)
int32_t compression;
int32_t size_img; // bmp数据大小,必须是4的整数倍
int32_t X_pel;
int32_t Y_pel;
int32_t clrused;
int32_t clrImportant;
}__attribute__((packed));
struct rgb_quad
{
int8_t blue;
int8_t green;
int8_t red;
int8_t reserved;
}__attribute_