Declare array in C++ header and define it in cpp file?

tree-hacker picture tree-hacker · Dec 8, 2010 · Viewed 63.8k times · Source

This is probably a really simple thing but I'm new to C++ so need help.

I just want to declare an array in my C++ header file like:

int lettersArr[26];

and then define it in a function in the cpp file like:

    lettersArr[26] = { letA, letB, letC, letD, letE, letF, letG, letH,
        letI, letJ, letK, letL, letM, letN, letO, letP, letQ, letR, letS,
        letT, letU, letV, letW, letX, letY, letZ };

but this doesn't work.

Have I got the syntax wrong or something? What is the correct way to to this?

Thanks a lot.

Answer

aschepler picture aschepler · Dec 8, 2010

Add extern to the declaration in the header file.

extern int lettersArr[26];

(Also, unless you plan to change the array, consider also adding const.)

The definition must have a type. Add int (or const int):

int lettersArr[26] = { letA, /*...*/ };