为什么主函数可以调用并运行其他CPP文件的功能

why can main function call and run the function of other cpp file?

本文关键字:CPP 其他 文件 功能 运行 函数 调用 为什么      更新时间:2023-10-16

i创建一个C 项目test,其中包含以下三个文件:你好。hpp:

#ifndef HELLO_H
#define HELLO_H
int cHelloSay();
#endif 

hello.cpp:

#include "hello.hpp"
#include<iostream>
int sayHello(){
    std::cout << "123";
}
int i=sayHello();

和main.cpp:

#include "hello.hpp"
int main(int argc, char** argv) {
    return 0;
}

然后我编译了此项目,然后输出:123。所以我很困惑为什么int i=sayHello();行执行,尽管main()不称呼它?

现在,我知道在函数之外声明的任何变量都是全局变量,尽管它在另一个 *.cpp文件中。因此,在致电main()

之前将执行int i=sayHello();

在遵守程序后,变量被初始化。作为其中的一部分,它在称为int main()之前调用您的 int i=sayHello();

希望这会有所帮助!