c++ - Makefile 与共享库的链接失败

标签 c++ c 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 的使用顺序。它应该在源文件之后使用 Dayal rai 指出的正确顺序是 gcc -I。 -L/home/pradheep/myexploration/mystring/main.c -lmystring -o mystring.out 欢呼它起作用了。

最佳答案

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

关于c++ - Makefile 与共享库的链接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17716482/

相关文章:

c++ - 使用 GLUT_DOUBLE 模式绘制形状

c - 从文件中读取的额外行

c++ - 对 `yylex' 的 undefined reference && 对 `yyin' 的 undefined reference

shell - 如何从 MAKEFILE 中的用户定义函数传递和返回值?

c++ - Makefile.am/Configure.ac 条件环境变量检查

c++ - 使用 I2C 发送 0x00

c++ - 如何在内联回调函数中使用 EXPECT_EQ 和其他 Google Mock 语句?

c++ - linux下源码编译

c - 笑脸的 DOS 字符?

c - 如何打印循环结果?