首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >getc是如何定义的?

getc是如何定义的?
EN

Stack Overflow用户
提问于 2020-06-14 06:58:23
回答 3查看 188关注 0票数 0

我听说getcfgetc不同,它是一个宏,所以我想看看这个。我在哪里可以找到getc的源代码?

EN

回答 3

Stack Overflow用户

发布于 2020-06-14 07:05:44

我相信from C99 standard about getc()这一部分已经说明了一切:

函数与fgetc等效,不同之处在于,如果它是作为宏实现的,它可能会对流进行多次求值,因此参数永远不应该是有副作用的表达式。

这样做:

代码语言:javascript
复制
// a function that does some side effects
// and also returns a FILE*
FILE *func_that_returns_file();

int main() {
   getc(func_that_returns_file())
}

,因为它可能会多次调用该函数。

票数 4
EN

Stack Overflow用户

发布于 2020-06-14 07:09:41

正如注释中所指出的,getc可以实现为宏,但不是必需的。相反,它必须有一个函数实现。这些都不是getc所特有的。来自C99规范的7.1.4/1节:

头中声明的任何函数都可以额外实现为头中定义的类似函数的宏,因此,如果库函数在包含其头时显式声明,则可以使用下面所示的技术之一来确保声明不受此类宏的影响。函数的任何宏定义都可以通过将函数的名称括在括号中来在本地取消,因为该名称后面没有表示宏函数名展开的左括号。出于相同的语法原因,允许使用库函数的地址,即使它也被定义为宏。

因此,事实上,虽然C实现可能选择将一些库函数实现为宏,但它也必须提供非宏实现,以便它们可以用作函数指针(例如,如果您将getc作为参数传递给另一个函数)。

票数 3
EN

Stack Overflow用户

发布于 2020-06-15 05:44:48

来自:https://code.woboq.org/userspace/glibc/libio/getc.c.html

getc()的源代码如下:

代码语言:javascript
复制
/* Copyright (C) 1993-2019 Free Software Foundation, Inc.
   This file is part of the GNU C Library.
   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <http://www.gnu.org/licenses/>.
   As a special exception, if you link the code in this file with
   files compiled with a GNU compiler to produce an executable,
   that does not cause the resulting executable to be covered by
   the GNU Lesser General Public License.  This exception does not
   however invalidate any other reasons why the executable file
   might be covered by the GNU Lesser General Public License.
   This exception applies to code released by its copyright holders
   in files containing the exception.  */
#include "libioP.h"
#include "stdio.h"
#undef _IO_getc
int
_IO_getc (FILE *fp)
{
  int result;
  CHECK_FILE (fp, EOF);
  if (!_IO_need_lock (fp))
    return _IO_getc_unlocked (fp);
  _IO_acquire_lock (fp);
  result = _IO_getc_unlocked (fp);
  _IO_release_lock (fp);
  return result;
}
#undef getc
weak_alias (_IO_getc, getc)
weak_alias (_IO_getc, fgetc)
#ifndef _IO_MTSAFE_IO
#undef getc_unlocked
weak_alias (_IO_getc, getc_unlocked)
weak_alias (_IO_getc, fgetc_unlocked)
#endif
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62366500

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档