I need to use getline() in C, but when i write:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
char *line;
getline(&line, NULL, stdin);
free(line);
return (0);
}
compiler writes error: getline was not declared in this scope what can i do? Isn't getline is delared in stdio.h? I never had this kind of problem before.
I use GCC GNU Compiler.
You need to define
_GNU_SOURCEto use this function, either define it before the inclusion ofstdio.hor pass it to the compile as-D_GNU_SOURCEsince this is a GNU extension function.Another possible cause is that your GLIBC does not have this function, so either try:
grepping for it in
/usr/include/stdio.hTest for
_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700like the manual page says (after includingfeatures.h)The following implementation may work (Un-tested):
Errors you currently have:
You're not freeing
lineafter you've used itYou're not passing
lineby reference, since the function prototype is:ssize_t getline(char **lineptr, size_t *n, FILE *stream);hencechar **lineptr