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.
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.
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.
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];
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.