ScaryAardvark ScaryAardvark - 1 month ago 20
C Question

__FILE__ macro manipulation handling at compile time

One of the issues I have had in porting some stuff from Solaris to Linux is that the Solaris compiler expands the macro

__FILE__
during preprocessing to the file name (e.g. MyFile.cpp) whereas gcc on Linux expandeds out to the full path (e.g. /home/user/MyFile.cpp). This can be reasonably easily resolved using basename() but....if you're using it a lot, then all those calls to basename() have got to add up, right?

Here's the question. Is there a way using templates and static metaprogramming, to run basename() or similar at compile time? Since
__FILE__
is constant and known at compile time this might make it easier. What do you think? Can it be done?

Answer

There is currently no way of doing full string processing at compile time (the maximum we can work with in templates are the weird four-character-literals).

Why not simply save the processed name statically, e.g.:

namespace 
{
  const std::string& thisFile() 
  {
      static const std::string s(prepocessFileName(__FILE__));
      return s;
  }
}

This way you are only doing the work once per file. Of course you can also wrap this into a macro etc.