|
您现在的位置是:
IT外包 ->技术支持 ->基础知识 ->
|
|
|
|
用ldscript实现编译期功能插入
|
作者:
不详
| 发布时间:
2008-06-12 13:21
| 信息类别:
基础知识
| 访问人次:
次 |
|
|
|
|
|
= 动机
设想,如果你想在程序中支持多种后端(backends),但在开发过程中并不能预计会有多少种。一般来说,会想着抽象出这种后端的描述,然后用动态模块的方式,如 shared library 实现所谓的插件。使用插件,可以实现动态的功能插入,但如果你不想动态的功能插入,所有功能在编译期间就已经确定呢。当然你可以使用一个数组硬编码维护,但这样增删功能就需要改代码,这里介绍一种使用 ld script 的方法。这种方法在 linux kernel 的代码中也使用到了。
= 关于 ld script
即使你不知道, ld script 在每次你链接程序的时候都被使用了,ld程序自带一个默认的脚本,如果你不指定其他的脚本就使用默认的。 ld script 的作用是描述如何组织从目标文件中得到的所有段,最终链接成最终的 elf 输出。
关于 ld script 更多的信息,可以参考 ld 的 info page。
= 定义 ldscript
这里实现一个简单的示例程序,结构如下:主程序遍历一个外部静态数组,打印里面的所有字符串,直到结束;其他目标文件分别向该数组插入一个或多个字符串,而无须修改主程序的代码或者执行额外的启动代码。
file:main.c
[code]
#include
#include
extern const char array_begin;
extern const char array_end;
int main ( void ){
const char *array_iter;
printf( "array_begin : %p , array_end : %p\n", &array_begin, &array_end);
for ( array_iter = &array_begin;
array_iter = 现实例子
在 PC x86 中,有多种通用的显示输出方式,常用的如 bios 提供的以字符为基础的输入输出例程,还有就是 vesa 2.0 显卡规范。在 linux x86 启动过程中,kernel 根据配置选择合适的视频输出设备。 实现中, kernel 就用到了 ldscript, 见 :
linux-2.6/arch/x86/boot/setup.ld :
.videocards : {
video_cards = .;
*(.videocards)
video_cards_end = .;
}
linux-2.6/arch/x86/boot/video.h :
...
#define __videocard struct card_info __attribute__((section(".videocards")))
...
extern struct card_info video_cards[], video_cards_end[];
...
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/8057/showart_696239.html
|