使用dlfcn.h库函数时无效的ELF标头错误

问题描述 投票:0回答:1

我想在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标题”。我怎么解决这个问题?

c linux gcc
1个回答
1
投票

dlopen()只能加载共享库文件(.so文件),而不能加载C头文件。

您将需要实现这些函数并将它们编译到共享库中以进行加载。

© www.soinside.com 2019 - 2024. All rights reserved.