To start off, I don't get this issue when I compile/"make" the code on a Linux machine which I connect to remotely. I'm experiencing it only on my Windows laptop with Mingw installed -- which I believe is causing the issue.
$ 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:
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? Thank you 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.
For some reason the Windows MingW distribution still maintains gets
and because of that you have a redefinition problem.
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.
As the error says the gets()
function is already defined in stdio.h
.
One trick you can do is put something like this:
#define gets MY_gets
before your definition of the gets()
function.
That way you are actually defining a MY_gets()
function which causes no conflict. And when you call gets()
later on in your code you are actually calling 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.