Why do I get a "conflicting types for getline" error when compiling the longest line example in chapter 1 of K&R2?

The conflicting function getline() is a GNU/POSIX extension.

K&R state that they address specifically ANSI C in their book (c.f.), which does not provide this function.

The authors present the complete guide to ANSI standard C language programming.

In order set gcc into "K&R compatibility mode" you can specify the ANSI or ISO modes for compilation. These are intended to disable extensions, e.g., the function getline(). This could eventually eliminate the need to edit other examples provided by K&R as well.

For example, the following compile just fine:

$ gcc test.c -ansi
$ gcc test.c -std=c89

(Except that they complain about the implicit default return type of main() with -Wall.)

Apparently on some systems, these modes may not work as presented here (apparently some version(s) of Mac OS fail to correctly disable all extensions). I tested this successfully on my machine:

$ gcc --version
gcc (GCC) 4.7.2 20121109 (Red Hat 4.7.2-8)
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

The problem is that getline() is a standard library function. (defined in stdio.h) Your function has the same name and is thus clashing with it.

The solution is to simply change the name.


This is because the stdio.h have a getline() function.

So a simple thing to make this work would be to rename your function to my_getline()

Both getline() and getdelim() were originally GNU extensions. They were standardized in POSIX.1-2008.