I am writing some code where I need to have a class variable, a static int array. I understand that I can do this with something like this in the header file, Ah:
#ifndef A_H_
#define A_H_
class A
{
public:
static const int a[];
};
const int A::a[] = {1,2};
#endif
This works fine if I include this header in only one other file, something like the following: main.cpp:
#include "A.h"
#include <iostream>
using namespace std;
int main()
{
A myA;
cout << "0: " << myA.a[0] << endl;
cout << "1: " << myA.a[1] << endl;
}
But suppose I need my class A to be a little more complicated, and I want to have an A.cpp file. I will save the main.cpp file the same way, but then change Ah as follows (I just added a function, printA):
#ifndef A_H_
#define A_H_
class A
{
public:
void printA() const;
static const int a[];
};
const int A::a[] = {1,2};
#endif
And then in the A.cpp file:
#include "A.h"
#include <iostream>
using namespace std;
void A::printA() const
{
cout << "Printing in A.cpp." << endl;
cout << "A.0: " << a[0] << endl;
cout << "A.1: " << a[1] << endl;
}
Compiling Ao with gcc -o Ao -c A.cpp is fine. But linking this when compiling main.cpp (gcc -o atest main.cpp Ao) fails with the "multiple definition" A :: a ".
, , , " ", , , extern , ( ). static, extern, ? , extern, , ( " " ).
, : , ? , ?