如何从另一个.cpp 源文件调用main.cpp 中定义的方法?

How to call a method defined in main.cpp from another .cpp source file?

首先,这是一个一般性问题

其次:我想到它是因为现在它使我的一个项目变得复杂。别担心,我有解决方法,但我仍然想知道是否有其他解决方法。

进入问题:

我有我的main.cpp。我在里面定义了一些方法和函数。我还有一些包含其他函数和内容的其他文件,但现在我需要一个函数来处理 main.cpp 中定义的临时变量。 我怎样才能扩展这样一个变量的范围,以便我也可以在其他文件中使用它?

从类,我知道字段可以是私有的或public。但是这个变量呢?是私人的吗? public?还有什么?我可以为这个变量创建一个 getter/setter 吗?我什至不能将 main.cpp 包含在另一个中,因为它是递归的,然后我将定义 main 无限次 ....)

主要问题是:

如何在另一个文件中访问我的 main.cpp 中定义的变量?

一些示例代码:

在main.cpp中:

int var = 0;

int getVar() {
    return var;
}


void doVar() {
    // sth happens with var
}

int main() {
    MyObject myObj;

    doVar();
}

在MyObject.cpp中:

class MyObject {
    void DoSth(){
        // NEEDS var from main.cpp, to do sth with it!
        // getVar() doesn't work!
        // doVar() doesn't work either!
    }
}

如果这是一个以前问过的问题或非常愚蠢的问题,请原谅我,但我刚才真的很想知道

我的解决方法是为 MyObject 的成员制作 doVar 和 var(即现在它们都在同一个文件中 MyObject.cpp),但这是唯一的方法吗?

"Is it private / public / something else?"

这称为全局变量,它是公开可见的。任何人只要提供 extern int var; 语句就可以访问它。

"can I create a getter/setter for this variable?"

是的,你可以做到(见后面的解释)

"I can't even include the main.cpp in another since it would be recursive and I'd have main defined infinite times then ....)"

当然你不能这样做(而且你永远不想在任何地方包含 .cpp 文件)。
你需要一些 header 来声明这个接口是在外部实现的,比如

VarInterface.hpp

#ifndef VARINTERFACE_HPP
#define VARINTERFACE_HPP

extern int var; // Optional, just encapsulating it with the functions is the
                // better choice
int getVar();
void doVar();

#endif // VARINTERFACE_HPP

并将其包含在 MyObject.cpp 中的实施中。


至于你的comment

"what would it do? I just googled and came up with something similar to static, is that right? so what's the difference?"

自由函数没有 privatepublic 访问范围策略(与 C static 关键字一样)。

如上例所示的任何函数或全局变量声明实际上都是可访问的,除非它被放置在未命名的命名空间 中。后者确实限制了链接器访问它们所在的翻译单元:

Another.cpp

namespace {
   // These functions and variables are exclusively accessible within
   // Another.cpp
   int var = 0;
   int getVar();
   void doVar();
}

但请将以上内容作为旁注,因为据我从你的问题中了解到,你想要相反的东西。


"Can you create 'private' fields in it and somehow access them from another .cpp in this project?"

如果你想对其他翻译单元隐藏 int var; declaration/definition(推荐),你仍然可以像

VarInterface.hpp

#ifndef VARINTERFACE_HPP
#define VARINTERFACE_HPP

int getVar();
void doVar();

#endif // VARINTERFACE_HPP

MyObject.cpp

#include "VarInterface.hpp"

namespace {
   int var = 0;
}

int getVar() {
   return var;
}

void doVar() {
    // sth happens with var
}

main.cpp

#include "VarInterface.hpp"

int main() {
    MyObject myObj;

    doVar();
}

声明您需要的任何外部变量或函数:

extern int var;
int getVar();
void doVar();

在使用它们的源文件中,或者 header 可以包含在任何想要使用它们的文件中。