Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Receiving compiling errors with code I was told would work, help to properly com

ID: 3815789 • Letter: R

Question


Receiving compiling errors with code I was told would work, help to properly compile is needed.

This is a C file using PuTTY, I tried gcc solution1.c and am given the error posted. The code is below.

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

#define N 5 //the number of philosophers

sem_t S[N]; //semaphores for chopsticks

void * philospher(void *num);
void take_chopsticks(int);
void put_chopsticks(int);

int phil_num[N]={0,1,2,3,4}; //philosopher ID

int main()
{
int i;
pthread_t thread_id[N];


for(i=0;i<N;i++)
sem_init(&S[i],0,1);

for(i=0;i<N;i++)
pthread_create(&thread_id[i],NULL,philospher,&phil_num[i]);

for(i=0;i<N;i++)
pthread_join(thread_id[i],NULL);
}


void *philospher(void *num)
{
while(1)
{
int *i = num;
take_chopsticks(*i);
put_chopsticks(*i);
}
}

void take_chopsticks(int ph_num)
{
printf(
"Philosopher %d is Hungry ",ph_num);

sem_wait(&S[ph_num]); //take the left chopstick
printf("Philosopher %d takes chopstick%d ",ph_num, ph_num);

sleep(1);

sem_wait (&S[(ph_num+1)%N]); //take the right chopstick
printf("Philosopher %d takes chopstick%d ",ph_num,(ph_num+1)%N);

printf("Philosopher %d is eating ",ph_num);
sleep(1);
  
}


void put_chopsticks(int ph_num)
{

sem_post (&S[ph_num]); //put the left chopstick
printf("Philosopher %d putting chopstick%d ",ph_num, ph_num);

sleep(1);

sem_post (&S[(ph_num+1)%N]); //put the right chopstick
printf("Philosopher %d putting chopstick%d ",ph_num,(ph_num+1)%N);

printf("Philosopher %d is thinking ",ph_num);
sleep(1);
}

/tmp/ccEnr YF4.o (.text+0x33) In function main' undefined reference to sem init tmp/ccEnrYF 4.o (.text+0x71) In function main undefined reference to pthread create tmp/ccEnrYF 4.o (.text+0x9b) In function main undefined reference to pthread join tmp/ccEnrYF4.o (.text+0x103) In function take chopsticks undefined reference to "sem vait' tmp/ccEnr YF4.o (.text+0x14a) In function take chopsticks undefined reference to sem vait' tmp/ccEnrYF4.o (.text+0x1ab) In function put chopsticks' undefined reference to sem post itnap/ccEnrYF4. o (.text +0x1f2) In function put chopsticks undefined reference to sem post' collect 2 ld returned 1 exit status

Explanation / Answer

Adding '-lpthread','-pthread' or '-ltr' to the end of ur code should resolve this issue.

the other reason is that you're getting these linker errors is because the order in which you specify input files and linker options on the command line matters..