0

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?

2
  • 6
    It's const. Don't do this. If you have some functional requirement, then contact the author and make your case. Otherwise, deal with it. Sorry. Commented Aug 18, 2011 at 23:50
  • I concur. Somebody putting a hard coded path should be shot! Commented Aug 19, 2011 at 0:07

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Is hiding it an option? Like this:

static const char* path = "...";

void f()
{
#if UNIT_TESTING
   static const char* path = "Ha!";
#endif
   cout << path;
}

Comments

0

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;

Comments

0

If you want to be hacky, and have no way to change the source directly, it is possible to use mprotect() on Unix and VirtualProtect() on Win32 to make the page of that array readable/writable/executable as a last resort.

Comments

0

If your system supports it, make the hard coded file a symbolic link to what you want. Something like ln -T /where/i/want/file /some/hardcoded/path/file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.