限制 Linux 静态库中的符号 [英] Restricting symbols in a Linux static library
问题描述
我正在寻找方法来限制导出到 Linux 静态库(存档)的 C 符号的数量.我想将这些限制为仅属于库官方 API 的那些符号.我已经使用静态"将大多数函数声明为静态,但这将它们限制在文件范围内.我正在寻找一种方法来限制图书馆的范围.
I'm looking for ways to restrict the number of C symbols exported to a Linux static library (archive). I'd like to limit these to only those symbols that are part of the official API for the library. I already use 'static' to declare most functions as static, but this restricts them to file scope. I'm looking for a way to restrict to scope to the library.
我可以使用 Ulrich Drepper 的 如何编写共享库,但我无法将这些技术应用于静态档案.在他早期的图书馆设计的良好实践论文中,他写道:
I can do this for shared libraries using the techniques in Ulrich Drepper's How to Write Shared Libraries, but I can't apply these techniques to static archives. In his earlier Good Practices in Library Design paper, he writes:
唯一的可能是组合所有需要的目标文件使用ld -r"将某些内部资源合二为一,然后限制符号由这个组合的目标文件导出.GNU 链接器可以选择这样做.
The only possibility is to combine all object files which need certain internal resources into one using 'ld -r' and then restrict the symbols which are exported by this combined object file. The GNU linker has options to do just this.
谁能帮我发现这些选项可能是什么?我在使用 'strip -w -K prefix_*' 方面取得了一些成功,但这感觉很粗鲁.理想情况下,我想要一个适用于 GCC 3 和 4 的解决方案.
Could anyone help me discover what these options might be? I've had some success with 'strip -w -K prefix_*', but this feels brutish. Ideally, I'd like a solution that will work with both GCC 3 and 4.
谢谢!
推荐答案
我不相信 GNU ld 有任何这样的选择;Ulrich 一定是指 objcopy
,它有很多这样的选项:--localize-hidden
、--localize-symbol=symbolname
、--localize-symbols=filename
.
I don't believe GNU ld has any such options; Ulrich must have meant objcopy
, which has many such options: --localize-hidden
, --localize-symbol=symbolname
, --localize-symbols=filename
.
--localize-hidden
特别允许人们对暴露的符号进行非常精细的控制.考虑:
The --localize-hidden
in particular allows one to have a very fine control over which symbols are exposed. Consider:
int foo() { return 42; }
int __attribute__((visibility("hidden"))) bar() { return 24; }
gcc -c foo.c
nm foo.o
000000000000000b T bar
0000000000000000 T foo
objcopy --localize-hidden foo.o bar.o
nm bar.o
000000000000000b t bar
0000000000000000 T foo
所以 bar()
不再从对象导出(即使它仍然存在并且可用于调试).您还可以将 bar()
与 objcopy --strip-unneeded
一起删除.
So bar()
is no longer exported from the object (even though it is still present and usable for debugging). You could also remove bar()
all together with objcopy --strip-unneeded
.
这篇关于限制 Linux 静态库中的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!