Why does the following code show an error?

2019-08-02 13:43发布

问题:

#include <stdio.h>

void m();

void n() {
    m();
}

void main() {
    void m() {
        printf("hi");
    }
}

On compiling, an error

"undefined reference to m"

is shown. Which m is being referred to?

回答1:

First, let me declare clearly,

Nested functions are not standard C. They are supported as GCC extension.

OK, now, in your code, m() is a nested function inside main(). It is having block scope for main() only. Outside main() other functions cannot see the existence of m() ,neither can call m() directly. m() can be called only inside main().

In your case, the call to m() inside n() is causing the issue. Even if you provided the forward declaration as void m();, linker won't be able to find the definition of m() and throw error.

Solution: Move the definition of m() outside main(), then you can use it from any other function.

Also note, the recommended signature of main() is int main(void).



回答2:

As has been explained elsewhere, C doesn't support nested functions as a rule (gcc does as an extension, but almost no other compiler that I know of does).

You need to move the definition of m outside of main. Preferably you should define m before it is used by n:

#include <stdio.h>

void m()
{
  printf("hi\n");
}

void n()
{
  m();
}

int main( void ) // void main() is not a valid signature for main
{
  n();       // call n, which calls m, which prints "hi"
  return 0;
}