如何使用Glibc功能测试宏?

时间:2016-10-25 11:37:14

标签: c linux libc

如果可用的话,我会使用pthread_setname_np函数。联机帮助页中的代码:

   #define _GNU_SOURCE             /* See feature_test_macros(7) */
   #include <pthread.h>
   int pthread_setname_np(pthread_t thread, const char *name);
   int pthread_getname_np(pthread_t thread,
                          char *name, size_t len);

这样做是否安全(没有包含,没有定义):

#ifdef _GNU_SOURCE
    pthread_setname_np(pthread_self(), "mythread");
#endif

不需要包含,因为我使用的C ++ #include <thread>似乎拉pthreads_GNU_SOURCE始终在libstdc++中启用,如果它被禁用,代码仍会编译。

我错过了什么吗?

1 个答案:

答案 0 :(得分:4)

  

这样做是否安全(没有包含,没有定义):

是。只要您提供<pthread.h>的原型pthread_setname_np,它就是安全的。

  

不需要包含,因为我使用的C ++ #include似乎拉动了pthreads。

libc++使用下面的pthreads库。因此,它适用于pthread.h。但这并不意味着如果您加入pthread.h则不需要<thread>。如果libc++更改底层机制以实现线程,该怎么办?因此,传递pthread.h并不安全,因为它恰好可以通过其他方式获得。