编译错误 error: implicit declaration of function ‘getopt’ [-Werror=implicit-function-declaration] 解决方法

博客讨论了在C编程中遇到的编译错误‘implicit declaration of function ‘getopt’’,解释了该错误的原因是因为在调用getopt函数前未进行正确声明。解决方案是在代码中包含<unistd.h>头文件,或者在编译时使用-gnu99标准。文章还详细分析了getopt.h头文件的内容,强调了__GNU_LIBRARY__宏在其中的作用。
摘要由CSDN通过智能技术生成

背景/需求

编译错误:
error: implicit declaration of function ‘getopt’ [-Werror=implicit-function-declaration]

解释

在某些C标准中,要求函数必须在调用前具有显示声明,例:

void function_a(); //函数声明

int main(){
	function_a();//函数调用
}
void function_a(){
	//函数实现或者叫函数定义
}

若在调用前没有显示声明,则报编译错误,例:

//void function_a(); //函数声明

int main(){
	function_a();//函数调用
}
void function_a(){
	//函数实现或者叫函数定义
}

使用getopt方法时,需要先#include <utistd.h>utistd.h中又进行了#include<getopt.h>的包含,因此,最终getopt函数的声明存在于getopt.h文件中,查看该文件:

  1. cd /usr/include/
  2. vim getopt.h
  3. 注意中间这部分代码:
...
...
#ifdef __GNU_LIBRARY__
/* Many other libraries have conflicting prototypes for getopt, with
   differences in the consts, in stdlib.h.  To avoid compilation
   errors, only prototype getopt for the GNU C library.  */
extern int getopt (int ___argc, char *const *___argv, const char *__shortopts)
       __THROW;

# if defined __need_getopt && defined __USE_POSIX2 \
  && !defined __USE_POSIX_IMPLICITLY && !defined __USE_GNU
/* The GNU getopt has more functionality than the standard version.  The
   additional functionality can be disable at runtime.  This redirection
   helps to also do this at runtime.  */
#  ifdef __REDIRECT
  extern int __REDIRECT_NTH (getopt, (int ___argc, char *const *___argv,
                                      const char *__shortopts),
                             __posix_getopt);
#  else
extern int __posix_getopt (int ___argc, char *const *___argv,
                           const char *__shortopts) __THROW;
#   define getopt __posix_getopt
#  endif
# endif
#else /* not __GNU_LIBRARY__ */
extern int getopt ();
#endif /* __GNU_LIBRARY__ */
...
...

分析可知,只有定义了__GNU_LIBRARY__才可以使用int getopt (int ___argc, char *const *___argv, const char *__shortopts) __THROW;这个函数声明

解决方法

目前我在编译时添加了选项:-std=gnu99而不是-std=c99,实测通过了编译。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值