I'm using Linux, compiling with gcc, getting error: warning: implicit declaration of function ‘fopen_s’, can someone help me fix this?

I'm using Linux, compiling with gcc, getting error: warning: implicit declaration of function ‘fopen_s’, can someone help me fix this?

我正在尝试用 c 语言编写一个简单的边缘检测程序。我正在使用 Red Hat Enterprise Linux Server 7.7 (Maipo) 和 gcc 版本 4.8.5。

这是代码的开头:

#include <stdio.h>

#define size 200

int _tmain(int argc, _TCHAR* argv[])
{
    char filein[size] = "./image.bmp";

    FILE *fin;

    fopen_s(&fin, filein, "rb");

return 0;

}

我最初在使用 _TCHAR* 时遇到了很多问题,所以最终我只用 char 替换了它,我不知道这以后是否会成为问题,但至少它编译并消除了这些错误。现在我收到隐式声明警告。我试图通过添加其他#include 来修复它。

我尝试用以下方法修复它:

#include <stdio.h>
#include <errno.h>
#include <string.h>

#define size 200

int main(int argc, char* argv[])
{
    char filein[size] = "./image.bmp";

    FILE *fin;

    fopen_s(&fin, filein, "rb");

return 0;

}

但是,我仍然收到同样的警告,有人能告诉我我做错了什么吗?

谢谢。

非常感谢,成功了!

#include <stdio.h>

#define size 200

int main(int argc, char* argv[])
{

    char filein[size] = "./image.bmp";

    FILE *fin;

    fin = fopen(filein, "rb");

return 0;

}

_s系列函数是C标准的Annex K中的可选函数,很少有C实现去实现Annex K。Annex K中引入的“安全”函数的实际效用争议很大;只需放弃这些功能并使用标准功能,例如 fopen.

我唯一一次遇到 _s 函数是在为 Windows 编写的代码中,Microsoft 包含了这些不符合标准集的自己的版本在附件 K 中列出。

查看此处查看附件 K 效用的研究:http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm

他们的结论:

Despite more than a decade since the original proposal and nearly ten years since the ratification of ISO/IEC TR 24731-1:2007, and almost five years since the introduction of the Bounds checking interfaces into the C standard, no viable conforming implementations has emerged. The APIs continue to be controversial and requests for implementation continue to be rejected by implementers.

The design of the Bounds checking interfaces, though well-intentioned, suffers from far too many problems to correct. Using the APIs has been seen to lead to worse quality, less secure software than relying on established approaches or modern technologies. More effective and less intrusive approaches have become commonplace and are often preferred by users and security experts alike.

Therefore, we propose that Annex K be either removed from the next revision of the C standard, or deprecated and then removed.

fopen_s 仅在 C11 的可选边界检查库中可用。为了使用它,你需要做:

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <errno.h>
... // rest of program

然后用-std=c11编译,祈祷

因为边界检查库的编译器支持很差,我不确定 gcc 实际实现了多少。 C 程序员之间的普遍共识似乎是边界检查库是危险的,应该避免——它的发布是一个彻底的失败。

你最好完全忘记这个库并使用 fopen