c - 仅当它在 C 中可用时才包含头文件?
问题描述
我想将 pthread 的逻辑添加到我为 C 编写的小型分析库中。但是,如果 pthread 可用,我只想执行与 pthread 相关的逻辑。
有没有使用预处理器指令的编程方式来做到这一点?
我想它看起来像:
#ifdef pthread_h
#include <pthread.h>
#endif
. . .
#ifdef pthread_h
// pthread specific logic here
#endif
但是我不确定并且不知道该怎么做的部分是
#ifdef pthread_h
如果我还没有包含pthread.h
,pthread_h
则不可用。正确的?
有没有办法只在头文件可用时才包含它?也许我可以通过这种方式实现我正在寻找的结果。
我想要的结果是在分析数据中包含有关当前线程 ID 的信息,但前提是库有 pthread 可供调用pthread_self()
。
解决方案
“有没有办法只在头文件可用的情况下才包含它?也许我可以通过这种方式实现我正在寻找的结果。 ”
是的。如果您的编译器支持,您可以使用 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 预处理器甚至在编译之前就完成了它的工作。
推荐阅读
- vue.js - 如何在 html 输入中使用 VueJs 添加最大日期?
- html - 具有绝对位置的父级不包装子元素
- java - Toast 未在 android studio 中显示
- kubernetes - 使用运行时指定的资源详细信息运行 Kubectl DevOps 任务
- javascript - 避免迭代外循环
- performance - 可以用 arrayfun() (或其他方式)加速这个 gpuArray 计算吗?
- android - 使用 FileProvider 和 ActivityResultContracts.TakePicture() 的问题
- javascript - 遍历包含普通值和对象和数组形式的属性的树(递归)
- python - 计算多个移动平均交叉
- r - R 等价于 Stata `tabulate , generate()` 命令