Thread: statics in headers

  1. #1
    Registered User
    Join Date
    Jan 2007

    statics in headers

    I saw this code where lots of static variables are initialized in headers like


    static const long	TM_X = 50;
    static const long	TM_Y = 50;
    Anyone knows what happens when I include this file from ten cpp files?
    A separate instance of every variable gets created every time the header is included?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    Yes, every file gets it's own copy of the variables. Since they are const, it won't matter much. Most likely, unless you take the address of either variable, the compiler should not use any memory for the variables.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Portland, OR
    In C++, a const POD value will not be given an address in memory unless somebody attempts to take that address (pointer or reference). And even if it does create a variable, the linker should fold all the copies together at link time. This was one of the major improvements of "const" in C++.

    But the fact that you are using "static" makes it even less of a problem, since the name will not be visible outside of any one module in the first place. I wouldn't have bothered with the "static" personally, but the idea of placing a const definition in a header is totally legitimate -- C++ is attempting to eradicate most usages of the preprocessor, and this is one of the cases where it was specifically meant for.
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  2. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM
  3. Headers that use each other
    By nickname_changed in forum C++ Programming
    Replies: 7
    Last Post: 10-03-2003, 04:25 AM
  4. how do you handle all your headers?
    By mart_man00 in forum Linux Programming
    Replies: 0
    Last Post: 06-16-2003, 03:17 PM