天天看點

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

根據錯誤

可以看出是在ld的時候系統無法找到pthread_create函數。也就是說編譯器在link得時候找不到其中的一個使用庫的函數。

如果差pthread_create的話可以發現其在pthread.so中,是以需要增加 -lpthread編譯參數,告訴linker在link的時候使用pthread子產品