以下代码编译正常:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
extern int errno ;
int main ( void )
{
FILE *fp;
int errnum;
fp = fopen ("testFile.txt", "rb");
if ( fp == NULL )
{
errnum = errno;
fprintf( stderr, "Value of errno: %d\n", errno );
perror( "Error printed by perror" );
fprintf( stderr, "Error opening file: %s\n", strerror( errnum ) );
exit( 1 );
}
fclose ( fp );
}
Run Code Online (Sandbox Code Playgroud)
但我不能编译它:
gcc-8 -Wall -Wextra -Werror -Wstrict-prototypes
Run Code Online (Sandbox Code Playgroud)
我得到以下内容:
program.c:6:1: error: function declaration isn’t a prototype [-Werror=strict-prototypes]
extern int errno ;
^~~~~~
cc1: all warnings being treated as errors
Run Code Online (Sandbox Code Playgroud)
我该如何避免/解决这个问题?我需要这个编译器标志-Wstrict-prototypes
extern int errno ;
Run Code Online (Sandbox Code Playgroud)
是错的.你应该删除这一行.
发生的事情是你所包含的<errno.h>,它定义了一个叫做的宏errno.实际上 ...
未指定
errno是使用外部链接声明的宏还是标识符.如果为了访问实际对象而禁止宏定义,或者程序使用名称定义标识符errno,则行为是未定义的.
(这是来自C99,7.5 错误<errno.h>.)
在你的情况下errno可能扩展到类似的东西(*__errno()),所以你的声明变成了
extern int (*__errno());
Run Code Online (Sandbox Code Playgroud)
声明__errno为函数(带有未指定的参数列表)返回指针int.