I was writing unit tests and I needed to override the path in "static const char[] path = "/some/hardcoded/path" to something else. Whats the best way to do it. I think it can be done by LD_PRELOAD but it requires me to create another library. Is there any other easy way to do this?
5 Answers
Comment it out and add in your own path.
You don't want to un-const something.
If you need, put it into a preprocessor block:
#ifndef __UNIT_TEST
static const char[] path = "/some/hardcoded/path";
#else
static const char[] path = "/some_other/hardcoded/path";
#endif
Then it won't fail on the original programmer's system either.
Comments
Changing the value of such a string at execution time is undefined behavior. On many systems, the implementation-defined response is to drop core (segmentation fault). That said, a formerly common paradigm in many UNIX applications was to have hard-coded but configurable pathnames. The name is set at compile time rather than execution time:
static const char * path = SOME_PREPROCESSOR_NAME;
const. Don't do this. If you have some functional requirement, then contact the author and make your case. Otherwise, deal with it. Sorry.