[英]Mingw -- Conflicting types for function due to previous declaration
To start off, I don't get this issue when I compile/"make" the code on a Linux machine which I connect to remotely.首先,当我在远程连接的 Linux 机器上编译/“制作”代码时,我没有遇到这个问题。 I'm experiencing it only on my Windows laptop with Mingw installed -- which I believe is causing the issue.我只在安装了 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
Here's the gets() code as requested:这是所要求的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] = '\0';
return buf;
}
Is there a way to fix this without changing the gets function name?有没有办法在不更改gets函数名称的情况下解决这个问题? Thank you sm谢谢sm
Your code works on Linux's gcc because the gets
function was removed , as it should, since it was deprecated in the C99 standard and removed with C11.您的代码可以在 Linux 的 gcc 上运行,因为gets
函数已被删除,因为它在 C99 标准中已被弃用并随 C11 被删除。
For some reason the Windows MingW distribution still maintains gets
and because of that you have a redefinition problem.出于某种原因,在Windows的MingW分布仍保持gets
正因为你有一个重新定义的问题。
So unfortunately you can't use that function name, unless you remove it by hand from stdio.h
, as C doesn't allow for function overloading.所以不幸的是你不能使用那个函数名,除非你从stdio.h
手动删除它,因为 C 不允许函数重载。
As the error says the gets()
function is already defined in stdio.h
.正如错误所说, gets()
函数已在stdio.h
定义。
One trick you can do is put something like this:你可以做的一个技巧是把这样的东西:
#define gets MY_gets
before your definition of the gets()
function.在您定义gets()
函数之前。
That way you are actually defining a MY_gets()
function which causes no conflict.这样你实际上定义了一个MY_gets()
函数,它不会引起冲突。 And when you call gets()
later on in your code you are actually calling MY_gets()
.当您稍后在代码中调用gets()
时,您实际上是在调用MY_gets()
。
If you define gets()
in a header file you should include stdio.h
first and then put #define gets MY_gets
before the declaration of gets()
in the header file.如果在头文件中定义gets()
,则应首先包含stdio.h
,然后在头文件中的gets()
声明之前放置#define gets MY_gets
。
Though I don't see why you want to refine this function if it already exists.虽然我不明白你为什么要改进这个功能,如果它已经存在的话。 It makes more sense to only define it if needed and surround the function with something like #ifndef HAVE_GETS
and endif
where HAVE_GETS
should be defined based on tests done in the configure/build system.仅在需要时定义它并用诸如#ifndef HAVE_GETS
和endif
类的东西来定义它更有意义,其中HAVE_GETS
应该根据在配置/构建系统中完成的测试来定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.