我正在寻找一种方法来重新定义一组 POSIX 函数,然后通过调用原始函数来结束重新定义。这个想法是我正在尝试创建一个层,该层可以根据哪个“配置文件”处于活动状态来限制可以调用哪些 OS API。此“配置文件”确定允许使用哪些功能集,并且不应使用任何未指定的功能。
例如,如果在一个配置文件中我不允许使用 strcpy,我希望能够导致编译时错误(通过 static_assert)或在屏幕上打印一些内容“此配置文件中不允许使用 strcpy”,例如以下:
MY_string.h
#include <string.h>
char *strcpy(char *restrict s1, const char *restrict s2)
{
#if defined(PROFILE_PASS_THROUGH)
printf("strcpy is not allowed in this profile\n");
return strcpy(s1, s2);
#elif defined(PROFILE_ERROR)
static_assesrt(0, "strcpy is not allowed in this profile\n");
return 0;
#else
return strcpy(s1, s2);
#endif
}
所以在 main.cpp 中我可以使用 MY_string.h
#define PROFILE_PASS_THROUGH
#include "MY_string.h"
int main()
{
char temp1[10];
char temp2[10];
sprintf(temp2, "Testing");
if (0 = strcpy(temp1, temp2))
{
printf("temp1 is %s\n", temp1);
}
return 0;
}
现在我意识到由于 strcpy 的重新定义,我上面编写的代码将无法正确编译,但是有没有办法在不使用宏或创建我自己的标准 c 和 c++ 库的情况下允许这种功能?