Defining an array in a .h file.
Jun 16, 2011 at 11:57am UTC
Hello, as my projects grow larger Im trying to Define an array in a header file, and use it elsewhere.
Im using Codeblocks.
ar.h
1 2 3 4 5
#ifndef ARRAY_H
#define ARRAY_H
extern int arch[5];
#endif
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include "ar.h"
using namespace std;
int main()
{
int i = 0;
for (i=0;i<5;i++ )
{
arch[i] = i;
}
cout << arch[0] << endl;
cout << arch[1] << endl;
cout << arch[2] << endl;
cout << arch[3] << endl;
cout << arch[4] << endl;
return 0;
}
my compiler spits out this error.
"undefined reference to `arch'"
How can I fix this.
Jun 16, 2011 at 12:08pm UTC
I think you misunderstand what the extern keyword does, it tells the compiler that that line is just a declaration and that the array will be defined elsewhere, you have not defined it anywhere.
Jun 16, 2011 at 12:30pm UTC
i think in ar.h you must write int arch[5];
and in main.cpp before main() write extern arch[5];
Jun 16, 2011 at 1:23pm UTC
ar.cpp
1 2 3
#include "ar.h"
int arch[5];
You must set both "ar.cpp" and "main.cpp" to compile and link in your project.
From the command-prompt, using GCC, the command would be:
Good luck!
Topic archived. No new replies allowed.