【问题标题】:c++ extern object arrayc++ 外部对象数组
【发布时间】:2018-10-23 16:49:10
【问题描述】:

我正在尝试创建一个外部对象数组,但我认为我遇到了链接问题。我在 class.hpp 文件中定义了一个类,在 Declarations.cpp 文件中包含了类头,然后我继续创建该类的数组,然后在我的第二个头文件中,我将相同的数组声明为 extern,这个头是要包含在我需要使用的地方,然后使用 main_header.hpp 文件来初始化 extern 数组,这样就可以在包含 main_header.hpp 的任何地方使用它们。

但我得到了:

错误:未定义对 main_header.hpp 上“myArray”的引用

下面的代码是重现问题的最少代码,在这里我省略了标题保护和不重要的代码。

这是我的设置:

类.hpp

class myClass
{
  //Class Declaration
};

/* end of file */

声明.cpp

#include "class.hpp"

myClass myArray[4];

/* end of file */

main_header.hpp

#include "class.hpp"

extern myClass *myArray;

/* end of file */

main_header.cpp

#include "main_header.hpp"

void setup()
{
  for(uint8_t i = 0; i < 4; i++)
  {
    myArray[i] = myClass();
    myArray[i].begin();
  }
}

/* end of file */

main.cpp

#include "main_header.hpp"

void function()
{
  setup();
  myArray[0].test();
}

/* end of file */

如何正确声明外部对象数组??

提前致谢!

车切罗莫

编辑: 我在 PSoC Creator 上使用 g++ 进行编译。

编辑2:

如果我在我的 Declarations.cpp 中添加

int var = 0;

然后在 main_header.hpp 我添加

外部整数变量;

然后在主cpp上

int a = var;

它显示 var 没有错误,仅适用于 myArray。

【问题讨论】:

  • 你是如何编译程序的?
  • 我在 PSoC Creator 中使用 g++ 进行编译。
  • 我解决了,声明文件上有一个不可见的unicode字符,我不知道为什么编译器没有警告我。抱歉这个垃圾问题。

标签: c++ arrays object g++ extern


【解决方案1】:

将 main_header.hpp 更改为:

extern myClass myArray[];

【讨论】:

  • 我已经测试过了,它给了我同样的错误:(
  • 您确实将 declarations.obj 链接到您的最终项目输出中,对吧?
  • 是的,它应该在 PSoC creator 上使用 g++ 编译时链接,我的意思是我不确定链接是如何完成的,但这不是我第一次在这个环境中使用外部变量,但它是我第一次声明一个外部对象数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 2015-08-01
相关资源
最近更新 更多