Distributing (native C++) libraries on windows

2019-05-27 01:50发布

问题:

I would like to share a library I've written in native C++ with a third party. By that I mean I'd like to share a library providing functionality I've developed with someone who is using windows, whom I do not wish to share source code with. We can assume the same CPU architecture here.

I've only ever shared source code directly, and mostly on linux. So the standard process of ensuring I can provide a binary that is as versatile as possible is a mystery to me. And I find documentation online to be lacking.

I am currently working on sharing .lib files, however it does seem to imply that these will only work if the compiler linking it is the same compiler I used to generate that lib file.

The more common method does seem to be the dynamic linking route - providing a .dll. I'm not terrifically fond of the overhead of doing so, as it seems that my function and class signatures would look something like this __declspec(dllexport) void __cdecl Function1(void);. As I am aiming to maintain cross-platform compatibility, I can imagine my source growing into a tangle of conditional compilation. Furthermore, unless I go the runtime linking route, I'll have to provide an import library .lib, which brings me back to the same problem as before.

Is there a guide to distributing libraries on Windows? Is runtime linking of DLLs the only realistic way? And is it dependable? (The issue of conflicting runtime libraries comes to mind).

回答1:

The easiest way to "export" a C++ class that will work reliably across different compiler and standard library implementations is to use cppcomponents https://github.com/jbandela/cppcomponents

The library is header only, so no building is required. It works on both Linux and Windows, and does not require any import libraries. It does however, require a capable C++11 compiler (gcc 4.7.2, clang 3.2, Visual Studio 2013 all work).

  • It supports std::string, vector, tuple as well as other standard types.
  • It supports exceptions.
  • It also supports std::function like objects that can be used across different compilers.
  • There is also built in support for events that should make your observer pattern easier to implement.

The library is released under the Boost License so it is free for both commercial and opensource use.

For an example of using it, take a look at my stackoverflow answer to a similar question https://stackoverflow.com/a/19592553/1858436

Using this for your library would allow a single binary to be used from Visual C++ (both debug and release, and future versions), as well as GCC. Otherwise, you will be stuck having to support a debug version, a release version, and a GCC version, and when a new version comes out have to rebuild for that version.

If you have a specific small example of what you want to do, I can help you with that.