编译器从哪里开始读取

时间:2011-06-27 13:54:52

标签: c++ visual-c++

这是一个小程序:

#include <iostream>
using namespace std;

int main() {
    f();
    system("pause");
}

void f() {
    static int x = 20 ;
    class tester {
    public :
        tester() {
            cout << x ;
        }
    } x1;
}

我在这里遇到的错误是:错误C3861:'f':找不到标识符

如果我将函数f放在main之上,我将获得所需的输出。

为什么会这样? 我被告知程序执行从main开始。据此,代码也应该在第一种情况下运行。

编译器如何开始阅读程序?

5 个答案:

答案 0 :(得分:7)

  

我被告知程序执行从main开始。

这就是重点。

编译器从main开始,然后看到对f()的调用,到目前为止它没有遇到过(因为它是后来定义的),所以它不知道如何处理它

如果您想在f之后定义main,可以先放置一个函数原型,例如

#include <iostream>
using namespace std;

void f(); // <--- This tells the compiler that a function name f will be defined

int main() {
f();
system("pause");
}

void f() {
static int x = 20 ;
class tester {
public :
    tester() {
        cout << x ;
    }
} x1;
}

答案 1 :(得分:3)

为了能够调用一个函数,它必须在代码中的某个早期点声明。这只是旨在帮助编译器的语言规则。

您可以先使用例如

声明该功能
void f();

...然后在main之后定义它就像你做的那样。

答案 2 :(得分:3)

编译器从顶部开始并向下读到底部。

你需要有类似的东西:

#include <iostream>
using namespace std;

void f();

int main() {
f();
system("pause");
}

void f() {
static int x = 20 ;
class tester {
public :
    tester() {
        cout << x ;
    }
} x1;
}

答案 3 :(得分:2)

不,编译器在使用之前需要至少看到f()的声明。 c(++)代码文件是一个简单的文本文件,必须由编译器从头到尾读取。

答案 4 :(得分:2)

在编译过程中,当编译器正在评估main()时,它需要事先知道f()是什么,以便能够生成正确的汇编代码来调用此函数。这就是为什么在这种情况下你需要把它放在main()之前。

作为替代方案,您可以在f()之前声明main()的原型,以便编译器知道它是在您文件的其他位置声明的本地函数:

void f(); // prototype

int main() 
{
  // .. code ..
}

void f() // implementation of f()
{
 // .. code ..
}