Makefile与共享库链接失败

Makefile Linking with shared library fails

本文关键字:链接 失败 共享 Makefile      更新时间:2023-10-16

我试图编写一个共享库,并试图将其链接以形成最终的可执行文件。

Makefile

mystring.out:main.c libmystring.so
    gcc -I. -L/home/pradheep/myexploration/mystring/ -lmystring main.c -o mystring.out
libmystring.so:mystring.o
    gcc -shared -Wl,-soname,libmystring.so -o libmystring.so mystring.o
libmystring.a:mystring.o
    ar -r libmystring.a mystring.o
mystring.o:mystring.h mystring.c
    gcc -Wall -g -c -fPIC -I. mystring.c
clean:
    rm *.o 
    rm *.a
    rm *.so
    rm *.out

这是错误消息:

 gcc -I. -L/home/pradheep/myexploration/mystring/ -lmystring  main.c -o mystring.out
 /tmp/ccS9UDPS.o: In function `main':
main.c:(.text+0x2d): undefined reference to `mystrcpy'
main.c:(.text+0x5a): undefined reference to `mystrncpy'
main.c:(.text+0x87): undefined reference to `mystrncpy'
main.c:(.text+0xa4): undefined reference to `mystrlen'
collect2: ld returned 1 exit status
make: *** [mystring.out] Error 1

我已经导出了LD_LIBRARY_PATH

echo $LD_LIBRARY_PATH
/home/pradheep/myexploration/mystring

我的libmystring.so 的输出

 000004ca T mystrncpy
 0000045c T mystrcpy

我错过了什么?

解决方案:

问题是库-l的使用顺序。它应该在源文件之后使用达雅尔赖指出的正确顺序是gcc-I-L/home/pradhep/myexploration/mystring/main.c-lmystring-o mystring.out欢呼吧,它起作用了。

链接器的传统行为是在命令行上指定的库中从左到右搜索外部函数。这意味着包含函数定义的库应该出现在任何使用它的源文件或对象文件之后