C pthread 包括头文件并与 -nolibc 链接

C pthread including header file and linking with -nolibc

这个例子:

#include <stdio.h>
#include <pthread.h>

__attribute__((weak)) int pthread_create( pthread_t*, const pthread_attr_t*,
    void*(*)(void*), void*);

int main()
{
    if (pthread_create)
    {
        printf("This is multi-thread version!\n");
    }
    else
    {
        printf("This is single-thread version!\n");
    }
    return 0;
}

它说如果不 link 到 pthread 库,它会 运行 在单线程模式下,但是使用 #include pthread 是不是 [=21] =]是否正常编译?
我认为 pthreadglibclibc 中,但首先有没有办法 link 排除标准库,如果是这样,你什么时候这样做?
如果在多线程模式下存在可以 运行 的代码,那么在单线程模式下 运行 是否有任何意义,如示例中所示,或者这只是一个糟糕的示例?如果是这样,将某些东西硬编码为弱符号的更好示例是什么?

but with the #include pthread isn't it going to be linked if compiled normally?

不,包含头文件与链接库不同。

I think pthread is in glibc or libc

不是。

is there a way to link excluding the standard library

检查您的编译器文档。 gccmany link options 喜欢 -nolibc -nostdlib nodefaultlibs.

if so when would you do that?

当我为确实没有 C 库的 bare-metal 目标编译时。当我编写自己的标准库或我想使用一个不同的 C 库时,默认的 C 库与系统一起分发,或者在交叉编译时,我在自定义位置有一个自定义 C 库,而系统没有随交叉编译器一起提供。等等

If there is code that can be run in multithread mode, is there ever any point in running it in single thread mode`

是的。由于某些原因,与单线程相比,多线程会导致更差的性能,例如在单核系统上。万一实时进程无论如何都拥有 cpu。或者如果特定算法不能多线程或在多线程时会导致更差的性能。