简体   繁体   English

如何从另一个源文件调用main.cpp中的静态函数?

[英]How to call a static function in main.cpp from another source file?

I have a method called initializeObjects() in my main.cpp file, and I want to call it from a method in another source file, named Scene.cpp . 我的main.cpp文件中有一个名为initializeObjects()的方法,我想从另一个名为Scene.cpp的源文件中的方法调用它。 How do I do that? 我怎么做? This is my main.cpp file, without the headers: 这是我的main.cpp文件,没有标题:

static void initializeObjects();
int main() {
    Scene myScene;
    myScene.render(640,480);
    return 0;
}

void initializeObjects(){
    //Add a plane of gray color
    Scene::shapes.push_back(std::make_shared<Plane>(Vector3D(0,1,1), Vector3D(0,0,80), COLOR_GRAY));
    //Add two spheres
    Scene::shapes.push_back(std::make_shared<Sphere>(100.0, Vector3D(0,50,0), COLOR_WHITE));
    Scene::shapes.push_back(std::make_shared<Sphere>(60.0,ORIGIN, COLOR_RED));
}

When you define a function with storage class specifier static , you explicitly say that you want this function to have an internal linkage - this means it should not be visible outside the translation unit where it is defined. 当使用存储类说明符static定义一个函数时,您明确表示要该函数具有内部链接-这意味着它在定义它的翻译单元之外不应该可见。

So to be able to call your function from some other translation unit (Scene.cpp), drop static specifier, and add declaration of your function to header file, which should be included by this other (Scene.cpp) translation unit. 因此,能够从其他转换单元(Scene.cpp)调用函数,删除static说明符,并将函数的声明添加到头文件中,该文件应包含在其他转换单元(Scene.cpp)中。

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

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