我從StackOverflow的其他帖子看到,未定義的引用錯誤意味着定義丟失,通常要修復它,文件必須在編譯中鏈接。但我只編譯一個文件。我得到這個函數的錯誤pthread_detach
和pthread_create
。Undefined 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);
}
我想你需要-lpthread傳遞給GCC來告訴它針對並行線程庫鏈接。未定義的參考只是意味着鏈接器無法找到您在代碼中調用的函數 – user3109672
您正在爲此運行哪個操作系統? – alk
對於Linux pease閱讀這裏:http://stackoverflow.com/q/1662909/694576 – alk