今日报错系列:collect2: ld returned 1 exit status

在搜索该报错时,找到了一些解决方法,虽我没有用到,但还是整理一下,希望能帮到大家,也方便自己后面遇到好翻阅。

报错、collect2: ld returned 1 exit status

解决方法一:将gcc -o 22 22.c 改变为 gcc -O2 -Wall -o 22 22.c -lpthread

今日在Linux下创建线程时,编译时会出现下面的错误:

[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

程序为:

#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);
    }
        
}

此时,只需改变编译方式

将gcc -o 22 22.c 改变为 gcc -O2 -Wall -o 22 22.c -lpthread

最关键的是-lpthread

根据错误

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

可以看出是在ld的时候系统无法找到pthread_create函数。也就是说编译器在link得时候找不到其中的一个使用库的函数。
如果差pthread_create的话可以发现其在pthread.so中,所以需要增加 -lpthread编译参数,告诉linker在link的时候使用pthread模块。

解决方法二:关闭

也有可能是小原因:因为上一个运行窗口未关,只需关闭上一个窗口再运行即可。

解决方法三:函数写错

在搜索的过程中发现,有的同学将main函数,打成了mian…
所以你懂的

扫描二维码关注公众号,回复: 12452398 查看本文章

注:方法一参考如下链接:
https://www.cnblogs.com/aspirant/p/3840101.html

结束:

分享也是自己对问题再次加深理解的方式,可能不全面,但绝对有用,后面将不断完善~

猜你喜欢

转载自blog.csdn.net/hwx802746/article/details/112286030
今日推荐