codeblocks and C undefined reference to getline

2019-06-09 18:40发布

I am trying to use getline in C with codeblocks and I am having trouble getting it to run on my machine. The code works on a server I have access too but I have limited wifi access so I need this to work on my machine. I am running windows 8.1 64 bit and codeblocks 13.12 with the gcc compiler.

here is the one of the three sections of code that uses getline, with some of the extra variables removed.

 #include <stdio.h>
 #include <stdlib.h> // For error exit()
 #include <string.h>


 char *cmd_buffer = NULL;
 size_t cmd_buffer_len = 0, bytes_read = 0;
 size_t words_read; // number of items read by sscanf call
 bytes_read = getline(&cmd_buffer, &cmd_buffer_len, stdin);

 if (bytes_read == -1) {
        done = 1; // Hit end of file
 }

the error is very simply:

undefined reference to 'getline'

How can I get this to work?

EDIT I added the headers. I also want to mention that I saw a few posts on this site that did not work for me.

标签: c getline
1条回答
乱世女痞
2楼-- · 2019-06-09 19:15

Perhaps this work.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

ssize_t getdelim(char **linep, size_t *n, int delim, FILE *fp){
    int ch;
    size_t i = 0;
    if(!linep || !n || !fp){
        errno = EINVAL;
        return -1;
    }
    if(*linep == NULL){
        if(NULL==(*linep = malloc(*n=128))){
            *n = 0;
            errno = ENOMEM;
            return -1;
        }
    }
    while((ch = fgetc(fp)) != EOF){
        if(i + 1 >= *n){
            char *temp = realloc(*linep, *n + 128);
            if(!temp){
                errno = ENOMEM;
                return -1;
            }
            *n += 128;
            *linep = temp;
        }
        (*linep)[i++] = ch;
        if(ch == delim)
            break;
    }
    (*linep)[i] = '\0';
    return !i && ch == EOF ? -1 : i;
}
ssize_t getline(char **linep, size_t *n, FILE *fp){
    return getdelim(linep, n, '\n', fp);
}
查看更多
登录 后发表回答