我正在使用K&R,使用Clang作为我的编译器.
使用Clang编译时,练习1-16会产生"getline'的冲突类型"错误.我猜是因为其中一个默认库有一个getline函数.
在编译K&R练习时,我应该向Clang传递哪些选项以避免包含任何其他内容?
要修改的运动样本是:
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
/* print longest input line */
main()
{
int len; /* current line length */
int max; /* maximum line lenght seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if ( len > max) {
max = len;
copy(longest, line); /* line -> longest */
}
if (max > 0) /* there was a line */
printf("\n\nLength: %d\nString: %s", max -1, longest);
return 0;
}
/* getline: read a line into s, return length */
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;
}
/* copy: copy "from" into "to"; assume to is big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while((to[i] = from[i]) != '\0')
++i;
}
Run Code Online (Sandbox Code Playgroud)
调用时Clang的错误为: cc ex1-16.c -o ex1-16
ex1-16.c:4:5: error: conflicting types for 'getline'
int getline(char line[], int maxline);
^
/usr/include/stdio.h:449:9: note: previous declaration is here
ssize_t getline(char ** __restrict, size_t * __restrict, FILE *...
^
ex1-16.c:17:38: error: too few arguments to function call, expected 3, have 2
while ((len = getline(line, MAXLINE)) > 0)
~~~~~~~ ^
/usr/include/stdio.h:449:1: note: 'getline' declared here
ssize_t getline(char ** __restrict, size_t * __restrict, FILE *...
^
ex1-16.c:29:5: error: conflicting types for 'getline'
int getline(char s[], int lim)
^
/usr/include/stdio.h:449:9: note: previous declaration is here
ssize_t getline(char ** __restrict, size_t * __restrict, FILE *...
^
3 errors generated.
Run Code Online (Sandbox Code Playgroud)
问题在于您的系统已经提供了一个名为的函数getline. man getline应该告诉你它的签名.在我的系统上它是:
ssize_t getline(char ** restrict linep, size_t * restrict linecapp, FILE * restrict stream);
Run Code Online (Sandbox Code Playgroud)
你可以匹配它,或者只是将你的函数重命名为'mygetline'或类似的东西.
或者,如果你可以避免包括stdio.h,你可以完全避免这个问题.
至于你的最后一个问题:
在编译K&R练习时,我应该向Clang传递哪些选项以避免包含任何其他内容?
你不能 - 系统标题就是它们,并且自从K&R于1988年最后一次修订以来可能已经开始了.从那时起已经有多个C标准更新.从某些方面来说,K&R真正开始长期存在.
| 归档时间: |
|
| 查看次数: |
2279 次 |
| 最近记录: |