0

hello,

I can't figure out how to create an array that can be called from any module. Global or public sounds familiar but they don't work.

Cheers.

2
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Tom Gunn
0

Traditionally it is done with a header file and an implementation file:

// myarray.h
#if !defined(MYARRAY_H)
#define MYARRAY_H

#define MYARRAY_SZ 100

extern int myarray[];

#endif
// myarray.cpp
#include "myarray.h"

int myarray[MYARRAY_SZ];
// main.c
#include <iostream>
#include "myarray.h"

int main()
{
    for (int x = 0; x < MYARRAY_SZ; ++x) myarray[x] = x;
    for (int x = 0; x < MYARRAY_SZ; ++x) std::cout << myarray[x] << '\n';
}

The header file declares a name so that multiple modules can use it without getting repeated definition errors, and the implementation file provides the single definition.

0

Cheers mate that was very helpful! But is there anyway to apply this to a class? So that data from a wav file could be read from multiple modules?

Cheers again!!

Traditionally it is done with a header file and an implementation file:

// myarray.h
#if !defined(MYARRAY_H)
#define MYARRAY_H

#define MYARRAY_SZ 100

extern int myarray[];

#endif
// myarray.cpp
#include "myarray.h"

int myarray[MYARRAY_SZ];
// main.c
#include <iostream>
#include "myarray.h"

int main()
{
    for (int x = 0; x < MYARRAY_SZ; ++x) myarray[x] = x;
    for (int x = 0; x < MYARRAY_SZ; ++x) std::cout << myarray[x] << '\n';
}

The header file declares a name so that multiple modules can use it without getting repeated definition errors, and the implementation file provides the single definition.

0

But is there anyway to apply this to a class?

It depends on what you mean, but until you correct me I will assume you mean an array of class objects. :) If the class is already defined then it is a usable type just like int:

// myarray.h
#if !defined(MYARRAY_H)
#define MYARRAY_H
#include "myclass.h"

#define MYARRAY_SZ 100

extern MyClass myarray[];

#endif
// myarray.cpp
#include "myarray.h"
#include "myclass.h"

MyClass myarray[MYARRAY_SZ];

As long as the class has a default constructor you can create an array like that. Alternatively you can use just a forward declaration of the class in the header file and define it in the implementation file:

// myarray.h
#if !defined(MYARRAY_H)
#define MYARRAY_H

#define MYARRAY_SZ 100

class MyClass;

extern MyClass myarray[];

#endif
// myarray.cpp
#include "myarray.h"
#include "myclass.h"

MyClass myarray[MYARRAY_SZ];
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.