将共享库从不同的位置链接到它预期的最终位置

时间:2022-09-18 14:14:12

Suppose I have a main.lo which I'd like to link against library foo.so. The linker should always look for foo.so at /foo/bar/lib.so (fixed path, no search), but I only have lib.so in my home directory and not in /foo/bar/, which is a protected directory I can't write to myself.

假设我有一个main。我想要链接到库页。链接器应该始终查找foo。所以在/ foo / bar / lib。所以(固定路径,没有搜索),但是我只有lib。所以在我的主目录中,而不是在/foo/bar/中,这是一个受保护的目录,我不能写给我自己。

Is it possible to link the lib like this?

是否有可能像这样链接lib ?

Edit: Below is a simple example using /tmp instead of /foo/bar. Can you make it work by modifying the build script?

编辑:下面是一个使用/tmp而不是/foo/bar的简单示例。可以通过修改构建脚本使其工作吗?

main.c

c

void foo();
int main(){
  foo();
  return 0;
}

foo.c (multiple-file libraries are overrated)

foo。c(多文件库被高估)

#include <stdio.h>

void foo(){
  puts("foo");
}

build.sh

build.sh

#!/bin/sh
set -x
gcc -c -fPIC main.c -o main.lo
gcc -c -fPIC foo.c -o foo.lo
gcc -shared -o foo.so foo.lo

gcc -o pwd main.lo "$PWD/foo.so"
rm -f /tmp/foo.so

#? Link into dest, against /tmp/foo.so but use "$PWD/foo.so"


cp -a foo.so /tmp/foo.so

echo pwd:
./pwd   #this works
echo dest:
./dest

1 个解决方案

#1


3  

You need two options to make it work:

你需要两个选择才能让它工作:

First you need to use the -L option to tell the linker where the library is actually located at the moment.

首先,需要使用-L选项告诉链接器当前库的实际位置。

Then you need to use the -rpath linker option to tell where the final location will be. Unfortunately this is a linker-specific option which means you need to use the -Wl option to the GCC frontend program.

然后需要使用-rpath链接器选项来确定最终位置。不幸的是,这是一个特定于链接的选项,这意味着您需要对GCC frontend程序使用-Wl选项。

So the command should look something like

命令应该是这样的。

$ gcc object.o files.o -o target \
    -L/current/path/to/library -Wl,-rpath,/final/path/to/library -llibrary

Note that the two paths can of course be the same.

注意,这两条路径当然可以是相同的。

#1


3  

You need two options to make it work:

你需要两个选择才能让它工作:

First you need to use the -L option to tell the linker where the library is actually located at the moment.

首先,需要使用-L选项告诉链接器当前库的实际位置。

Then you need to use the -rpath linker option to tell where the final location will be. Unfortunately this is a linker-specific option which means you need to use the -Wl option to the GCC frontend program.

然后需要使用-rpath链接器选项来确定最终位置。不幸的是,这是一个特定于链接的选项,这意味着您需要对GCC frontend程序使用-Wl选项。

So the command should look something like

命令应该是这样的。

$ gcc object.o files.o -o target \
    -L/current/path/to/library -Wl,-rpath,/final/path/to/library -llibrary

Note that the two paths can of course be the same.

注意,这两条路径当然可以是相同的。