Cheche Romo
Cheche Romo

Reputation: 139

c++ extern object array

I am trying to create an extern object array, but I think I am having a linking problem. I have a class defined on class.hpp file, on the Declarations.cpp file I include the class header and I proceed to create an array of the class, then on my second header file I have the same array declared as extern, this header is to be included where I need to use it, then main_header.hpp file is used to initialize the extern array , so they can be used wherever main_header.hpp is included.

But I am getting:

error: undefined Reference to "myArray" on main_header.hpp

The code below is the minimal code to reproduce the issue, in here I had omitted header guards and code that is not important.

this is my setup:

class.hpp

class myClass
{
  //Class Declaration
};

/* end of file */

Declarations.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 */

How can I properly declare an extern object array??

Thanks in advance!

Cheche Romo

edit: I am compiling with g++ on PSoC Creator.

edit2:

if in my Declarations.cpp I add

int var = 0;

then on main_header.hpp I add

extern int var;

an then on main cpp

int a = var;

it shows me no error for var, only for myArray.

Upvotes: 0

Views: 896

Answers (1)

selbie
selbie

Reputation: 104579

Change main_header.hpp to be:

extern myClass myArray[];

Upvotes: 1

Related Questions