Swiss Frank
Swiss Frank

Reputation: 2422

library's object files with classes not explicitly referenced but available via a factory are being skipped at link time

I have dozens of classes that are subclasses of a generic class. Based on messages my program receives, it will instantiate objects of those subclasses via a factory. Each subclass is in a file, as per usual C++ programming style. Each such file also includes a 1-line instantiation of a Type class template that takes the subclass as a template parameter, and the string name of the class as a constructor parameter, and registering itself with the factory. When asked for an object of a named type, the factory can check the registered Type's and and able to create an object of any named type.

End result is that there need not be any master list of subclasses available to be created upon message receipt. At worst this eliminates one task of adding types, and avoids any possible merge conflicts.

OK: if all the object files are included at link time as objects, it works fine. If they're all put in a dynamic library, again it works fine. However if they're all put in a static library, then the linker "helpfully" notes that no symbols in these files are referred to and so removes the object file completely.

No surprise, I've known about this from the early 90s.

But is there any modern C++ or linker magic I can employ to have the linker simply leave all the object files in the resulting binary?

(Complaint: the fact that the file has code to run at program startup--the constructor of the Type classes, that register themselves with the factory--should be sufficient for the compiler to leave them in place, don't you think?)

Upvotes: 3

Views: 123

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

You appear to be looking for this option from ld(1)'s manual page:

   --whole-archive
       For each archive mentioned on the command line after the
       --whole-archive option, include every object file in the archive in
       the link, rather than searching the archive for the required object
       files.

The rest of the paragraph notes that this is normally used when creating a shared library, but is not limited to that use case. The next paragraph mention a specific detail you need to know, so I'll just refer you to the manual page for more information.

Upvotes: 1

Related Questions