Why is there no error on Linux without library qualifiers?

I am currently a student and study operating systems and use Linux as an OS for practice. When we got to multi-threaded applications and started practicing with them (mostly just pthread_create () and pthread_join ()), one of the most common errors the class got was that they used when compiling:

gcc -Wall homework.c

instead:

gcc -Wall -lpthread homework.c

My question is why the compiler and linker do not throw an error when they are not compiled / linked with the -lpthread specifier, even if the functions used in the code require the pthread library. My instructor also does not know the reason. Is this exactly how the school created our system? Does this happen in all Linux environments? Why is the linker error not selected?

+4
source share
2 answers

Unable to play:

#include <pthread.h>

void *thread(void *arg)
{
    (void) arg;
    return 0;
}

int main(void)
{
    pthread_t t;
    pthread_create(&t, 0, thread, 0);
    return 0;
}

Attempting to link without libpthread:

> gcc -Wall -o thread thread.c
/tmp/ccyyu0cn.o: In function `main':
thread.c:(.text+0x2e): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

edit : you can check the characters defined in the library with nm -D, for example. in my case:

> nm -D /lib/x86_64-linux-gnu/libc.so.6 | grep pthread_create
> nm -D /lib/x86_64-linux-gnu/libpthread.so.0 | grep pthread_create
00000000000082e0 T pthread_create

(therefore pthread_create not found in libc, but valid in libpthread)

edit2: , , , , (libc, libgcc), pthread_create. , , , libpthread. , . , .

+2

@FelixPalmen . pthread , gcc. gcc .

, -lpthreads:

serga@XXXXX:~$ gcc ./thread.c -o thread
/tmp/ccHgCRzO.o: In function `main':
thread.c:(.text+0x29): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

, gcc :

serga@XXXXX:~$ strace gcc 2>&1 | grep spec
access("/usr/lib/gcc/i686-linux-gnu/5/specs", R_OK) = -1 ENOENT (No such file or directory)
access("/usr/lib/gcc/i686-linux-gnu/5/../../../../i686-linux-gnu/lib/i686-linux-gnu/5/specs", R_OK) = -1 ENOENT (No such file or directory)
access("/usr/lib/gcc/i686-linux-gnu/5/../../../../i686-linux-gnu/lib/specs", R_OK) = -1 ENOENT (No such file or directory)
access("/usr/lib/gcc/i686-linux-gnu/specs", R_OK) = -1 ENOENT (No such file or directory)

spec , , :

    serga@XXXXX:~$ sudo gcc -dumpspecs >/usr/lib/gcc/i686-linux-gnu/5/specs

-lpthread *link:, *lib: *libgcc: spec . gcc pthread:

serga@XXXXX:~$ gcc ./thread.c -o thread && echo "completed"
completed

!!!

, gcc

( gcc-5.1.0):

serga@XXXXX:~$ gcc -v 2>&1 | head -1
  • gcc spec , :

    Reading specs from /usr/lib/gcc/i686-linux-gnu/5/specs
    
  • :

    Using built-in specs.
    

    :

    serga@XXXXX:~$ gcc -dumpspecs
    

, pthread

spec -lpthread , .

0

Source: https://habr.com/ru/post/1612313/


All Articles