PDA

View Full Version : Linking to constants


Reedbeta
11-14-2007, 04:07 PM
Okay, I'm sure I'm just missing something completely obvious here, but I cannot figure out why this does not work.

data.cpp:

const unsigned char data[] = { 1, 2, 3, 4};


main.cpp:

extern const unsigned char data[];
int main (int argc, char **argv)
{
return data[0];
}


When I put these files into a new project in Visual C++ 7.1 and compile, 'data' is reported as an unresolved external. What am I doing wrong?! :wallbash:

Dia Kharrat
11-14-2007, 05:36 PM
C++ defaults to internal linkage for const variables, which means it's only visible to the translation unit where it's defined. What you will have to do is explicitly tell the compiler that you want to give the const variable external linkage (the compiler will then be forced to allocate storage for the constant, as opposed to simply folding it at compile-time). To do that, just add the extern keyword where you define it (data.cpp):


extern const unsigned char data[] = { 1, 2, 3, 4};

Reedbeta
11-14-2007, 06:42 PM
Thanks Dia! I knew it was going to be something simple like that.