Friday, December 20, 2013

Visual Studio Solution dependent code sections

If you have a Visual Studio project that is part of several solution files (which in most cases is a bad practice - if conditions allow it, rather build a DLL that could be referenced from any solution), you may want to implement solution specific code fragments. In my case, I had a COM interface class that needed to specify a unique CLSID in its IMPLEMENT_OLECREATE call.

The solution: Create a solution specific preprocessor directive. This has been tested in C++ on VS2010:
  1. Define the parameter SOLUTION_$(SolutionName) in Project properties - Configuration Properties - C/C++ - Preprocessor - Preprocessor definitions. Note that the term $(SolutionName) should be written exactly as you see it here - these are MsBuild style variables.
  2. Now in your code, add #ifdef sections checking for the solution name.
  3. If you need to render an error in case none of the solution names defined are found, include a #define SOLUTION_FOUND inside each of your sections and check that it is defined afterwards. If not generate an #error to stop the compiler.
The code will look something like:

#undef SOLUTION_FOUND
#ifdef SOLUTION_MySolutionName1
     (some code specific to that solution)
     #define SOLUTION_FOUND
#endif
#ifdef SOLUTION_MySolutionName2
     (some code specific to that solution)
     #define SOLUTION_FOUND
#endif
#ifndef SOLUTION_FOUND
     #error None of the defined solutions were found. Build can not continue.
#endif

No comments: