views:

314

answers:

2

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?

+4  A: 

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.

Georg Fritzsche
+5  A: 

you might want to try the BASE_FILE macro. This page describes alot of macros which gcc supports.

Andrew Keith
Excellent point. If that results in compile errors under Solaris and you have to support both, add ifdefs to check for BASE_FILE and use __FILE__ if BASE_FILE is not present.
Amigable Clark Kant
Actually this isn't a very good point. __BASE_FILE__ on solaris still includes the path of the file, not just it's name component.
ScaryAardvark