c - 使用 dlfcn.h 库函数时出现无效的 ELF header 错误

标签 c linux gcc

我正在尝试用 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/

相关文章:

python-3.x - 我正在进行 cryptopals 挑战 5。尝试在 kali linux 中运行此脚本时,我在第 5 行遇到语法错误

linux - Bash 将多行 Git 日志输出保存到环境变量

linux - 在 *nix cd 命令中将目录更改为最后一个匹配项

c - 使用 gcc 中的内联汇编从 stdin 扫描并打印到 stdout

c++ - 出现无法分配内存错误

c - -D MACRO 和#define MACRO 的优先级

生成轻量级可执行文件的 C 编译器

c - “由于数据类型范围有限,比较总是正确的”C 中的警告?

c - 如何在 C 中以二进制形式从 PE_file 导入信息

c - 无法让这个数据结构工作(新手)