【问题标题】:Shared library not found in /usr/local/lib在 /usr/local/lib 中找不到共享库
【发布时间】:2021-05-10 15:07:17
【问题描述】:

类似的问题被问了很多,但我仍然不太明白我编译和安装共享库的方式有什么问题。

就编译而言,我会做

> gcc -c -fPIC libt.c
> gcc -shared -Wl,-soname,libt.so.0 -o libt.so.0.1 libt.o

为了安装我运行的库

> cp libt.so.0.1 /usr/local/lib/
> cp libt.h /usr/local/include/
> ln -s /usr/local/lib/libt.so.0.1 /usr/local/lib/libt.so.0 # ldconfig would setup this symlink itself ...
> ln -s /usr/local/lib/libt.so.0 /usr/local/lib/libt.so # ... but not this one, so I do it myself
> sudo ldconfig

/usr/local/lib 包含在 /etc/ld.so.conf.d/libc.conf 中,ldconfig -p | grep libt 产生

libt.so.0 (libc6,x86-64) => /usr/local/lib/libt.so.0
libt.so (libc6,x86-64) => /usr/local/lib/libt.so

所以,据我所知,到目前为止,一切看起来都还不错。但是,编译一个应该使用我的库的程序会失败:

> gcc -o prog main.c -llibt
/usr/bin/ld: cannot find -llibt

libt.h

#ifndef libt_h__
#define libt_h__

extern int add(int, int);

#endif 

libt.c

int
add(int a, int b)
{
    return a + b;
}

main.c

#include <stdio.h>
#include <stdlib.h>
#include "libt.h"

void
print_usage()
{
    printf("usage: ./prog <number a> <number b>\n");
}

int
main(int argc, char *argv[])
{
    int a = 0, b = 0, c = 0;

    if (argc != 3) {
        print_usage();
        return 1;
    }

    a = atoi(argv[1]);
    b = atoi(argv[2]);
    c = add(a, b);

    printf("%d\n", c);

    return 0;
}

【问题讨论】:

    标签: compilation shared-libraries ld


    【解决方案1】:

    想通了。虽然库名称必须以“lib”为前缀,但链接时不得指定该前缀。也就是说,gcc -o prog main.c -llibt 是错误的,而 gcc -o prog main.c -lt 可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 2013-07-27
      • 2011-02-23
      • 2012-08-16
      • 2015-11-03
      • 2013-09-09
      相关资源
      最近更新 更多