Mingw——由于之前的声明导致函数类型冲突
Mingw -- Conflicting types for function due to previous declaration
首先,当我在远程连接的 Linux 机器上编译/“制作”代码时,我没有遇到这个问题。我只在安装了 Mingw 的 Windows 笔记本电脑上遇到过这个问题——我认为这是导致问题的原因。
$ make
gcc -c parser.c
parser.c:34:7: error: conflicting types for 'gets'
34 | char* gets(char *buf, int max)
| ^~~~
In file included from parser.h:4,
from parser.c:1:
c:\mingw\include\stdio.h:709:41: note: previous declaration of 'gets' was here
709 | _CRTIMP __cdecl __MINGW_NOTHROW char * gets (char *);
| ^~~~
Makefile:13: recipe for target 'parser.o' failed
make: *** [parser.o] Error 1
这是请求的 gets() 代码:
char* gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
cc = read(0, &c, 1);
if(cc < 1) break;
//c = getchar();
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '[=11=]';
return buf;
}
有没有办法在不更改 gets 函数名称的情况下解决这个问题?谢谢sm
您的代码适用于 Linux 的 gcc,因为 the gets
function was removed,因为它在 C99 标准中已被弃用并随 C11 一起删除。
出于某种原因,Windows MingW 发行版仍然保持 gets
,因此您遇到了重新定义问题。
很遗憾,您不能使用该函数名称,除非您从 stdio.h
中手动删除它,因为 C 不允许函数重载。
如错误所述,gets()
函数已在 stdio.h
中定义。
你可以做的一个技巧是像这样放一些东西:
#define gets MY_gets
在您定义 gets()
函数之前。
这样你实际上定义了一个 MY_gets()
函数,不会引起冲突。当您稍后在代码中调用 gets()
时,您实际上是在调用 MY_gets()
.
如果您在头文件中定义 gets()
,您应该首先包含 stdio.h
,然后在头文件中的 gets()
声明之前放置 #define gets MY_gets
。
虽然我不明白你为什么要优化这个功能,如果它已经存在的话。
只在需要时定义它并用 #ifndef HAVE_GETS
和 endif
之类的东西包围函数更有意义,其中 HAVE_GETS
应该根据在 configure/build 系统中完成的测试来定义。
首先,当我在远程连接的 Linux 机器上编译/“制作”代码时,我没有遇到这个问题。我只在安装了 Mingw 的 Windows 笔记本电脑上遇到过这个问题——我认为这是导致问题的原因。
$ make
gcc -c parser.c
parser.c:34:7: error: conflicting types for 'gets'
34 | char* gets(char *buf, int max)
| ^~~~
In file included from parser.h:4,
from parser.c:1:
c:\mingw\include\stdio.h:709:41: note: previous declaration of 'gets' was here
709 | _CRTIMP __cdecl __MINGW_NOTHROW char * gets (char *);
| ^~~~
Makefile:13: recipe for target 'parser.o' failed
make: *** [parser.o] Error 1
这是请求的 gets() 代码:
char* gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
cc = read(0, &c, 1);
if(cc < 1) break;
//c = getchar();
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '[=11=]';
return buf;
}
有没有办法在不更改 gets 函数名称的情况下解决这个问题?谢谢sm
您的代码适用于 Linux 的 gcc,因为 the gets
function was removed,因为它在 C99 标准中已被弃用并随 C11 一起删除。
出于某种原因,Windows MingW 发行版仍然保持 gets
,因此您遇到了重新定义问题。
很遗憾,您不能使用该函数名称,除非您从 stdio.h
中手动删除它,因为 C 不允许函数重载。
如错误所述,gets()
函数已在 stdio.h
中定义。
你可以做的一个技巧是像这样放一些东西:
#define gets MY_gets
在您定义 gets()
函数之前。
这样你实际上定义了一个 MY_gets()
函数,不会引起冲突。当您稍后在代码中调用 gets()
时,您实际上是在调用 MY_gets()
.
如果您在头文件中定义 gets()
,您应该首先包含 stdio.h
,然后在头文件中的 gets()
声明之前放置 #define gets MY_gets
。
虽然我不明白你为什么要优化这个功能,如果它已经存在的话。
只在需要时定义它并用 #ifndef HAVE_GETS
和 endif
之类的东西包围函数更有意义,其中 HAVE_GETS
应该根据在 configure/build 系统中完成的测试来定义。