I have a C library with a function
#ifdef __cplusplus
extern "C" {
#endif
void exitWithError(const char* func) {
printf("woopsie in %s", func);
exit(1);
}
#ifdef __cplusplus
}
#endif
exitWithError
is exclusively called by other C code internal to the library.
The C library is always compiled in "C mode", i.e. via g++ -x c ...
, conforming to C99, so cannot feature any C++ code. (I've realised now this makes the #ifdef __cplusplus
check completely superfluous, but ho-hum, not relevant here).
I'm seeking to redefine exitWithError
in a C++14 project which uses this C library, so that I can change how errors are handled (see my related question). This would change the C library's internal behaviour. I am trying to avoid change to the underlying C library code, but that's not a strict necessity.
It turns out I can, in my calling C++ code, simply override the behaviour of exit
with
extern "C" void exit(int status) {
throw 1;
}
This works great, but features the C exitWithError
function calling printf
. I wish to remove that behaviour, so nothing is printed when the C library invokes exitWithError
.
Trying to redefine exitWithError
with the same trick...
extern "C" void exitWithError(const char* func) {
throw 1;
}
causes a duplicate symbol
error during compiling, naturally.
What about exit
enabled it to be redefined? Is there any way to "undefine" exitWithError
so that the calling C++ code can redefine it?
I suspect I could pass an additional compiler flag (e.g. -DSILENCE_FOOL
) when compiling the C library for use in my C++ project, and modify the C library code to
void exitWithError(const char* func) {
#ifndef SILENCE_FOOL
printf("woopsie in %s", func);
#endif
exit(1);
}
but I'd prefer a method without any modification to the C code.
And finally, is there a more sensible way (refactoring the C library) to allow users of the C library to "hook in" or override the exitWithError
behaviour? It's a function invoked when the user supplies incorrect arguments (in my C++ code, I'll override it with std::invalid_argument
).