【问题标题】:Includes in Eclipse Mars C++包含在 Eclipse Mars C++ 中
【发布时间】:2016-02-16 14:40:54
【问题描述】:

我在Main.cpp 文件中定义了函数int getRandomNumber()。在这个文件之外,还有类,由头文件和类文件组成。

函数int getRandomNumber()由于某种原因不能从其他类文件中访问,即使它被认为是全局的。

Main.cpp 中的代码如下所示:

#include <iostream>

using namespace std;

int getRandomNumber() {
    return 4; // Chosen by fair dice roll
}

#include "folder/ClassName.h"

int main(int argc, char* argv[]) {
    ClassName t;
    t.test();
    return 0;
}

ClassName.h 的内部看起来像这样:

#ifndef SRC_CLASSNAME_H_
#define SRC_CLASSNAME_H_

class ClassName {
public:
    ClassName();
    virtual ~ClassName();
    void test();
};

#endif /* SRC_CLASSNAME_H_ */

最后,ClassName.cpp 的内部包含以下内容:

#include <iostream>
#include "ClassName.h"

using namespace std;

ClassName::ClassName() {
    cout << "Created" << endl;
}
ClassName::~ClassName() {
    cout << "Destroyed" << endl;
}
void ClassName::test() {
    cout << "Tested" << endl;
}

为什么“Created”、“Tested”和“Destroyed”都打印到控制台,即使ClassName.cpp文件从未明确包含在任何地方?

为什么不能从ClassName.h 文件中访问int getRandomNumber(),即使预处理器将它粘贴到包含它的位置?同样的事情也适用于&lt;iostream&gt;。为什么需要在.cpp 文件中再次包含它?

【问题讨论】:

  • 似乎ClassName.cpp 文件在项目中,因此它与程序的其余部分一起构建。而且您无法从头文件(或任何其他源文件)访问getRandomNumber,因为它没有在其他任何地方声明
  • 您需要将getRandomNumber() 移动到标题中,然后将该标题包含在ClassName.h 中以便您使用它,但仍保留Main.cpp 文件中的功能。而且我认为您将标头与源文件(c,cpp)混淆了,编译器将每个源文件视为一个单独的文件,因此您需要在两个 cpp 文件中包含iostream
  • 哦,我现在明白这个概念了。谢谢你们俩!因此,在头文件中,您声明 内容,然后在.cpp 文件中放入内容,可以从仅包含头文件的任何其他源文件中访问这些内容。这个问题我该怎么办?

标签: c++ eclipse include eclipse-mars


【解决方案1】:

要从多个位置访问getRandomNumber(),您可以将其移至标题,然后将其包含在需要该功能的所有源文件中:

MyHeader.h

#ifndef MYHEADER_H
#define MYHEADER_H

int getRandomNumber();

// ... other stuff here

#endif /* MYHEADER_H */

Main.cpp

#include "MyHeader.h"

int getRandomNumber() {
    return 4; // Chosen by fair dice roll
}

// ... other stuff here

现在您可以在任何源文件中通过#include 访问getRandomNumber()

【讨论】:

    猜你喜欢
    • 2016-05-19
    • 1970-01-01
    • 2015-12-19
    • 2016-10-12
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 2016-01-21
    • 2016-06-28
    相关资源
    最近更新 更多