title: Concatenating an expanded macro and a word using the Fortran preprocessor
body: <p>I'm trying to concatenate a word in the source code with the expansion of a preprocessor macro. Basically I have <code>foo</code> somewhere in the code, and with a <code>#define EXPANSION bar</code> I want to obtain <code>foobar</code>. However, I'm struggling to find a way to do this, which works with all compilers. For the moment I would be happy if it works with gfortran and ifort.</p>
  
  <p>According to its <a href="https://gcc.gnu.org/onlinedocs/cpp/Traditional-macros.html#Traditional-macros" rel="nofollow noreferrer">documentation</a>, the gfortran preprocessor is a C preprocessor running in "traditional mode", which does not have the <code>##</code> token paste operator. However, the same effect can be obtained with an empty C-style <code>/**/</code> comment. The ifort preprocessor seems to behave more like the normal C preprocessor, so normal token pasting does the trick in ifort. Unfortunately the empty <code>/**/</code> comment does not work in ifort, as the comment is replaced by a single space instead.</p>
  
  <p>Here is a little example:</p>
  
  <pre><code>#define EXPANSION bar
  #define CAT(x,y) PASTE(x,y)
  #define PASTE(x,y) x ## y
  
  foo/**/EXPANSION   
  CAT(foo,EXPANSION)
  </code></pre>
  
  <p>For which gfortran produces:</p>
  
  <pre><code>foobar
  foo ## bar
  </code></pre>
  
  <p>While ifort gives me:</p>
  
  <pre><code>foo bar
  foobar
  </code></pre>
  
  <p>Of course I could choose the right way by checking the predefined macros for both compilers:</p>
  
  <pre><code>#ifdef __GFORTRAN__
  foo/**/EXPANSION
  #else
  CAT(foo,EXPANSION)
  #endif
  </code></pre>
  
  <p>This works for both of them, but it's rather ugly to have the preprocessor conditional for every expansion. I would much rather avoid this and have some macro magic only once in the beginning.</p>
  
  <p>I have seen <a href="https://stackoverflow.com/a/31753386/1746785">this answer</a> to another question, which would probably allow me to work around this issue, but I would rather find a solution that does not invoke the preprocessor separately.</p>
  
  <p>I'm not too familiar with the C preprocessor. Maybe there is a simple way to do what I want. Any ideas?</p>
  
  <p><strong>EDIT:</strong> I've already tried something like this:</p>
  
  <pre><code>#define EXPANSION bar
  #define CAT(x,y) PASTE(x,y)
  #ifdef __GFORTRAN__
  #define PASTE(x,y) x/**/y
  #else
  #define PASTE(x,y) x ## y
  #endif
  
  CAT(foo,EXPANSION)
  </code></pre>
  
  <p>Unfortunately this does not work in gfortran where it produces <code>fooEXPANSION</code>. I'm not entirely sure how this works, but apparently the expansion of the <code>CAT</code> macro prevents the expansion of <code>EXPANSION</code> in the same line. I suspect that this is a feature of the "traditional" C preprocessor ...</p>