3

我的#include <unistd.h>源文件中包含了手册页中指定的标题sync(2)。但是,当我编译我的程序时,我收到以下警告。

./test.c:25:3: 警告:函数'sync'的隐式声明</p>

我在这里错过了什么吗?下面是我的小测试程序的源代码。

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  // Open file ./test.txt and append to it
  int fd = open("./test.txt", O_RDWR | O_CREAT | O_TRUNC, 0);
  if (fd < 0) {
    perror("Failure to open file: ");
    close(fd);
    return(1);
  }
  // Write Hello World\n\0 100 time to ./test.txt
  for (int i = 0; i < 100; ++i) {
    ssize_t bytes = write(fd, "Hello World\n", 12); // 12 for Null '\0'
    if (bytes != 12) {
      perror("Failure to write to file");
      close(fd);
      return(1);
    }
  }

  // Close the file for the exercise
  sync();
  close(fd);

  // This will allow lseek to go back
  fd = open("./test.txt", O_RDWR, 0);
  // This will not allow lseek to go back
  //fd = open("./test.txt", O_RDWR | O_APPEND, 0);
  if (fd < 0) {
    perror("Failure to open files: ");
    close(fd);
    return(1);
  }

  if (lseek(fd, -500, SEEK_END) == -1) {
    perror("Test failed: ");
    close(fd);
    return(1);
  }

  ssize_t bytes = write(fd, "\n\nHello Dog\n\n", 14);
  if(bytes != 14) {
    perror("Failure to write: ");
    close(fd);
    return(1);
  }

  write(1, "Done!!!\n", 9);
  close(fd);


return(0);
}
4

1 回答 1

1

在评论中,我问:

你的编译器选项是什么?您是否设置-D_XOPEN_SOURCE=700(或其他值)?您是否指定-std=c99而不是-std=gnu99,或类似的东西?

对此的回应是:

我曾经-std=c99在 for 循环中允许变量初始化。-std=gnu99似乎成功了。

当您设置 时-std=c99,您必须明确请求所有不属于 C99 的符号(至少是第一个近似值)。如您所见,获取所有符号的最简单方法是使用-std=gnu99。如果您愿意,您可以更精确地使用诸如此标头(我称之为posixver.h)之类的选项:

#ifndef JLSS_ID_POSIXVER_H
#define JLSS_ID_POSIXVER_H

/*
** Include this file before including system headers.  By default, with
** C99 support from the compiler, it requests POSIX 2001 support.  With
** C89 support only, it requests POSIX 1997 support.  Override the
** default behaviour by setting either _XOPEN_SOURCE or _POSIX_C_SOURCE.
*/

/* _XOPEN_SOURCE 700 is loosely equivalent to _POSIX_C_SOURCE 200809L */
/* _XOPEN_SOURCE 600 is loosely equivalent to _POSIX_C_SOURCE 200112L */
/* _XOPEN_SOURCE 500 is loosely equivalent to _POSIX_C_SOURCE 199506L */

#if !defined(_XOPEN_SOURCE) && !defined(_POSIX_C_SOURCE)
#if __STDC_VERSION__ >= 199901L
#define _XOPEN_SOURCE 600   /* SUS v3, POSIX 1003.1 2004 (POSIX 2001 + Corrigenda) */
#else
#define _XOPEN_SOURCE 500   /* SUS v2, POSIX 1003.1 1997 */
#endif /* __STDC_VERSION__ */
#endif /* !_XOPEN_SOURCE && !_POSIX_C_SOURCE */

#endif /* JLSS_ID_POSIXVER_H */

在 Linux 上,您可能更喜欢使用_XOPEN_SOURCEset to 700(对于 POSIX 2008),但我使用的许多机器对此没有很好的支持。

于 2012-07-01T05:53:46.760 回答