ubuntu20.04使用openpty时链接lutil库失败

内核编译和嵌入式产品的设计与开发
回复
头像
shzb89
帖子: 4
注册时间: 2011-11-25 11:20
系统: ubuntu9.10&10.04

ubuntu20.04使用openpty时链接lutil库失败

#1

帖子 shzb89 » 2022-06-08 14:36

源代码如下:
#include <stddef.h>
#include <stdio.h>
#include <pty.h>

int main(void)
{
int iRet;
int iMaster;
int iSlave;

iRet = openpty(&iMaster, &iSlave, NULL, NULL, NULL);
if (0 != iRet)
{
printf("failed to open pty.\n");
return -1;
}

return 0;
}

编译报链接错误:
gcc -Wall -lutil -o test test.c
/usr/bin/ld: /tmp/ccNbau8Y.o: in function `main':
test.c:(.text+0x37): undefined reference to `openpty'
collect2: error: ld returned 1 exit status

同样代码在centos 7.1编译通过,gcc glibc版本使用更高的,也可以编译通过;

手动指定ltuil的位置,以及手动重编glibc库,再重新指定,也无法编译通过,各位谁有经验处理过类似问题的,请不吝赐教,谢谢~

系统版本:
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 20.04.4 LTS
Release: 20.04
Codename: focal
头像
astolia
论坛版主
帖子: 6453
注册时间: 2008-09-18 13:11

Re: ubuntu20.04使用openpty时链接lutil库失败

#2

帖子 astolia » 2022-06-08 17:55

其实就是个参数顺序的问题。好像是从gcc 4.7开始,链接时搜寻符号的时候严格参照参数的顺序,所以必须将被依赖的库放到目标之后
gcc -Wall -o test test.c -lutil
头像
shzb89
帖子: 4
注册时间: 2011-11-25 11:20
系统: ubuntu9.10&10.04

Re: ubuntu20.04使用openpty时链接lutil库失败

#3

帖子 shzb89 » 2022-06-14 19:22

嗯,后面发现了。不过不是4.7吧?CentOS 7.1的这个gcc版本是4.8.3。
Ubuntu的这个是9.4版本,我在其他服务器上,用更高版本(10.3)的,好像又没这个问题。
头像
astolia
论坛版主
帖子: 6453
注册时间: 2008-09-18 13:11

Re: ubuntu20.04使用openpty时链接lutil库失败

#4

帖子 astolia » 2022-06-15 11:37

shzb89 写了: 2022-06-14 19:22 嗯,后面发现了。不过不是4.7吧?CentOS 7.1的这个gcc版本是4.8.3。
Ubuntu的这个是9.4版本,我在其他服务器上,用更高版本(10.3)的,好像又没这个问题。
十多年前的事记不太清了,刚查了一下,是从ubuntu11.10上的gcc 4.6.1开始,默认启用了链接参数-Wl,--as-needed https://wiki.ubuntu.com/ToolChain/Compi ... -as-needed ,所以需要严格控制链接顺序
至于为什么更高版本的不会报错,这是因为在更高版本所在的系统上,libutil.a实际上是个空文件,-lutil这个参数并不起作用,删掉都行。openpty这些符号实际上是由libc库提供的,而在链接时-lc参数是放在test.c生成的对象文件之后的,可用gcc --verbose -o test test.c查看
回复