Archive for July, 2010

Linking .lib files in C++

Thursday, July 22nd, 2010

Sooner or later you will need to link static external library files (.lib files), when developing a larger project. Microsoft C++ can do this in several ways:

  1. Link settings in the project properties
  2. Adding the file to the source file tree
  3. Using a #pragma

So far I’ve mostly used 1 & 2, because they’re the easiest and most obvious ways. Solution 2 can even be used conditionally for certain build types (by using the “exclude for this build” option).

But with the projects getting more complex, I found that solution 3 is the best and switched projects to that. The reason is that different combinations of project types (debug/release 32/64 Bit) are otherwise quite difficult  to handle.

With #pragma’s is does take some space in one your .cpp-files, but at least the different conditions are easy to understand and verify:

#ifdef _WIN64
  #ifdef _DEBUG
    #pragma comment(lib, "C:\MyPath\\MyDebug64.lib")
  #else
    #pragma comment(lib, "C:\MyPath\\MyRelease64.lib")
  #endif
#else
  #ifdef _DEBUG
    #pragma comment(lib, "C:\MyPath\\MyDebug32.lib")
  #else
    #pragma comment(lib, "C:\MyPath\\MyRelease32.lib")
  #endif
#endif