Luca
Luca

Reputation: 595

Undefined Reference for Single File

I saw from other posts on StackOverflow that the undefined reference error means that a definition is missing and that generally to fix it, files must be linked in compilation. But I am only compiling one file. I am getting this error for the functions pthread_detach and pthread_create.

/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

The code:

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

Upvotes: 0

Views: 1023

Answers (1)

ForceBru
ForceBru

Reputation: 44838

You have to link this with a pthread library using -lpthread or -pthread options of GCC or clang.

Examples:

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

Upvotes: 2

Related Questions