Jump to content


Linking to constants


2 replies to this topic

#1 Reedbeta

    DevMaster Staff

  • Administrators
  • 4979 posts
  • LocationBellevue, WA

Posted 15 November 2007 - 12:07 AM

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:
reedbeta.com - developer blog, OpenGL demos, and other projects

#2 Dia

    DevMaster Staff

  • Administrators
  • 1097 posts

Posted 15 November 2007 - 01:36 AM

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};


#3 Reedbeta

    DevMaster Staff

  • Administrators
  • 4979 posts
  • LocationBellevue, WA

Posted 15 November 2007 - 02:42 AM

Thanks Dia! I knew it was going to be something simple like that.
reedbeta.com - developer blog, OpenGL demos, and other projects





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users