首页 > 解决方案 > 仅当它在 C 中可用时才包含头文件?

问题描述

我想将 pthread 的逻辑添加到我为 C 编写的小型分析库中。但是,如果 pthread 可用,我只想执行与 pthread 相关的逻辑。

有没有使用预处理器指令的编程方式来做到这一点?

我想它看起来像:

#ifdef pthread_h
#include <pthread.h>
#endif

. . .


#ifdef pthread_h
// pthread specific logic here
#endif

但是我不确定并且不知道该怎么做的部分是

#ifdef pthread_h

如果我还没有包含pthread.hpthread_h则不可用。正确的?

有没有办法只在头文件可用时才包含它?也许我可以通过这种方式实现我正在寻找的结果。


我想要的结果是在分析数据中包含有关当前线程 ID 的信息,但前提是库有 pthread 可供调用pthread_self()

标签: cmacrosincludec-preprocessorheader-files

解决方案


有没有办法只在头文件可用的情况下才包含它?也许我可以通过这种方式实现我正在寻找的结果。

是的。如果您的编译器支持,您可以使用 ie__has_include宏:

#if defined __has_include
#  if __has_include (<pthread.h>)
#    include <pthread.h>
#  endif
#endif

...

#if defined __has_include
#  if __has_include (<pthread.h>)
#    // pthread specific logic here
#  endif
#endif

边注:

  • “...如果 pthread 在编译时实际上已被链接。”

链接过程不在编译时完成。它出现在编译之后。C 预处理器甚至在编译之前就完成了它的工作。


推荐阅读