 |
 |
C++ undefined symbols problem using a const static char array
|
 |
|
 |
|
Fresh-Faced Recruit
Join Date: Jul 2001
Location: San Diego, CA
Status:
Offline
|
|
I am having a problem using a const static char array as a class data member. Below is a simplification of my problem. The variable sStatic can be declared and initialized, but simply can't be accessed.
Thanks for any help,
Harvo
The compile command:
%> c++ t.cpp
The compiler response:
/usr/bin/ld: Undefined symbols:
__4Test.sStatic
The source file (each of the cerr statements alone produces the above error):
#include <iostream>
class Test {
public:
const static char sStatic[][15] = { "hello", "goodbye" };
Test() {
cerr << Test::sStatic[0] << endl;
cerr << sStatic[0] << endl;
}
};
int main() {
Test t;
cerr << t.sStatic[0] << endl;
cerr << Test::sStatic[0] << endl;
return 0;
}
|
|
|
| |
|
|
|
 |
|
 |
|
Mac Elite
Join Date: Sep 2000
Location: Tempe, AZ
Status:
Offline
|
|
It's been a while since I've played with C++, but IIRC, you need to initialize your static const outside of the class definition so it's got file scope. Try this...
<BLOCKQUOTE><font size="1"face="Geneva, Verdana, Arial">code:</font><HR><pre><font size=1 face=courier>
#include <iostream>
class Test {
public:
const static char sStatic[][<font color = blue>15</font>];
Test() {
cerr << Test::sStatic[<font color = blue>0</font>] << endl;
cerr << sStatic[<font color = blue>0</font>] << endl;
}
};
Test::sStatic = { <font color = red>"hello"</font>, <font color = red>"goodbye"</font> };
</font>[/code]
|
Geekspiff - generating spiffdiddlee software since before you began paying attention.
|
| |
|
|
|
 |
|
 |
|
Fresh-Faced Recruit
Join Date: Jul 2001
Location: San Diego, CA
Status:
Offline
|
|
I tried you're idea, and you're close. Below is what actually worked. The initialization of the variable requires the same declaration without the "static" keyword.
Thanks
#include <iostream>
class Test {
public:
const static char sStatic[][15];
Test() {
cerr << Test::sStatic[0] << endl;
cerr << sStatic[0] << endl;
}
};
const char Test::sStatic[][15] = { "hello", "goodbye" };
int main() {
Test t;
cerr << t.sStatic[0] << endl;
cerr << Test::sStatic[0] << endl;
return 0;
}
|
|
|
| |
|
|
|
 |
|
 |
|
Professional Poster
Join Date: Apr 2001
Location: Long Beach, CA
Status:
Offline
|
|
In addition, I don't believe class member variables can be initialized inside the class definition. You have to create a constructor to initialize the variables. (of course, if they're public, you can initialize them however you want.)
|

ACSA 10.4/10.3, ACTC 10.3, ACHDS 10.3
|
| |
|
|
|
 |
 |
|
 |
|
|
|
|
|

|
|
 |
Forum Rules
|
 |
 |
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
|
HTML code is Off
|
|
|
|
|
|
 |
 |
 |
 |
|
 |