title: Are preprocessor-based feature switches necessary in C++ libraries?
body: <p>I have been looking at some mature C++ projects and I have noticed a pattern where preprocessor flags are used to enable features at compile-time. </p>
  
  <p>For example: </p>
  
  <pre><code>#ifdef MY_WIDGET
  Widget createMyWidget() {
      // etc... 
  }
  #endif
  </code></pre>
  
  <p>Then elsewhere in the code: </p>
  
  <pre><code>#ifdef MY_WIDGET
  widgets.push_back(createMyWidget());
  // etc... 
  #endif
  </code></pre>
  
  <p>To me this seems unnecessary since we can employ a strategy pattern, either using inheritance or <code>std::function</code>. </p>
  
  <p>Currently the user's application might look like this (where the library has been compiled with <code>-DMY_WIDGET</code>): </p>
  
  <pre><code>#include &lt;library/startApp.hpp&gt;
  
  int main() {
    startApp(); // createMyWidget will be called by the library
    return 0;
  }
  </code></pre>
  
  <p>But instead, we could redesign the library so that the user can write this: </p>
  
  <pre><code>#include &lt;library/startApp.hpp&gt;
  #include &lt;my-widget-plugin/createMyWidget.hpp&gt;
  
  int main() {
    const std::vector&lt;Widget&gt; widgets = { createMyWidget() };
    startApp(widgets);
    return 0;
  }
  </code></pre>
  
  <p>Now the library does not have any compilation switches, which makes the build much simpler, but we can still extend the functionality of the library. This also prevents potential confusion in the case where someone compiles a library without a feature but then tries to use that feature mistakenly. </p>
  
  <p>Appropriate use of <code>const</code> allows the compiled binary to be as efficient in either case. If the widgets should be instantiated lazily, we can pass a vector of factories. </p>
  
  <p>Are preprocessor-based feature switches simply a less controlled version of the strategy pattern? </p>