Static const variables cause linker problems under Qt

Discussion in 'C++' started by Rune Allnor, Feb 5, 2010.

  1. Rune Allnor

    Rune Allnor Guest

    Hi all.

    I have a template class where I have defined some
    constants in a header file, along the lines of

    ////////////////////////////////////////////
    class flags{
    static const size_t flag;
    };

    const size_t flags::flag = 1;
    ////////////////////////////////////////////

    This compiles and runs nicely in the Boost.Test program,
    but when I try to use the template class in a Qt GUI program,
    the linker starts complaining about the constants as being
    multiple defined objects:

    - in main.obj
    - in moc_myfile.obj
    - in myfile.obj

    I have included the standard guard about multiple inclucions
    of the header files, and I can see why these constants would
    appear in myfile.obj, as I include the file where they are declared
    from myfile.h. However, I have no idea why the constants should
    be available in main.obj or moc-myfile.obj - that's where Qt come
    in to do its thing.

    There isn't much I can do about the ways Qt twists and turns
    the code into an executable, so I suppose my only hope
    is to be able to resolve the 'multiple definition' problem.

    Any hints on how to do this?

    The flags class will exist in millions of instances, so I can not
    afford to include the flag definintions as const variables in the
    class.

    Rune
    Rune Allnor, Feb 5, 2010
    #1
    1. Advertising

  2. Rune Allnor wrote:
    > I have a template class where I have defined some
    > constants in a header file,


    *Never* define your static data that you might want to link to, in a
    header. *Always* define them in *one of the source files*. As soon as
    you do that, your linker problems will disappear.

    Const or no const plays no role here.

    > along the lines of
    > [..]


    V
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask
    Victor Bazarov, Feb 5, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Martin Magnusson

    Linker error with static const field

    Martin Magnusson, Oct 20, 2003, in forum: C++
    Replies:
    2
    Views:
    434
    Ron Natalie
    Oct 20, 2003
  2. Rakesh Sinha
    Replies:
    4
    Views:
    1,842
    Rakesh Sinha
    Jan 13, 2005
  3. Dave
    Replies:
    10
    Views:
    35,240
    Ron Natalie
    May 22, 2005
  4. Javier
    Replies:
    2
    Views:
    548
    James Kanze
    Sep 4, 2007
  5. er
    Replies:
    3
    Views:
    375
Loading...

Share This Page