[英]Linker error when using a function defined in a custom shared library
I created following shared library and wanted to use the functions defined in the library in a different c file.我创建了以下共享库,并希望在不同的 c 文件中使用库中定义的函数。
Header file: Header 文件:
#ifndef _MY_MALLOC_H_
#define _MY_MALLOC_H_
#include <dlfcn.h>
#include <stdio.h>
extern void* malloc(size_t sz);
extern void free(void *p);
extern int get_total_malloc_requested(void);
#endif
Implementation:执行:
#define _GNU_SOURCE
#include "my_malloc.h"
static int num_times_malloc_called = 0;
static int num_times_free_called = 0;
void* malloc(size_t sz)
{
void *(*libc_malloc)(size_t) = dlsym(RTLD_NEXT, "malloc");
num_times_malloc_called++;
fprintf(stderr,"malloc called %d\n",num_times_malloc_called);
return libc_malloc(sz);
// return NULL;
}
void free(void *p)
{
void (*libc_free)(void*) = dlsym(RTLD_NEXT, "free");
fprintf(stderr,"free\n");
libc_free(p);
}
int get_total_malloc_requested(void){
return num_times_malloc_called;
}
There was no problem when I created the.so.我创建.so时没有问题。
gcc -shared -fPIC -o my_malloc.so my_malloc.c -ldl
But when I am invoking get_total_malloc_requested from another.c file, I get linker error.但是当我从 another.c 文件调用 get_total_malloc_requested 时,我收到 linker 错误。
#include <stdio.h>
#include <stdlib.h>
#include "my_malloc.h"
int main(){
void *ptr;
ptr = malloc(64); <---no problem here
fprintf(stderr,"called malloc ");
free(ptr);<---no problem here
ptr = malloc(64);
fprintf(stderr,"called malloc ");
free(ptr);
get_total_malloc_requested();<---linker doesn't find the symbol
return 0;
}
gcc hello.c -o hello.o -L ./my_malloc.c
ld: warning: -L path './my_malloc.c' is not a directory
Undefined symbols for architecture x86_64:
"_get_total_malloc_requested", referenced from:
_main in hello-1dfbf1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
You created a shared object, but you are not creating an executable to use it.您创建了一个共享 object,但您没有创建一个可执行文件来使用它。 Since the executable is not using it, the referenced symbol is not found.由于可执行文件没有使用它,因此找不到引用的符号。
Remove the extraneous -L
option, and specify the shared object when linking.去掉多余的-L
选项,链接时指定共享的 object。
gcc hello.c -o hello ./my_malloc.so
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.