dari
dari

Reputation: 2455

Static library linked two times

I have the following setup:

  1. A static library
  2. A dynamic library that links to (1.)
  3. An executable that links to (1.) and (2.)

The code from the from the static library is now duplicated and present in the dynamic library and the executable.

Questions:

Is the Data (global variables, static class members) also duplicated and does the executable and the dll see the same data?

Is there a difference between Linux and Windows?

How would you solve this?

Edit:

Thanks for the answers, I can now explain what happened in my case exactly.

The static library had no export/import flags. The dynamic library had export on its own symbols.

Windows:

The dynamic library had a copy of the text+data segement of the static library. The executeable couldn't know, that the dynamic library had linked the static library, because non of the static-library symbols are visible from the outside.

Linux:

The dynamic library had a copy of the text data segment of the static library and included all symbols (text and data) from the static library in its own symbol table. -> The executable sees, that the dynamic library has already defined all symbols of the static library and does not redefine them.

This is bad because you usually want the same behavior on linux and on windows.

  1. Share symbols (default on linux)
  1. Reduntant symbols (default on windows)

Upvotes: 12

Views: 4698

Answers (2)

user1196549
user1196549

Reputation:

IMO this is a nasty situation, as there are two executables (the exe and the dll) each with their instance of the code and global data. They are built independently and cannot share their memory mapping.

An option could be to let the dll expose the required members of the static library so that the exe can link to them directly.

Upvotes: 0

pqnet
pqnet

Reputation: 6588

As far as I know, it depends on the operating system (because C++ language doesn't say much about how libraries should work).

On windows, you'll get twice the code and data, and worse of that all twice the global variables declared in that library (!)

This issue shows up when linking statically the standard library in a program and a library using that, when you get two default allocators and if you call new on a library and delete on the other, the object will leak on the new side and the heap is likely to become corrupted on the delete side.

I do not know the details about other operating systems, but I expect similar issues may arise

Upvotes: 8

Related Questions