jpo38
jpo38

Reputation: 21544

How to compile a 3rd C++ party source code as shared library

I downloaded a third party source code, EDFlib, and would like to compile it (using Visual Studio) into a shared library with all symbols exported.

Header file looks like this:

#ifdef __cplusplus
extern "C" {
#endif

...
long long edftell(int handle, int edfsignal);
...


#ifdef __cplusplus
}
#endif

When I compile the header and source file in Visual Studio, no .lib is generated (probably meaning that no symbol is exported).

Is it possible to compile this into a shared library with all symbols exported without modifying the library header file at all? This would make it easy to switch to a newer version when the 3rd party team releases one.

Note:

If I had created the library myself, I would have done this:

#ifdef WIN32
    #ifdef EDFLIB_EXPORTS
        #define EDFLIB_API __declspec(dllexport)
    #else
        #define EDFLIB_API __declspec(dllimport)
    #endif
#else 
    #define EDFLIB_API
#endif

long long EDFLIB_API edftell(int handle, int edfsignal);

It would be possible to modify the library header file with those export flags but I don't want to modify it, I'd like to find an alternative.

Upvotes: 1

Views: 494

Answers (1)

A possible solution for a larger library would be to automatize this task, but that is probably not as easy as it looks (non POD data in C++, enums, ...)

If you compile with some recent GCC (e.g. on Linux), you might customize it with my GCC MELT tool, perhaps by making it generate some ed script to patch the header. It is not an easy task (probably a few weeks of work), and I would recommend going this way only for a quite large library (e.g. of a million lines of C++), and even in such a case, it might not worth the pain to partly automatize the thing....

For your EDFlib the simplest way is to patch their edflib.h file (you'll probably need to add EDFLIB_API at about 30 declarations) and make a pull request on github.

The real issue is that Windows and POSIX (at least Linux and most Unix like AIX, Solaris, HPUX) have incompatible views regarding the role of the linker and the nature of dynamic libraries (and of symbols inside them). Levine's Linkers and Loaders book explains that in details. This is also why I am skeptical about a fully automated approach (the developer is the only one knowing what exactly should be exported, and how to do that; so for your library, you'll need to annotate your declarations for export; at last, making a C-compatible API for a C++ library often requires some redesign and code refactoring).

NB. GCC MELT is a plugin for GCC, and GCC does not allow plugins on Windows (but does allow them on Linux), precisely because of the issue you are encountering: decorating every exported function with __declspec(dllexport) is too painful.

Upvotes: 1

Related Questions