简体   繁体   English

为什么我们不能在main函数中定义函数?

[英]Why can't we define function inside the main function?

In the following program, I try to call the function n() and inside n() , try to call m() function which is defined in the main function, but when I compile, I get the error below: 在下面的程序中,我尝试调用函数n()并在n()内部,尝试调用在main函数中定义的m()函数,但是在编译时,出现以下错误:

 In function `n': (.text+0xa): undefined reference to `m' error: ld returned 1 exit status 

Why do I get an error? 为什么会出现错误? Please explain. 请解释。

The code is here: 代码在这里:

#include <stdio.h>
void m();
void n()
{
    m();
}

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

You can not implement a function within the scope of another function in standard C. Move the implementation of m() out of your main. 您不能在标准C中的另一个函数范围内实现一个函数。将m()的实现移出main函数。

The code you posted should not compile at all; 您发布的代码完全不应该编译。 though, the error you get is because the linker ld can not find the implementation of m . 但是,您得到的错误是因为链接器ld找不到m的实现。 The function can be used because you declared it, but the implementation is missing and thus can not be linked. 可以使用该函数,因为您已声明该函数,但是缺少实现 ,因此无法链接。

Also note that your main function shall return a value of type int . 另请注意,您的main函数应返回int类型的值。 Using void will make your program return an arbitrary value from which the operating system/shell can't conclude whether execution was successful. 使用void将使您的程序返回一个任意值,操作系统/ shell无法从该值得出执行是否成功的结论。

#include <stdio.h>

void m();

void n() {
    m();
}

int main() {
    n();
    return 0;
}

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

m is defined inside of main . mmain内部定义。 In standard C, that's not allowed (you can't define a function within another function). 在标准C中,这是不允许的(您不能在另一个函数中定义一个函数)。

Some compilers (eg gcc) allow it as an extension. 一些编译器(例如gcc)允许它作为扩展。 But then the function is local , ie m only exists within main and can't be seen from the outside. 但是然后函数是局部的 ,即m仅存在于main ,而不能从外部看到。 Similarly, variables defined within a function are local to that function and can't be seen from the outside. 同样,在函数中定义的变量是该函数的局部变量,无法从外部看到。

Your void m(); 您的void m(); declaration at the top claims that a (global) function called m exists, but it doesn't. 顶部的声明声称存在一个名为m的(全局)函数,但不存在。 That's why you get the linker error. 这就是为什么您收到链接器错误。

m()的函数声明移到main()方法之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM