2015-05-02 115 views
0

我从StackOverflow的其他帖子看到,未定义的引用错误意味着定义丢失,通常要修复它,文件必须在编译中链接。但我只编译一个文件。我得到这个函数的错误pthread_detachpthread_createUndefined Reference for Single File

/tmp/ccAET7bU.o: In function `sample_thread1': 
foo.c:(.text+0x2a): undefined reference to `pthread_detach' 

/tmp/ccAET7bU.o: In function `main': 
foo.c:(.text+0x85): undefined reference to `pthread_create' 

collect2: error: ld returned 1 exit status 

代码:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <memory.h> 
#include <signal.h> 
#include <string.h> 
#include <linux/unistd.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <sys/syscall.h> 
#include <netinet/in.h> 
#include <pthread.h> 

pid_t gettid(void) 
{ 
    return syscall(__NR_gettid); 
} 

void *sample_thread1(void *x_void_ptr) 
{ 
    FILE *fp; 
    int counter; 

    pthread_detach(pthread_self()); 

    if((fp = fopen("thread_data.txt", "w")) == NULL) 
    { 
     printf("ERROR : Thread cannot open data file.\n"); 
     return; 
    } 
    counter = 1; 
    while(1); 
    { 
     fprintf(fp, "INFO : Thread1 id %d output message %10d\n", 
       gettid(), counter); 
     fflush(fp); 
     counter++; 
     sleep(1); 
    } 
    pthread_exit(NULL); 
} 

int main(int argc, char *argv[]) 
{ 
    int counter; 
    pthread_t sample_thread_t1; 

    if(pthread_create(&sample_thread_t1, NULL, sample_thread1, NULL)) 
    { 
     fprintf(stderr, "Error creating thread\n"); 
     exit(-1); 
    } 
    system("clear"); 

    counter = 1; 
    while(1) 
    { 
     printf("INFO : Main Process Counter = %d\n", counter); 
     counter++; 
     sleep(1); 
    } 
    return(0); 
} 
+3

我想你需要-lpthread传递给GCC来告诉它针对并行线程库链接。未定义的参考只是意味着链接器无法找到您在代码中调用的函数 – user3109672

+0

您正在为此运行哪个操作系统? – alk

+0

对于Linux pease阅读这里:http://stackoverflow.com/q/1662909/694576 – alk

回答

2

你必须使用GCC或铿锵的-lpthread-pthread选项pthread库链接此。

例子:

gcc your_file.c -o program -lpthread 
# or gcc your_file.c -o program -pthread 
# the same for clang 
+0

'-lpthread'和'-pthread'不一定是相同的。人们应该参考必须使用的实现文档。例如,对于Linux,man-page(http://man7.org/linux/man-pages/man3/pthread_create.3.html)明确声明使用'-pthread'! – alk

+0

@alk,三次或更多次我在越狱iPhone上遇到'-lpthread'的问题,并使用了'-pthread',它工作得很好。这就是为什么我建议两个选项最好的尝试。 – ForceBru

+0

'-pthread'总是暗示链接PThreads库,这就是'-lpthread'所做的所有事情,而不是'-pthread',它可能会做更多的事情,比如设置编译时间“开关”。 – alk