我正在尝试用 c 语言创建一个带有 3 个函数的小库。这是我的代码:
mm_alloc.h:
/*
* mm_alloc.h
*
* A clone of the interface documented in "man 3 malloc".
*/
#pragma once
#include <stdlib.h>
void *mm_malloc(size_t size);
void *mm_realloc(void *ptr, size_t size);
void mm_free(void *ptr);
上面三个函数里面暂时是空的
mm_test.c
#include "assert.h"
#include "dlfcn.h"
#include "stdio.h"
#include "stdlib.h"
/* Function pointers to hw3 functions */
void* (*mm_malloc)(size_t);
void* (*mm_realloc)(void*, size_t);
void (*mm_free)(void*);
void load_alloc_functions() {
void *handle = dlopen(".(Its path here)../mm_alloc.h", RTLD_NOW);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
char* error;
mm_malloc = dlsym(handle, "mm_malloc");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
mm_realloc = dlsym(handle, "mm_realloc");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
mm_free = dlsym(handle, "mm_free");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
}
int main() {
load_alloc_functions();
}
我的操作系统是 Ubuntu。这是我编译代码的方式:
gcc mm_test.c -o tmp -ldl
当我运行 tmp 时,它显示“无效的 ELF header ”。我该如何解决这个问题?
最佳答案
dlopen()
只能加载共享库文件(.so
文件),不能加载C头文件。
您将需要实现这些功能并将它们编译成共享库以供加载。
关于c - 使用 dlfcn.h 库函数时出现无效的 ELF header 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47963695/