title: C++ preprocessor executing both #ifdef and #ifndef
body: <p>So I'm currently working on something that uses OpenCL. The OpenCL spec provides the users with a directive which must be included before the inclusion of the header (cl.h)</p>
  
  <p><code>#define CL_TARGET_OPENCL_VERSION 110</code></p>
  
  <p>Which basically defines the version they want to use. Suppose I'm making a library and I want my users to define this instead of me defining this inside my files. What I did was.</p>
  
  <pre><code>-----main.cpp---
  #define CL_TARGET_OPENCL_VERSION 110
  #include "library.h"
  -------x---------
  
  ----library.h-----
  #ifdef CL_TARGET_OPENCL_VERSION
  #pragma message("def")
  #endif
  
  #ifndef CL_TARGET_OPENCL_VERSION
  #pragma message("ndef")
  #endif
  .... include other headers.
  --------x---------
  </code></pre>
  
  <p>And the compiler prints both <code>def</code> and <code>ndef</code> messages. And the OpenCL library also throws a warning that it's undefined. I thought that the library header would get substituted into main and it'd only print the <code>def</code> message. Is there anything I understood wrong? </p>
  
  <p>I'm particularly confused as to where does the preprocessor start? If it starts from <code>main.cpp</code> and goes from top to down, then it surely has defined the macro. After that it sees the library inclusion, then it should only print the <code>def</code> message but it prints both. </p>
  
  <p>This leds me to believe the preprocessor does scan the header file before including it in main? Dunno the reason why. Also I have assured that the library header isn't included elsewhere.</p>
  
  <p>One interesting thing I noticed was, if i did this</p>
  
  <pre><code>-----helper.h---
  #define CL_TARGET_OPENCL_VERSION 110    
  -------x---------
  
  ----library.h-----
  #include helper.h    
  #ifdef CL_TARGET_OPENCL_VERSION
  #pragma message("def")
  #endif
  
  #ifndef CL_TARGET_OPENCL_VERSION
  #pragma message("ndef")
  #endif
  .... include other headers.
  --------x---------
  </code></pre>
  
  <p>It prints the <code>def</code> message "twice". If anybody can explain all this I'd be grateful.</p>
  
  <p>EDIT:- The files I'm compiling are <code>main.cpp</code> <code>library.h</code> and <code>library.cpp</code> 
  <code>Library.cpp</code> includes <code>library.h</code> from the start as usual. Maybe this other cpp is causing the problem?</p>