r/cpp • u/debhaldar • Oct 10 '19
10 differences between static and dynamic libraries every C++ developer should know
https://www.acodersjourney.com/cplusplus-static-vs-dynamic-libraries/30
u/carrottread Oct 10 '19
As a rule of thumb, prefer to distribute your library as a dynamic library unless it is very small and is prone to version conflicts with rest of the system.
No, as a rule of thumb, prefer to distribute it as a source code.
20
u/o11c int main = 12828721; Oct 10 '19
Horribly inaccurate in places, and missing critical info.
Point 3's parenthetical is wrong; dynamic libraries are needed even before the function is called, unless you are using dlsym.
Point 6 is completely wrong for static - version problems are more likely due to collisions. And it doesn't mention either SOLIBs or symbol versions for the dynamic case.
Point 8 omits the fact that unloading is extremely dangerous and likely to break things, due to all the implicit sharing going on. If you really need that kind of control, you must spawn a new process.
Point 9 is basically saying "waah, my shitty tooling doesn't support it" rather than being a real criticism of dynamic linking.
No mention of TLS, PIC, prelinking, rpath ... and how architecture matters.
7
u/adnukator Oct 10 '19
Point 5. Memory efficiency as "Low" with static libs is questionable since the linker can strip out unused symbols, keeping only used ones in the final binary
Point 6. Versioning problems are possible with static libraries during linking if your static libs depend on other static libs (not saying it's a good idea, but still)
Another thing not mentioned is that with dynamic libraries (at least in Windows) you can potentially run into problems with the global loader lock, leading to deadlocks during dll loading. With statics this is not possible.
6
u/markand67 Oct 10 '19
Point 4. No. A good library is implemented in individual object files, thus the linker does not need to pull all symbols. This is also why most C libraries implement all functions into individual objects.
1
u/ShakaUVM i+++ ++i+i[arr] Oct 10 '19
Is there an easy way to enumerate all the function names in a dynamic library? I'd like to make an AI tournament with an unknown number of competitors
4
u/drcforbin Oct 10 '19
On Linux, nm will do it, on Windows, dumpbin.
1
u/ShakaUVM i+++ ++i+i[arr] Oct 11 '19
Thanks
From inside of C++, though? I have been searching for some function that will return a list of functions in a so file so that I can find all functions starting with AI_ (like AI_Bob, AI_Charles, etc.) and have my game server put them in a match with each other without having to recompile each time.
Competitors would enter their AI into the competition by copying their so file to the executable's directory.
I could probably system() nm and parse the results, but that seems a bit clunky.
5
u/evaned Oct 11 '19
This to me sounds like you're asking for the wrong thing. Your different AIs don't need entry points that are named differently -- you could have them all expose something called
run_aior something. If you want a name, that could be exposed via a different function (string_view get_name()or whatever), or you could have it exposed as a constant instead of a function, or maybe you even just have the interface be just a single struct with some function pointers or something.If you're talking about dynamically-loaded AI modules instead of shared objects that you link into the executable at link time, I don't really see any drawback to this.
(Part of why I suggest it though is that you'll have to do a bit of work to actually get to the symbol tables of your loaded shared libraries, so this will be easier as well as what seems to be the norm.)
3
u/drcforbin Oct 11 '19
Agreed. Having a standard API to be exposed by the libraries is a better solution than guessing at functions and parsing their names by pattern. If you want more complicated interfaces, versioned interfaces, different kinds of APIs, COM (more or less) did this by having a single function that would be implemented by every shared library, which when called would return a function table, including a function for retrieving pointers to other tables by id, each representing a different kind of interface...it let you basically query whether an object supported an interface, and then to use it.
That said, do consider security...loading untrusted shared libraries can be dangerous.
1
u/ShakaUVM i+++ ++i+i[arr] Oct 11 '19
That said, do consider security...loading untrusted shared libraries can be dangerous.
It runs in a sandboxed account, so the best it could do is delete or modify all the files in the local directory. Somebody did try that last time (modifying the other AIs to make invalid moves), but all they managed to do was cause a crash, which gave them an automatic loss. The people in the AI tournament are all friends of mine, so I don't see a need for more security than this.
3
u/evaned Oct 11 '19
Just in case it's not clear what I mean or how to do it, I whipped up a crappy little example of what I mean:
///// DRIVER.CPP ////// #include <dlfcn.h> #include <stdio.h> #include <vector> struct Ai { char const* name; int (*do_action)(int x); }; int main(int argc, char* argv[]) { std::vector<Ai> ais; ais.reserve(argc - 1); for (int i = 1; i < argc; ++i) { void* lib = dlopen(argv[i], RTLD_LAZY | RTLD_LOCAL); if (not lib) { fprintf(stdout, "%s: dlopen(%s): %s\n", argv[0], argv[i], dlerror()); return 1; } void* name_v = dlsym(lib, "name"); if (not name_v) { fprintf(stdout, "%s: dlsym(\"name\"): %s\n", argv[0], dlerror()); return 1; } void* do_action_v = dlsym(lib, "do_action"); if (not do_action_v) { fprintf(stdout, "%s: dlsym(\"do_action\"): %s\n", argv[0], dlerror()); return 1; } Ai ai = { *static_cast<char const**>(name_v), reinterpret_cast<int(*)(int)>(do_action_v) }; ais.emplace_back(ai); } for (int i = 0; i < (int)ais.size(); ++i) printf("%s: do_action(%d) => %d\n", ais[i].name, i, ais[i].do_action(i)); return 0; } ///// ALICE.C ///// char const * name = "Alice"; int do_action(int x) { return x; } ///// BOB.C ///// char const * name = "Bob"; int do_action(int x) { return x * 2; } ///// CAROL.C ///// char const * name = "Carol"; int do_action(int x) { return x * x; } ///// DAVE.C ///// char const * name = "Dave"; int do_action(int x) { return 9; } ///// Makefile (I hate make but whatever let's use it here) ///// CXXFLAGS=-g -Wall -Wextra -Wconversion -std=c++17 LDLIBS=-ldl all: demo all-built: driver alice.so bob.so carol.so dave.so .PHONY: all all-built demo driver.o: driver.cpp Makefile driver: driver.o Makefile $(CXX) $(LDFLAGS) -o "$@" "$<" $(LOADLIBES) $(LDLIBS) %.so: %.o Makefile $(CXX) $(LDFLAGS) -o "$@" "$<" -shared demo: all-built ./driver ./dave.so ./alice.so ./bob.so ./carol.soGives:
$ ./driver ./dave.so ./alice.so ./bob.so ./carol.so Dave: do_action(0) => 9 Alice: do_action(1) => 1 Bob: do_action(2) => 4 Carol: do_action(3) => 91
u/ShakaUVM i+++ ++i+i[arr] Oct 11 '19
That's... yeah, exactly what I was trying to figure out what to do. I like how you use the name string to distinguish between the different AI calls with the same name.
Thank you so much!
0
u/ravixp Oct 10 '19
One thing that wasn’t touched on is matching compiler versions. A dynamic library should work no matter what compiler the client is using, while a static library has no such guarantee, and it’s safest to match the exact compiler and compiler flags that were used to build it.
(Yes, in practice a static library is likely to work if the compiler version is close enough. “Likely to work” is rarely good enough, though, and dynamic libraries have actual guarantees.)
9
Oct 10 '19
I'm pretty sure a dynamic library guarantees nothing of the sort. In c++ each compiler (-version) has its own ABI, and your library has to be built with the same compiler if you want to link with it.
5
u/TheThiefMaster C++latest fanatic (and game dev) Oct 10 '19
You can generally either directly specify a dynamic lib to the linker (Linux I think) or generate an import lib from a dynamic library (Windows) and use it even far across versions.
ABIs are generally extremely stable across compiler versions and even different compilers on the same platform. On Windows MSVC and Clang produce ABI-compatible results, and on Linux you can do the same with Clang and GCC.
The last big ABI break on Linux was the std::string change in GCC 5.0.
On Windows C++ types aren't generally used in ABIs, so in practice the (C) ABI hasn't really changed since Windows XP. The C++ ABI has been stable since Visual Studio 2015, and libs are inter-compatible across the 2015-2019 compilers.
3
u/adnukator Oct 10 '19
libs are inter-compatible across the 2015-2019 compilers.
It's only backwards compability. You still can't link a library built with a newer toolset than the one used with the final binary. Also it requires you to have /GL disabled on consumed libraries even if they are built with an older toolset version.
1
u/TheThiefMaster C++latest fanatic (and game dev) Oct 11 '19 edited Oct 11 '19
You wouldn't build a lib with /GL (whole program optimization) and then distribute it - I don't think that format is even stable across updates to a single Vs version.
As for using newer libs with an older compiler, I think the problem is more nuanced. By my reading of Microsoft's docs, the main limiting factor for lib compatibility is the C Runtime version used - which must be at least as new as the newest used by any static lib.
The key there though is "static" lib and "used" - a lib that doesn't use the C Runtime, or the import library for a dynamic lib (i.e. dll) should be fine to use on an older compiler. The documentation even explicitly says that an executable using multiple versions of the CRT via DLLs is ok - which is talking about DLL compatibility with other major compiler versions (2015-2019 all load the same CRT at runtime - the universal CRT). The example given is for MSVC 11 and 12 - which were 2012 and 2013.
https://docs.microsoft.com/en-us/cpp/porting/binary-compat-2015-2017?view=vs-2019
1
u/ravixp Oct 10 '19
That’s true if you’re using C++ in general, but not because of dynamic vs static libraries. There’s an ABI-compatible subset of C++ that you have to use to get those guarantees if you’re using dynamic libraries, while there’s no way to get those guarantees with static libs.
2
u/barchar MSVC STL Dev Oct 10 '19
This isn't really true, however dynamic libraries handle the situation of:
a needs b(abi1)
c needs b(abi2)
app needs a, and c.
1
u/ravixp Oct 10 '19
Which part isn’t? I’m not sure whether you meant that dynamic libs provide weaker guarantees than that, or whether static libs provide stronger ones.
2
13
u/mcmcc #pragma once Oct 10 '19
Surprisingly, no mention of Position Independent Code.