Reputation: 3986
I'm providing a Microsoft C++ library (static and dynamic) for other clients in my company. My library has a few classes that depend upon functions located in common Windows DLLs whose import libraries aren't included in the project link settings by default.
Rather than add a new import library name to the linker section of every build configuration of my library each time a new dependency like this came up, I thought it would be better in terms of encapsulation of dependencies (and a bit more self-documenting) if I used #pragma comment(lib, ...)
in the .cpp file of the class that depended upon a function from such a DLL, e.g.:
Foo.cpp:
#include <SomeWinLib.h>
#pragma comment(lib, "somewinlib.lib")
... implementation of Foo class ...
...but I found that this was causing link warnings/errors for clients of my library if they were also using SomeWinLib. After doing some reading on the subject, it seems that the recommended/best practice is to let the client who is linking in my library also link in the libraries it depends upon.
I still wanted this to be as automatic/painless as possible for the clients, so rather than just put a list of required import libraries in a readme.txt file (and then sit back and wait for the inevitable phone calls from frustrated developers), I'd just place the #pragma comment
in the Foo.h header file. That way, clients would automatically link in the required library if they included the header file of a class that required it.
Foo.h:
#pragma comment(lib, "somewinlib.lib")
public class Foo
{
However, when I build my library, Foo.cpp includes Foo.h obviously, so it would seem that I need some kind of preprocessor "guard" around the #pragma comment
line in the header file so that it's only seen by the preprocessor when clients include my header file.
Foo.h:
#if !defined(building_my_library)
#pragma comment(lib, "somewinlib.lib")
#endif
public class Foo
{
All of this seems like something that pretty much EVERY library must be doing, yet I don't see examples of this when I Google other open source Windows libraries. That makes me suspect I've missed something somewhere.
Does anyone know if I'm understanding the issues correctly, and if so, whether I'm over-complicating the solution?
Thanks!
Upvotes: 0
Views: 1109
Reputation: 30494
Your last option is more or less what the boost headers do, except they also provide a preprocessor directive to explicitly turn off the auto-linking in case you want to control things yourself:
#if !defined(building_my_library) && !defined(no_auto_link_stuff)
#pragma comment(lib, "somelib.lib")
#endif
Upvotes: 1
Reputation: 63451
A solution that you might not have considered is to use runtime linkage to the DLL via LoadLibrary
and GetProcAddress
, removing the dependence on somewinlib.lib.
Upvotes: 1