Why does the following code show an error?

爱⌒轻易说出口 提交于 2019-12-11 08:57:56

问题


#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;
}


来源:https://stackoverflow.com/questions/31076470/why-does-the-following-code-show-an-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!