I'm starting with this code:
void func1() {
char tmpfile[] = "/tmp/tmpXXXXXX";
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
void func2() {
char tmpfile[] = "/tmp/tmpXXXXXX";
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
I'd like to refactor this to pull out the shared "/tmp/tmpXXXXXX"
constant. Here is an attempt:
constexpr char kTmpfile[] = "/tmp/tmpXXXXXX";
void func1() {
char tmpfile[] = kTmpfile;
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
void func2() {
char tmpfile[] = kTmpfile;
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
However, this doesn't compile. Changing tmpfile[]
to tmpfile[sizeof(kTmpfile)]
also doesn't work.
The below does work, but it uses a macro which is discouraged by my company's style guide (which is based on the Google Style Guide).
#define TMPFILE "/tmp/tmpXXXXXX"
void func1() {
char tmpfile[] = TMPFILE;
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
void func2() {
char tmpfile[] = TMPFILE;
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
Is there any way to write this "nicely"? Without having to use a macro or hardcode the size? Or is the macro the best option for readability and maintainability?