繁体   English   中英

我的共享库的c函数在库外看不到

[英]c function of my shared lib is not seen out of the lib

我已经开发了这个 lib: mylib.c:

#include "mylib.h"
int foo(int a,int b) {
return 1;
}

mylib.h:

#include <stdio.h>
extern int foo(int a,int b);

Makefile(libmylib.so在lib文件夹中生成成功):

CFLAGS += -g -Wall -Werror -Wpointer-arith -fPIC -fno-strict-aliasing
OBJECTS = mylib.o
MY_LIBRARY := libmylib.so

all: $(MY_LIBRARY)

$(MY_LIBRARY): $(OBJECTS)
    $(CC) $(CFLAGS) $(LDFLAGS) -fPIC -rdynamic -shared -Wl,-soname,$@ -o ./lib/$@  $^

$(OBJECTS):
    $(CC) $(CFLAGS) $(INCLUDES) -c ${@:.o=.c} -o $@
    
clean :
    @rm -f *.o
    @rm -f ./lib/$(MY_LIBRARY)

我的测试程序:test.c:

#include <stdio.h>
#include <mylib.h> //mylib.h was copied to /usr/include

int main () {
foo(5,2);
return 0;
}

编译:

gcc -c test.c -o test.o => pass
gcc -L./lib -lmylib test.o -o TEST => fail

错误:

user~/Desktop/test_lib$ gcc -L./lib -lmylib test.o -o TEST
test.o: In function `main':
test.c:(.text+0xf): undefined reference to `foo'
collect2: error: ld returned 1 exit status

我不明白为什么它在生成我的程序时失败?

如果在gcc命令行上使用-I选项,则不需要使用测试文件污染/usr/include

gcc -c test.c -o test.o -I.

链接命令行上文件的顺序很重要。 将库放在使用它们的文件之后:

$ gcc -L./lib -lmylib test.o -o TEST
/usr/bin/ld: test.o: in function `main':
test.c:(.text+0x13): undefined reference to `foo'
collect2: error: ld returned 1 exit status
$ gcc test.o -L./lib -lmylib  -o TEST
$

然后,使用LD_LIBRARY_PATH环境变量将库的路径名添加到动态链接器的搜索路径列表中(建议使用绝对路径名,但出于测试目的,我使用相对路径名):

$ ./TEST
./TEST: error while loading shared libraries: libmylib.so: cannot open shared object file: No such file or directory
$ ldd TEST
    linux-vdso.so.1 (0x00007ffeb8bf1000)
    libmylib.so => not found
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f268fe40000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f2690056000)
$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:./lib
$ ldd TEST
    linux-vdso.so.1 (0x00007ffd75bcb000)
    libmylib.so => ./lib/libmylib.so (0x00007f16ff112000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f16fef03000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f16ff11e000)
$ ./TEST
$

我已经通过在链接到 mylib 时更改 gcc 命令中选项的顺序来修复此错误,我没有解释,但这解决了我的问题。

user:~/Desktop/test_lib$ gcc -L./lib -lmylib test.o -o TEST
test.o: In function `main':
test.c:(.text+0xf): undefined reference to `foo'
collect2: error: ld returned 1 exit status
user:~/Desktop/test_lib$ gcc -L./lib test.o -o TEST -lmylib
user:~/Desktop/test_lib$ ls -l
total 40
drwxr-xr-x 2 user group 4096 nov.  16 19:15 lib
-rw-r--r-- 1 user group  346 nov.  16 19:00 Makefile
-rw-r--r-- 1 user group   54 nov.  16 18:20 mylib.c
-rw-r--r-- 1 user group   22 nov.  16 18:20 mylib.h
-rw-r--r-- 1 user group 2632 nov.  16 19:15 mylib.o
-rwxr-xr-x 1 user group 8592 nov.  17 14:20 TEST
-rw-r--r-- 1 user group   56 nov.  16 18:21 test.c
-rw-r--r-- 1 v 1376 nov.  16 19:15 test.o
user:~/Desktop/test_lib$

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM