代码块和C对getline的未定义引用 [英] codeblocks and C undefined reference to getline
问题描述
我正在尝试在C中使用带有代码块的getline,但在使其在我的计算机上运行时遇到了麻烦.该代码也可以在我也可以访问的服务器上工作,但是我对wifi的访问受到限制,因此我需要在我的机器上工作.我正在使用gcc编译器运行Windows 8.1 64位和代码块13.12.
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.
这是使用getline的代码的三个部分之一,其中删除了一些额外的变量.
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
}
错误非常简单:
undefined reference to 'getline'
如何使它正常工作?
编辑 我添加了标题.我还想提一提,我在该网站上看到了一些对我不起作用的帖子.
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.
推荐答案
也许是可行的.
#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);
}
这篇关于代码块和C对getline的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!