是否有任何提示可以禁止软件工程师在 compile/link 阶段使用 snprintf

Is there any tips to disable software engineer from using snprintf in compile/link stage

我们的客户敦促我们在我们的产品中用 snprintf_s/sscanf_s/strncat_s... 等安全版本替换不安全的 c 函数,例如 snprintf/sscanf/strncat...。

不仅仅是替换,我想知道 compile/link 控制上是否有任何提示可以阻止我们的软件工程师将来使用这些不安全的 c 函数?

谢谢。

首先,您可以像 #define snprintf snprintf_s 一样重新定义它们。他们的签名是相等的。

如果您只想生成一个编译器错误,最简单的方法是始终包含一个 header 并重新定义您想要阻止的所有函数。

这些重新定义可能会产生语法错误,并且还会为用户提供错误原因:

#include <stdio.h>

#define snprintf {"Unsafe! Use snprintf_s instead!"}
#define sscanf {"Unsafe! Use sscanf_s instead!"}
#define strncat {"Unsafe! Use strncat_s instead!"}

您可以创建这样一个 header(我们称之为 force_safe.h)并将其包含在每个源文件的开头。在 GCC 中,您还可以在编译器标志中执行此操作(例如 gcc -iforce_safe.h ...)。

GCC 允许您不想使用的中毒函数。这可以使用 pragma 预处理指令来完成。例如,下面的代码不会在 GCC 上编译,因为 printf 被标记为有毒。

# pragma GCC poison printf

# include <stdio.h>

int main()
{
  printf("Hello World");
  return 0;
}

编辑: 编译指示依赖于编译器。因此,如果您使用 pragma 进行中毒,我建议将它们与 #ifdef 和 #warning 或 #error 结合使用以检查编译器。

#ifdef __GNUC__
# pragma GCC poison printf
#else
#warning Compiling with compiler other than gcc. Use of unsafe functions not tested
#endif

检查编译器,参考How to #ifdef by CompilerType ? GCC or VC++