【发布时间】:2018-10-31 15:12:41
【问题描述】:
我想将目标文件和一个静态库合并到一个共享库中,但是静态库不能暴露,它只在进入共享库的目标文件中引用。我认为在这种情况下,我不需要使用-fPIC 编译静态库,但我不知道如何告诉链接器我不会使用静态库中的符号这一事实。为了说明我的问题,请使用以下文件:
文件foo.cpp:
#include "static.h"
using namespace std;
string version_info()
{
return static_version_info();
}
文件static.cpp:
#include"static.h"
#include <vector>
using namespace std;
string static_version_info()
{
std::vector<int> ivec;
return to_string(ivec.size());
}
文件static.h:
#ifndef STATIC_H
#define STATIC_H
#include<iostream>
using namespace std;
std::string static_version_info();
#endif
那就做吧
$ g++ -c foo.cpp -o foo.o -fPIC
$ g++ -c static.cpp -o static.o
$ gcc-ar rcs static.a static.o
$ g++ -shared foo.o static.a
/usr/bin/ld: static.a(static.o): relocation R_X86_64_PC32 against symbol `_ZNSt6vectorIiSaIiEEC1Ev' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
问题: 如何调整最后一个命令,以免出现错误?这可能吗?
注意我不想编译 static.cpp with -fPIC 我不需要符号(这里 @987654331 @) 在共享库中。
【问题讨论】:
-
我没有按照你的思路。如果你
...will not use the symbols from the static library...你为什么需要它链接? -
@SergeyA 静态库仅在与静态库一起链接到共享库的目标文件中定义的接口中使用。我只通过这个接口访问静态库。问题是在这种情况下我是否可以避免
-fPIC用于静态库。