4

私はコンパイラとして Clang を使用して、K&R を使用しています。

Clang でコンパイルすると、演習 1-16 で「'getline' のタイプが競合しています」というエラーが発生します。デフォルトのライブラリの 1 つに 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;
}

次のように呼び出されたときの 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.
4

2 に答える 2

6

問題は、システムが という関数をすでに提供していることgetlineです。 man getlineその署名を教えてください。私のシステムでは次のとおりです。

ssize_t getline(char ** restrict linep, size_t * restrict linecapp, FILE * restrict stream);

それに一致させるか、関数の名前を「mygetline」またはそのような名前に変更することができます。

あるいは、 を含めないようにすればstdio.h、問題を完全に回避できます。

最後の質問について:

K&R 演習をコンパイルするときに、他に何も含まれないようにするには、どのオプションを Clang に渡す必要がありますか?

できません。システム ヘッダーは現状のものであり、K&R が 1988 年に最後に改訂されてからおそらく移動しています。それ以来、複数の C 標準の更新が行われています。いくつかの点で、K&R は本当に長くなり始めています。

于 2013-07-02T20:00:21.433 に答える