Today’s error series: collect2: ld returned 1 exit status

When searching for the error, I found some solutions. Although I didn't use it, I would like to sort it out. I hope it can help you and make it easier for you to read it later.

Error, collect2: ld returned 1 exit status

Solution 1: Change gcc -o 22 22.c to gcc -O2 -Wall -o 22 22.c -lpthread

When creating threads under Linux today, the following errors will appear during compilation:

[root@linuxserver 807]# gcc -o 22 22.c
/tmp/cc21HcoW.o(.text+0x4c): In function `main':
: undefined reference to `pthread_create'
collect2: ld returned 1 exit status

The procedure is:

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void testthread(void)
{
    
    
    printf("I am working.\n");
    printf("I am stopping.\n");
    pthread_exit(0);
}

int main(int argc,char *argv[])
{
    
    
    int i=0;
    pthread_t pid;
    char *szP=NULL;
    while(1)
    {
    
    
        i++;
        pthread_create(&pid,NULL,(void *)testthread,(void *)&i);
        printf("ok%d,pid=%d\n",i,pid);
        sleep(5);
    }
        
}

At this point, just change the compilation method

Change gcc -o 22 22.c to gcc -O2 -Wall -o 22 22.c -lpthread

The most important thing is -lpthread

According to the error

/tmp/cc21HcoW.o(.text+0x4c): In function `main':
: undefined reference to `pthread_create'
collect2: ld returned 1 exit status

It can be seen that the system cannot find the pthread_create function at the time of ld. That is to say, the compiler cannot find one of the functions using the library when link is available.
If pthread_create is not good enough, it can be found in pthread.so, so you need to add the -lpthread compilation parameter to tell the linker to use the pthread module when linking.

Solution 2: Close

There may also be a small reason: because the last running window is not closed, just close the last window and run it again.

Solution 3: Wrong function

During the search, I found that some students typed the main function as mian...
so you know

Note: Refer to the following link for Method 1:
https://www.cnblogs.com/aspirant/p/3840101.html

End:

Sharing is also a way to deepen your understanding of the problem again. It may not be comprehensive, but it is definitely useful and will continue to be improved later~

Guess you like

Origin blog.csdn.net/hwx802746/article/details/112286030