简体   繁体   English

在C ++中修剪静态库

[英]Pruning a static library in c++

I am trying to expose a single well defined class by building a static library and then shipping the built library with a few header files that define that class and the interfaces needed to use it. 我试图通过建立一个静态库来公开一个定义明确的类,然后在构建的库中附带一些头文件,这些头文件定义了该类以及使用该类所需的接口。 I have that working but the problem I am running into is the library is gigantic. 我已经在工作,但是我遇到的问题是图书馆巨大。 It has every single object file from the whole project and all I need is a subset. 它具有整个项目中的每个目标文件,我只需要一个子集。 If I make a simple main.cpp file and include and use that single class then I get a output file that is only as big as the 20% of the library I am using. 如果我制作一个简单的main.cpp文件并包含并使用该单个类,那么我得到的输出文件仅与我正在使用的库的20%一样大。 Is there a way to tell the linker to start from a given place and prune everything else like in the executable case? 有没有办法告诉链接器从给定的位置开始,然后修剪可执行文件中的其他所有内容?

EDIT: I forgot to mention that I am using gcc on cygwin and linux (though I would like a solution that worked with visual studio as well, we generally use that for development but deploy primarily on linux) 编辑:我忘了提到我在cygwin和linux上使用gcc(尽管我也希望使用与Visual Studio兼容的解决方案,我们通常将其用于开发,但主要部署在linux上)

You have to split the project up. 您必须拆分项目。 Take out the files needed for the library and make that a separate project just building the lib. 取出需要的库文件,并做出一个单独的项目只是建立的lib。

The remaining project (with main.cpp in) needs to call the new lib project to get the lib Details depend on what tools and OS you are using to manage the project (eg Visual Studio or make or ... ) 剩下的项目(包含main.cpp)需要调用新的lib项目来获取lib Details,具体取决于您用来管理该项目的工具和操作系统(例如Visual Studio或make或...)

You haven't told us what toolchain you are using but since you say project, I'm guessing you are using the MS toolchain. 您没有告诉我们您正在使用什么工具链,但是由于您说的是Project,所以我猜您正在使用MS工具链。

The MS toolchain includes every object from a project into the static library. MS工具链将项目中的每个对象都包含到静态库中。 What you want to do is break your single class into a separate project. 您想要做的是将您的单个班级拆分为一个单独的项目。 You can continue to have a super-project that includes that class so you don't have to modify any of your existing projects. 您可以继续拥有一个包含该类的超级项目,因此您无需修改​​任何现有项目。

Now, if you want to take this to the next level, you should consider putting each member of the class into it's own translation unit (ie .cpp file). 现在,如果您想将其带入新的高度,则应考虑将类的每个成员放入其自己的翻译单元(即.cpp文件)。 This way, if a user of the class only needs a few parts of the class, they will only need to link in the parts they need. 这样,如果班级的用户只需要班级的几个部分,那么他们只需要链接所需的部分。

Make a shared library. 制作一个共享库。 It behaves like an executable from the point of view of linking etc. It should do the discarding you mentioned you saw on the executable. 从链接等角度来看,它的行为类似于可执行文件。它应该执行您在可执行文件中看到的丢弃操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM