As I am going through a sample code in the book (program that reads a set of text lines and prints the longest):
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max){
max = len;
copy(longest, line);
}
if (max > 0)
printf("%s", longest);
return 0;
}
int getline(char s[], int lim)
{
int c, i;
for (i=0; i<lim-1 && (c=getchar()) !=EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
gcc spits out
longestline.c:4:5: error: conflicting types for ‘getline’
4 | int getline(char line[], int maxline);
| ^~~~~~~
In file included from longestline.c:1:
/usr/include/stdio.h:616:18: note: previous declaration of ‘getline’ was here
616 | extern __ssize_t getline (char **__restrict __lineptr,
| ^~~~~~~
longestline.c:7:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
7 | main()
| ^~~~
longestline.c:25:5: error: conflicting types for ‘getline’
25 | int getline(char s[], int lim)
| ^~~~~~~
In file included from longestline.c:1:
/usr/include/stdio.h:616:18: note: previous declaration of ‘getline’ was here
616 | extern __ssize_t getline (char **__restrict __lineptr,
| ^~~~~~~
that is the exact sample from the book, so what can be done here? I think this might be due to this book being quite outdated, what is the solution?
The problem is that there is a POSIX function called getline
. Your compiler is defaulting to POSIX compatibility instead of ISO C compatibility. To work around it you can either:
For gcc use a switch such as -std=c11
; or it is also possible to control dialect on a per-file basis with feature test macros .
It turns out getline
is defined in stdio.h,
simply renamed the function:
int gettline(char line[], int maxline);
int getline(char s[], int lim)
.
#include <stdio.h>
#define MAXLINE 1000
int gettline(char line[], int maxline);
void copy(char to[], char from[]);
main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = gettline(line, MAXLINE)) > 0)
if (len > max){
max = len;
copy(longest, line);
}
if (max > 0)
printf("%s", longest);
return 0;
}
int gettline(char s[], int lim)
{
int c, i;
for (i=0; i<lim-1 && (c=getchar()) !=EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
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.