Is there any way to create a hash of string at compile time using the C/C++ preprocessor (or even template-metaprogramming)?
e.g. UNIQUE_SALT("HelloWord", 3DES);
The idea is that HelloWorld will not be present in the compiled binary, just a hash.
Edit: There are many of these declarations spread over a large codebase.
This can be done with Boost.MPL but it might not be the type of hash you are after.
http://arcticinteractive.com/2009/04/18/compile-time-string-hashing-boost-mpl/
Why not make generating the hash part of your build process? You can write a simple batch file to generate the hash (assuming you have a program to do such a thing - if not, write one) and have it output a preprocessor directive something like:
to a .h file that then gets #included in your application.
Answers claiming that strings cannot be parsed at compile time are wrong. Character pointers can't be parsed at compile time, but string literals are not character pointers; they are arrays of characters whose length is part of the type. It's easy to forget that, because in most cases it's far more useful to let them decay into a char*. But they don't start out that way.
Ah, but how to actually define a function that takes a fixed-length character array, especially if we'd really rather use it on strings of arbitrary length? That's where template argument deduction comes in super handy:
That should get you started. Obviously the hash itself needs to be simple enough for compile-time computation, but that's probably ok.
While this is not a proper answer to the question, see this blog entry for an example of a hash function for strings of up to 256 characters implemented purely as a C macro:
http://lolengine.net/blog/2011/12/20/cpp-constant-string-hash
Here is the actual code from the blog:
If you know ahead of time that you will only use it for static strings you could replace strlen() with sizeof().
I stumbled across a solution using the good 'ol C++ standard (I'm not sure what version it's considered, but let's just say this solution works in Visual Studio). Here's the link: link.
Also, here's a short version of a JSHash function using the above technique. The shown one here supports up to 4 characters, though you can add as many as you want.
As noted, because this is a compile time hash, you can do something like this:
It's not the most elegant solution, so I plan on doing more research in this area, however as this is the only thing I've gotten to work in VisualStudio2010 I'm a little limited as far as my current project is concerned.
This is how I do this compile-time string hash with C++0x:
Usage: