这两天在做64位移植的工作,在编译某组建时报错如下:
error: implicit declaration of function ‘pthread_mutexattr_settype’
造成这个错误的原因网上已经说得很明白了,就是由于没有添加所需要的头文件导致的,于是找到了函数pthread_mutexattr_settype的声明(在 <pthread.h> 文件中):
#ifdef __USE_UNIX98 /* Return in *KIND the mutex kind attribute in *ATTR. */ extern int pthread_mutexattr_gettype (__const pthread_mutexattr_t *__restrict __attr, int *__restrict __kind) __THROW; /* Set the mutex kind attribute in *ATTR to KIND (either PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK, or PTHREAD_MUTEX_DEFAULT). */ extern int pthread_mutexattr_settype (pthread_mutexattr_t *__attr, int __kind) __THROW; /* Return in *PROTOCOL the mutex protocol attribute in *ATTR. */ extern int pthread_mutexattr_getprotocol (__const pthread_mutexattr_t *__restrict __attr, int *__restrict __protocol) __THROW; /* Set the mutex protocol attribute in *ATTR to PROTOCOL (either PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT, or PTHREAD_PRIO_PROTECT). */ extern int pthread_mutexattr_setprotocol (pthread_mutexattr_t *__attr, int __protocol) __THROW; /* Return in *PRIOCEILING the mutex prioceiling attribute in *ATTR. */ extern int pthread_mutexattr_getprioceiling (__const pthread_mutexattr_t *__restrict __attr, int *__restrict __prioceiling) __THROW; /* Set the mutex prioceiling attribute in *ATTR to PRIOCEILING. */ extern int pthread_mutexattr_setprioceiling (pthread_mutexattr_t *__attr, int __prioceiling) __THROW; #endif
如果没有定义__USE_UNIX98这个宏,那就没有声明pthread_mutexattr_settype,后面也就无法使用该函数。接下来,翻阅了一番资料后发现,/usr/include/features.h头文件中有如下代码:
#ifdef _XOPEN_SOURCE # define __USE_XOPEN 1 # if (_XOPEN_SOURCE - 0) >= 500 # define __USE_XOPEN_EXTENDED 1 # define __USE_UNIX98 1 # undef _LARGEFILE_SOURCE # define _LARGEFILE_SOURCE 1 # if (_XOPEN_SOURCE - 0) >= 600 # if (_XOPEN_SOURCE - 0) >= 700 # define __USE_XOPEN2K8 1 # endif # define __USE_XOPEN2K 1 # undef __USE_ISOC99 # define __USE_ISOC99 1 # endif # else # ifdef _XOPEN_SOURCE_EXTENDED # define __USE_XOPEN_EXTENDED 1 # endif # endif #endif
这样的话,pthread.h头文件中的pthread_mutexattr_settype函数也就会被声明。
而features.h中还有另一段代码:
/* If _GNU_SOURCE was defined by the user, turn on all the other features. */ #ifdef _GNU_SOURCE # undef _ISOC99_SOURCE # define _ISOC99_SOURCE 1 # undef _POSIX_SOURCE # define _POSIX_SOURCE 1 # undef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L # undef _XOPEN_SOURCE # define _XOPEN_SOURCE 700 # undef _XOPEN_SOURCE_EXTENDED # define _XOPEN_SOURCE_EXTENDED 1 # undef _LARGEFILE64_SOURCE # define _LARGEFILE64_SOURCE 1 # undef _BSD_SOURCE # define _BSD_SOURCE 1 # undef _SVID_SOURCE # define _SVID_SOURCE 1 # undef _ATFILE_SOURCE # define _ATFILE_SOURCE 1 #endif
也就是说,_GUN_SOURCE宏一旦被定义,就会定义上面几种宏,其中会定义_XOPEN_SOURCE为700,正好满足了定义_GNU_SOURCE宏的条件。所以我也可以定义宏_GNU_SOURCE.
-D_XOPEN_SOURCE=500 或 -D_GNU_SOURCE 即可解决。
其实还有另一种方法解决error: implicit declaration of function ‘pthread_mutexattr_settype’ 错误,那就是在编译的时候把编译选项“-Werror-implicit-function-declaration”去掉即可,但是不推荐去掉该选项!