ld returned 1 exit status"的解決辦法


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模塊


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM