为什么以下代码显示错误? [英] Why does the following code show an error?

查看:176
本文介绍了为什么以下代码显示错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

void m();

void n() {
    m();
}

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

在编译时出现错误


undefined reference to m

"undefined reference to m"

被显示。哪个 m 被引用?

推荐答案

首先,让我声明显然,


嵌套函数不是标准的 C 。它们被支持为GCC扩展。

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

现在,在你的代码中, m() main()内的嵌套函数。它仅具有 main()的块范围。外部 main()其他函数看不到 m()的存在,既不能调用 m()直接。 m()只能在 main()内调用。

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

在您的情况下, n()内的 m()的调用正在导致问题。即使您提供了前向声明为 void m(); ,链接器将无法找到 m()并抛出错误。

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.

解决方案:移动 m()外面 main(),那么你可以从任何其他功能使用它。

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

另请注意,推荐 main()的签名是 int main(void)

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

这篇关于为什么以下代码显示错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆