views:

901

answers:

1

Hi, I'm trying to complete a project for school involving the use of semaphores. I have included the proper header files ( plus one for pthreads). I have pointed the compiler to the proper libraries as well. This is written in C. Yes, this is an assignment, but please be aware I am not looking for help with implementation, rather I can't seem to figure out this damnable compile error.

Here are lines 47 through 50 of my code, which are "simple" declarations of the semaphores and initializing them:

sem_t empty;
sem_init(&empty, 0, 5); 
sem_t full;
sem_init(&full, 0, 0);

Here are the messages I'm getting when I try and compile for line 48. I get the same set for line 50 but didn't post it for the sake of brevity:

|48|error: expected declaration specifiers or ‘...’ before ‘&’ token|
|48|error: expected declaration specifiers or ‘...’ before numeric constant|
|48|error: expected declaration specifiers or ‘...’ before numeric constant|
|48|warning: data definition has no type or storage class|
|48|warning: type defaults to ‘int’ in declaration of ‘sem_init’|

I have declared all these outside the main() function. How can I resolve these errors? I'm baffled because it seems to indicate no data type for sem_t, but it is defined in semaphore.h, which I have included. I am compiling this using Code::Blocks under Ubuntu, which is using gcc. This error occurs even when compiling from the command line.

Thanks in advance for the help.

+7  A: 

I think your problem may be related to scoping.

"I have declared all these outside the main() function"

sounds suspicious, because I can see you calling a function right after the declaration.

Try moving the calls to sem_init inside main

You can declare things at file scope (i.e. outside of main, effectively creating a global variable) but you can't call functions (like sem_init) at file scope. They must be called at function scope (e.g. inside of main())

Daniel LeCheminant
This is probably the answer. You can't put function calls at file scope - they need to be inside another function.
Andrew Medico
and don't forget to link with the right library ... -lrt here
Ben
@Andrew: Good call; I've amended my answer to include aspects of your comment.
Daniel LeCheminant