21

I came across a piece of code which uses #pragma comment(lib, "libraryname").

Why this type of usage as opposed to just linking the library from the properties menu? In what situations is this usage called for? I am in windows using C++ Visual Studio 2010.

It would be nice to see an example which calls for this type of usage.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
user1612986
  • 1,343
  • 3
  • 21
  • 38

3 Answers3

33

The library writer can place a #pragma comment(lib, ...) command in the public header (.h) file. In this case, the client doesn't need to add this library to the linker dependencies list. By including an h-file in the program, the client is automatically linked to the required library.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Alex F
  • 40,884
  • 40
  • 141
  • 206
24

Classic example - linking against different versions of the library:

#if CURRENT_VERSION >= 10
     #pragma comment(lib, "thirdPartyLibV2.0.lib")
#else //version < 10
     #pragma comment(lib, "thirdPartyLibV1.0.lib")
#endif
Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
6

It's contained in the sense that all it takes is including the header file for the associated library to be automatically pulled in. You can even do #ifdef..#endif magic to conditionally bring in the right library based on your environment.

Not everyone is going to be using your MSVC project when starting a new project from scratch, simply being able to #include and have it work is the sign of a well written library.

Blindy
  • 60,429
  • 9
  • 84
  • 123