Why do you need '-lpthread'?

回眸只為那壹抹淺笑 提交于 2020-01-14 10:38:48

问题


So my questions is: Why do you need '-lpthread' at the end of a compiling command?

Why does this command work:

gcc -o name name.c -lpthread

but this won't:

gcc -o name name.c

I am using the pthread.h library in my c code.
I already looked online for some answers but didn't really find anything that answered it understandably


回答1:


pthread.h is not a library it is just a header file which gives you declaration (not the actual body of function) of functions which you will be using for multi-threading.

using -libpthread or -lpthread while compiling actually links the GCC library pthread with your code. Hence the compiler flag, -libLIBRARY_NAME or -lLIBRARY_NAME is essential.

If you don't include the flags -l or -lib with LIBRARY_NAME you won't be able to use the external libraries.

In this case, say if you are using functions pthread_create and pthread_join, so you'll get an error saying:

undefined reference to `pthread_create'

undefined reference to `pthread_join'



回答2:


The -l options tells the linker to link in the specified external library, in this case the pthread library.

Including pthread.h allows you to use the functions in the pthread library in you code. However, unlike the functions declared in places like studio.h or stdlib.h, the actual code for the functions in pthread.h are not linked in by default.

So if you use functions from this library and fail to use -lpthread, the linking phase will fail because it will be unable to find functions in the library such as pthread_create, among others.



来源:https://stackoverflow.com/questions/59053585/why-do-you-need-lpthread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!