[我想将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_self()
的pthread。
pthread_h
是宏定义。您定义它以允许预处理器做什么。
示例
#define PRINT_HELLO
int main()
{
#ifdef PRINT_HELLO
printf("Hello ");
#endif
#ifdef PRINT_WORLD
printf("world\n");
#endif
}
预处理器将输出此代码(预处理在编译之前进行:
int main()
{
printf("Hello ");
}
将由编译器和链接器编译和链接。
“ 只有在头文件可用的情况下,才有办法包括它吗?也许我可以以这种方式获得想要的结果。”
您可以使用f.e. __has_include
宏:
#if __has_include(<phtread.h>)
# include "myinclude.h"
#endif
旧答案:
如果要包含头文件pthread_h
,则需要定义marco #define pthread_h
(通过使用pthread.h
。
[此后,使用#ifdef pthread_h
,您检查是否定义了宏pthread_h
,并且是否包含标头pthread_h
。
如果已定义,则将编译#ifdef pthread_h
和#endif
之间的代码并将其插入到相应的目标文件中。
例如:
#define pthread_h // define macro pthread_h if we want to include pthread.h.
#include <pthread.h>
...
#ifdef pthread_h // check whether pthread_h was defined/ pthread.h was included.
// pthread specific logic here
#endif
可执行演示(Online Test)
#define pthread_h // define macro pthread_h if we want to include pthread.h.
#include <pthread.h>
#include <stdio.h>
int main (void)
{
#ifdef pthread_h // check whether pthread_h was defined/ pthread.h was included.
// pthread specific logic here
puts("It is linked!");
#endif
}
输出:
It is linked!
尝试在第一行注释掉宏pthread_h
的定义,您将看到没有输出显示。
旁注:
“ ...,如果pthread实际上在编译时已链接。”
链接过程在编译时未完成。它在编译后出现。因此,您不能使用预处理宏(甚至在编译前也要进行评估/扩展)来确定文件是否成功链接。如果不是,则链接程序应对此进行诊断。但是我的最高猜测是,只是您在这里放错了措辞,并打算根据是否在源文件中包含标头pthread.h
来包含源代码。