1

Given this code :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <pthread.h>

#define BUF_SIZE 256
int main()
{
    key_t key;
    char *virtualaddr;
    sem_t *get, *put;
    int shmid;

   const char* messageOne = "Hello world , I'm child number 1\n";
   const char* messageTwo = "Hello world , I'm child number 2\n";

   char buf[BUF_SIZE];

   key = ftok("anyfile",'R');

  shmid = shmget(key,1024,0644|IPC_CREAT);
...
...
shmctl (shmid, IPC_RMID, NULL);
exit(EXIT_SUCCESS);
}

I get from eclipse undefined reference to sem_open .

I've check with this post since this question is very similar to mine , but didn't understand exactly where is my mistake ,

Can you please explain where do I need to fix it / add another compilation command (if this is indeed the case) ?

Much appreciated

Community
  • 1
  • 1
JAN
  • 21,236
  • 66
  • 181
  • 318
  • Please read the second answer to that question carefully. You're not doing what it says you should be doing. – Mat Jul 16 '12 at 08:56
  • I don't know how eclipse works, so here is a question: When do you get the error? Is it shown in the editor just as you type in sem_open, or only shows up when/compiling? How do you compile? – ArjunShankar Jul 16 '12 at 08:56
  • @ArjunShankar: Only when I compile it . – JAN Jul 16 '12 at 08:57
  • possible duplicate of [sem_open() error: "undefined reference to sem_open()" on linux (Ubuntu 10.10)](http://stackoverflow.com/questions/4916881/sem-open-error-undefined-reference-to-sem-open-on-linux-ubuntu-10-10) – Jens Gustedt Jul 16 '12 at 09:49

3 Answers3

4

You need to include -lpthread when compiling. This is used by the linker, to link your binary against the library.

The other answers already cover how to do this on the command line.

To do this in Eclipse, you need to follow the directions here:

In the project properties, go to : C/C++ Build --> Settings. Then "Tool Settings", select "Libraries" under "Linker". You can add all your project libraries there (without the "-l"). Also in the lower part, you can add custom path to search libraries

Community
  • 1
  • 1
ArjunShankar
  • 23,020
  • 5
  • 61
  • 83
  • Thanks a lot , this is very annoying for the Eclipse users , if you write the command in `terminal` each time ... and there are more downsides . Anyway ,thanks ! +10 for this if I could :) – JAN Jul 16 '12 at 09:10
1

When linking, you have to add the flag -pthread or -lrt to the command line. It's right there in the manual page.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

As it is written in the first answer in the question you linked, you nedd to compile it in this way:

gcc source.c -lpthread

-lrt or -pthread will do the same.

Zagorax
  • 11,440
  • 8
  • 44
  • 56