Defining an array in a .h file.

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.
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.
closed account (yUq2Nwbp)
i think in ar.h you must write int arch[5];

and in main.cpp before main() write extern arch[5];
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:

g++ main.cpp ar.cpp

Good luck!
Topic archived. No new replies allowed.