我有一个带有功能的C库
#ifdef __cplusplus
extern "C" {
#endif
void exitWithError(const char* func) {
printf("woopsie in %s", func);
exit(1);
}
#ifdef __cplusplus
}
#endif
exitWithError
仅由库内部的其他C代码调用。C库始终以“ C模式”编译,即通过g++ -x c ...
进行编译,符合C99,因此不能包含任何C ++代码。 (我现在意识到,这使#ifdef __cplusplus
检查完全多余,但是哼哼,在这里不相关)。
我正在尝试在使用此C库的C ++ 14项目中重新定义exitWithError
,以便可以更改错误的处理方式(请参见related question)。这将改变C库的内部行为。我试图避免更改底层的C库代码,但这不是严格的必要。
事实证明,在调用C ++的代码中,我可以简单地用[]覆盖exit
的行为
extern "C" void exit(int status) {
throw 1;
}
这很好用,但是具有C exitWithError
函数调用printf
的功能。我希望删除该行为,因此C库调用exitWithError
时不会打印任何内容。
[使用相同的技巧尝试重新定义exitWithError
...
extern "C" void exitWithError(const char* func) { throw 1; }
自然会在编译过程中导致
duplicate symbol
错误。
exit
使它能够重新定义呢?有什么办法可以“取消定义” exitWithError
,以便调用的C ++代码可以重新定义它?
[我怀疑我在编译供我的C ++项目使用的C库时可以传递一个附加的编译器标志(例如-DSILENCE_FOOL
),>
void exitWithError(const char* func) { #ifndef SILENCE_FOOL printf("woopsie in %s", func); #endif exit(1); }
但是我更喜欢一种无需对C代码进行任何修改的方法。
最后,还有一种更明智的方法(重构C库)允许C库的用户“挂接”或覆盖
exitWithError
行为吗?当用户提供不正确的参数时,将调用此函数(在我的C ++代码中,我将使用std::invalid_argument
覆盖它)。
我有一个C库,带有一个函数#ifdef __cplusplus extern“ C” {#endif void exitWithError(const char * func){printf(“ woopsie in%s”,func);出口(1); } #ifdef __cplusplus} #endif ...
我可以在我的调用C ++代码中,简单地使用以下方法覆盖exit的行为:>
extern "C" void exit(int status) { throw 1; }