Search code examples
linuxmultithreadingposixundefined-reference

Undefined Reference to function while threading in Linux


I looked up the other questions to make sure this isn't duplicate.

I have 3 files:

file1.h
file1.c
file2.c

file1.h has this line in it:

void *myFunction(void *vargp);

file1.c has:

#include <pthread.h>
#include "file1.h"    
void *myFunction(void *vargp)
    { 
        //do stuff
        return 0;
    }

file2.c has:

#include <pthread.h>
#include "file1.h"

int main()
{
    pthread_t thread_id;
    int t1; 
    t1 =  pthread_create(&thread_id, NULL, myFunction, NULL);
    pthread_join(thread_id, NULL);
    return 0;
}

I use the following command to compile and link:

gcc -pthread -o file2 file2.c

and I get these errors:

file2.c:(.text+0xa64): undefined reference to `myFunction'
file2.c:(.text+0xa68): undefined reference to `myFunction'

Solution

  • I came up with two independent solutions that both worked:

    1. doing this: gcc -pthread -o file2 file2.c file1.c
    2. doing this: putting #include "file1.c" in code file2.c instead of #include "file1.h"

    Edit: You can't do method #2 if you have two mains!