1
#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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
aditya
  • 165
  • 2
  • 12
  • 3
    First you should know that C doesn't support nested functions, if it works for you then it's because your compiler allows it, but it's not portable. Then think about scoping, you would not expect a local variable defined inside the `main` function to be available in the global scope would you? – Some programmer dude Jun 26 '15 at 15:05
  • there's only one m not defined - also there are no nested functions in ANSI C – BeyelerStudios Jun 26 '15 at 15:05

2 Answers2

3

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).

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
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;
}
John Bode
  • 119,563
  • 19
  • 122
  • 198