简体   繁体   中英

Why does this code generate the error 'undefined reference to main' upon compilation?

This is for an assignment, but right now I'm just playing around with a code I found in a tutorial, but I can't seem to get it to compile, and I don't understand the error I receive. My code is below:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *myfunc (void *myvar);

int main( int argc, char *argv[])
{
    pthread_t thread1;
    pthread_t thread2;
    char *msg1 = "First thread";
    char *msg2 = "Second thread";
    int ret1;
    int ret2;
    //create threads
    ret1 = pthread_create(&thread1, NULL, myfunc, (void*) msg1);
    ret2 = pthread_create(&thread2, NULL, myfunc, (void*) msg2);

    printf("Main function after pthread_create\n");
    //join threads back to main process once completed
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    printf("Return thread ret1 = %d\n", ret1);
    printf("Return thread ret2 = %d\n", ret2);


    return 0;
}

void *myfunc(void *myvar)

{
    char *msg;
    msg = (char *) myvar;
    int i;
    for (i = 0; i < 10; i++) {
        printf("%s%d\n", msg, i);
        sleep(1);
    }
    return NULL;
}

I compiled using gcc -o c_thread c_thread.c and received the error:

/usr/lib/gcc/x86_64-linux-gnu/5/.../.../.../x84_64-linux-gnu/ctr1.o: In function '_start':
/build/buildd/glibc-2.21/csu/.../sysdeps/x86_64/start.S:114: undefined reference to 'main'
collect2: error: ld returned 1 exit status

I know other questions have been asked about similar errors, but every answer I found related to a code which used a 'nontraditional' main function, whereas mine follows the standard int main(int argc char *argv[]) format

Any suggestions would be greatly appreciated

Your missing the -lpthread when compiling

Try compiling as following via terminal or adjusting the settings from the linker if you're working in an IDE:

gcc pro.c -o pro -lpthread

Suppose pro.c was your program file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM