静态库“接口”
在构建目标文件 (lib*.o
) 时,有什么方法可以告诉编译器 (gcc/mingw32) 仅公开 .c 文件中的某些函数吗?
我想要这样做的原因是我静态链接到一个超过 100,000 行的库 (SQLite),但我只使用它提供的部分功能。我希望,如果我可以告诉编译器只公开这些函数,它将优化我选择的少数函数中永远不需要的函数的所有代码,从而大大减小库的大小。
Is there any way to tell the compiler (gcc/mingw32) when building an object file (lib*.o
) to only expose certain functions from the .c file?
The reason I want to do this is that I am statically linking to a 100,000+ line library (SQLite), but am only using a select few of the functions it offers. I am hoping that if I can tell the compiler to only expose those functions, it will optimize out all the code of the functions that are never needed for those few I selected, thus dratically decreasing the size of the library.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能是链接器的工作,而不是编译器的工作。当将其链接为程序(.exe)时,链接器将只负责导入相关符号,而当链接 DLL 时,__dllexport 机制可能就是您正在寻找的,或者 ld 的一些标志可以帮助您(man ld)。
That's probably the linkers job, not the compilers. When linking that as a program (.exe), the linker will take care of only importing the relevant symbols, and when linking a DLL, the __dllexport mechanism is probably what you are looking for, or some flags of ld can help you (man ld).
我找到了几种可能的解决方案:
这就是我所问的。它是 Windows 的
dllexpoort
的 gcc 等效项:-fvisibility
)我还发现了链接时代码生成。这允许链接器查看实际使用的代码部分并删除其余部分。将其与
strip
和-fwhole-program
一起使用给了我更好的结果。-flto
和-fwhole-program
)注意: 仅当您不是在一次调用 gcc 中编译整个程序时,此标志才有意义,这就是我正在做的事情(创建一个 sqlite.o 文件,然后静态链接它)。
这里提到了我发现但尚未研究的第三个选项:
I found several possible solutions:
This is what I asked about. It is the gcc equivalent of Windows'
dllexpoort
:-fvisibility
)I also discovered link-time code-generation. This allows the linker to see what parts of the code are actually used and get rid of the rest. Using this together with
strip
and-fwhole-program
has given me drastically better results.-flto
and-fwhole-program
)Note: This flag only makes sense if you are not compiling the whole program in one call to gcc, which is what I was doing (making a sqlite.o file and then statically linking it in).
The third option which I found but have not yet looked into is mentioned here: