我正在尝试使用C语言进行动态加载,并且在开头就遇到了问题。我有一个小程序,可以在运行时加载一个对象。该对象包含一个单独的函数,该函数将一些消息写入标准输入。该程序已经在OS X 10.10上使用clang编译。以下是代码:
/* loader.c */
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include "module.h"
int main(int argc, char **argv) {
char file[] = "/users/user/dev/module.o";
void *handle;
int (*function)();
handle = dlopen(file, RTLD_NOW);
if (!handle) {
printf("Cannot load program. Error: %s\n", dlerror());
return 1;
}
program = dlsym(handle, "function");
printf("Program loaded");
function();
printf("Exiting");
return 0;
}
以下是 module.h 模块文件:
/* module.h */
int
function();
这里是module.c文件:
/* module.c */
#include <stdio.h>
#include <unistd.h>
int function() {
printf("Hello from module");
sleep(1);
printf("Hello from module again");
return 0;
}
这是Makefile:
loader : loader.c module.o
cc -Wall loader.c -ldl -o loader
module.o : module.c
cc -Wall -fpic -c module.c
这个程序编译时没有警告,但是它并没有按照我的期望执行。程序返回以下错误:
Error: dlopen(/users/user/dev/module.o, 2): no suitable image found. Did find: /users/user/dev/module.o: file too short
。
我查看了一下,关于这个错误信息几乎没有什么资料。这个程序是基于TLDP的dlopen
示例编写的。这是否意味着文件需要满足一定的大小才能被动态加载,还是这些文件的编译方式存在问题?
我感觉自己错过了一些简单的东西。
我该如何使这个程序按照预期执行?