为什么需要“-lpthread”?
Why do you need '-lpthread'?
所以我的问题是:为什么在编译命令的末尾需要“-lpthread”?
为什么这个命令有效:
gcc -o name name.c -lpthread
但这不会:
gcc -o name name.c
我在我的 C 代码中使用 pthread.h 库。
我已经在网上寻找了一些答案,但没有真正找到任何可以理解的答案
-l
选项告诉 linker 在指定的外部库中 link,在本例中是 pthread 库。
包括 pthread.h 允许您在代码中使用 pthread 库中的函数。但是,与在 studio.h 或 stdlib.h 中声明的函数不同,pthread.h 中函数的实际代码默认情况下并未 link。
因此,如果您使用此库中的函数而无法使用 -lpthread
,则 linking 阶段将失败,因为它将无法在库中找到函数,例如 pthread_create
,等等。
pthread.h
不是一个库 它只是一个头文件 它为您提供了您将要使用的函数的声明(不是函数的实际主体)多线程。
在编译时使用 -libpthread
或 -lpthread
实际上将 GCC 库 pthread
与您的代码链接起来。因此,编译器标志 -libLIBRARY_NAME
或 -lLIBRARY_NAME
是必不可少的。
如果您不将 -l
或 -lib
标志包含在 LIBRARY_NAME
中,您将无法使用外部库。
在这种情况下,假设您正在使用函数 pthread_create
和 pthread_join
,那么您将收到一条错误消息:
undefined reference to `pthread_create'
undefined reference to `pthread_join'
所以我的问题是:为什么在编译命令的末尾需要“-lpthread”?
为什么这个命令有效:
gcc -o name name.c -lpthread
但这不会:
gcc -o name name.c
我在我的 C 代码中使用 pthread.h 库。
我已经在网上寻找了一些答案,但没有真正找到任何可以理解的答案
-l
选项告诉 linker 在指定的外部库中 link,在本例中是 pthread 库。
包括 pthread.h 允许您在代码中使用 pthread 库中的函数。但是,与在 studio.h 或 stdlib.h 中声明的函数不同,pthread.h 中函数的实际代码默认情况下并未 link。
因此,如果您使用此库中的函数而无法使用 -lpthread
,则 linking 阶段将失败,因为它将无法在库中找到函数,例如 pthread_create
,等等。
pthread.h
不是一个库 它只是一个头文件 它为您提供了您将要使用的函数的声明(不是函数的实际主体)多线程。
在编译时使用 -libpthread
或 -lpthread
实际上将 GCC 库 pthread
与您的代码链接起来。因此,编译器标志 -libLIBRARY_NAME
或 -lLIBRARY_NAME
是必不可少的。
如果您不将 -l
或 -lib
标志包含在 LIBRARY_NAME
中,您将无法使用外部库。
在这种情况下,假设您正在使用函数 pthread_create
和 pthread_join
,那么您将收到一条错误消息:
undefined reference to `pthread_create'
undefined reference to `pthread_join'