pthread error

A

asit

This is the code snippet with main function..

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

pthread_t ntid;

void printids(const char *s) {
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x) \n", s, (unsigned int)pid, (unsigned
int)tid, (unsigned int)tid);
}

void * thr_fn(void *arg) {
printids("new thread : ");
return ((void*)0);
}

int main() {
int err;
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if(err != 0)
printf("can't create thread \n");
printids("main thread : ");
sleep(1);
return 0;
}

When I tried to compile this, it showed the following error ???

asit@asit-desktop:~/cpp$ gedit pthread1.c
asit@asit-desktop:~/cpp$ gcc -o pthread1 pthread1.c
/tmp/ccgO2hyj.o: In function `main':
pthread1.c:(.text+0x85): undefined reference to `pthread_create'
collect2: ld returned 1 exit status
 
H

Hamiral

asit a écrit :
asit@asit-desktop:~/cpp$ gedit pthread1.c
asit@asit-desktop:~/cpp$ gcc -o pthread1 pthread1.c
/tmp/ccgO2hyj.o: In function `main':
pthread1.c:(.text+0x85): undefined reference to `pthread_create'
collect2: ld returned 1 exit status

You forgot to link with pthread...

Try compiling with
gcc -o pthread1 pthread1.c -lpthread
 
M

Mikko Rauhala

(Off-topic for comp.lang.c, moving to comp.unix.programmer where
this seems more suited.)

You forgot to link with pthread...

Try compiling with
gcc -o pthread1 pthread1.c -lpthread

With gcc, you should rather use -pthread which should set both preprocessor
and linker flags appropriately for using pthreads on the current platform.

Just -lpthread may of course work for some use cases.
 
K

Keith Thompson

asit said:
This is the code snippet with main function..

#include <stdio.h>
#include <pthread.h> [snip]
When I tried to compile this, it showed the following error ???

asit@asit-desktop:~/cpp$ gedit pthread1.c
asit@asit-desktop:~/cpp$ gcc -o pthread1 pthread1.c
/tmp/ccgO2hyj.o: In function `main':
pthread1.c:(.text+0x85): undefined reference to `pthread_create'
collect2: ld returned 1 exit status

Note that <pthread.h> is not a standard C header.

You need to tell the compiler (actually the linker) where to find the
library that implements pthreads. The way to do this can vary from
system to system and from compiler to compiler.

(For gcc, it's probably either "-pthread" or "-lpthread". Consult
your system's documentation, perhaps "man pthreads", to be sure.)

If you have more questions about thread programming, try
comp.programming.threads.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top