Hi friends,
I am using semaphores in my program, but when I compile the program, it gives the following error
$ gcc sem.c -o sem -lpthread
Undefined first referenced
symbol in file
sem_init /var/tmp//ccAGJZdT.o
sem_post /var/tmp//ccAGJZdT.o
sem_wait /var/tmp//ccAGJZdT.o
ld: fatal: Symbol referencing errors. No output written to sem
collect2: ld returned 1 exit status
Or
$ gcc sem.c -o sem
Undefined first referenced
symbol in file
sem_init /var/tmp//cc3WmF9R.o
sem_post /var/tmp//cc3WmF9R.o
sem_wait /var/tmp//cc3WmF9R.o
ld: fatal: Symbol referencing errors. No output written to sem
collect2: ld returned 1 exit status
$
Here is my program's full source
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/sem.h>
#define MAX_THREAD 100
typedef struct
{
int start,end;
} param;
sem_t mysem;
void *count(void *arg)
{
sem_wait(&mysem);
int i =0;
param *p=(param *)arg;
printf("\nprintfrom %d to %d\n",p->start,p->end);
for(i =p->start ; i< p->end ; i++)
{
printf(" i = %d",i);sleep(1);
}
sem_post(&mysem);
return (void*)(1);
}
int main(int argc, char *argv[])
{
if (sem_init(&mysem,0,1))
{
perror("init");
}
int n,i;
pthread_t *threads;
param *p;
if (argc != 2)
{
printf ("Usage: %s n\n",argv[0]);
printf ("\twhere n is no. of threads\n");
exit(1);
}
n=atoi(argv[1]);
if ((n < 1) || (n > MAX_THREAD))
{
printf ("arg[1] should be 1 - %d.\n",MAX_THREAD);
exit(1);
}
threads=(pthread_t *)malloc(n*sizeof(*threads));
p=(param *)malloc(sizeof(param)*n); /* Assign args to a struct and start thread */
for (i=0; i<n; i++)
{
p.start=i*100;
p.end=(i+1)*100;
pthread_create(&threads,NULL,count,(void *)(p+i));
}
printf("\nWait threads\n");
sleep(1); /* Wait for all threads. */
int *x = malloc(sizeof(int));
for (i=0; i<n; i++)
{
pthread_join(threads,(void*)x);
}
free(p);
exit(0);
return 0;
}
---------- Post updated at 09:34 AM ---------- Previous update was at 02:28 AM ----------
Nobody seems to bother replying to this query, I guess. Anyways, I found the solution to my problem. This commands works now on my Solaris 10 machine.
gcc sem.c -o sem -lrt
Thanks anyways, and keep up the good work!