nunos
nunos

Reputation: 21389

Declaring a function inside a function?

I have came across the following code, and being a C beginner, I came here for your help.

This function is from a c implmentation of a queue.

Bool queuePut(Queue *q, char c) 
{
    void beep();

    if (queueFull(q)) 
    {
        beep();
        return false;
    }

    //do stuff

    return true;
}

So, I am getting a strange error with gcc on the void beep(). Can someone please explain me what is this, declaring a function inside a function. Or is it the void beep() simply out of place? I was given this code and there's always the possibility that it isn't correct.

Edit: The error I am getting:

c:/djgpp/tmp/src/ccrjtmBh.o:queue.c:(.text+0x50): undefined reference to
    '_beep'
collect 2: ld returned 1 exit status.

Is this a linking error?

Upvotes: 5

Views: 526

Answers (3)

JaredPar
JaredPar

Reputation: 754545

As others have noted what's going on here is that your function is declaring a prototype for a function named "beep". The way to work around this is to ensure that the function beep is included in your compilation or linking.

The first step is to make sure you're compiling all of the files you received and linking all of the supported .lib's

If this doesn't work you can just add the method yourself ;)

void beep() {
  printf ("beep\n");
}

Upvotes: 1

Jakob Borg
Jakob Borg

Reputation: 24425

This is unusual but legal. The error you are seeing might be from the linker, if there is no actual beep() defined anywhere else. Can you post the actual error you receive?

Upvotes: 3

Khaled Alshaya
Khaled Alshaya

Reputation: 96849

Most probably you are having a linking error because:

void beep();

is a prototype of a function that has to be defined elsewhere. In C you can't define a function inside another one. Please, elaborate on the error you are getting.

Upvotes: 4

Related Questions