Thread: Multiple definition issue when using static const

  1. #1
    Registered User
    Join Date
    Sep 2019

    Multiple definition issue when using static const

    Hello, I defined this as a private member of my class:

    static const Vec3f normals [7];
    and then try to initialize it outside the class:

    const Vec3f BVolume::normals [7] = {{1,0,0},{0,1,0},{0,0,1},{SQRT3_3,SQRT3_3,SQRT3_3},{-SQRT3_3,SQRT3_3,SQRT3_3},
    This in a header file. When trying to compile it, I receive three error messages like
    /media/34GB/demos/asmfrt/TextManager.cpp|352|multiple definition of `BVolume::normals'|
    Two of them at the end of classes. How it cn be solved?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Two options come to mind:
    • Declare normals in the class definition (which is what you're already doing) then define and initialise it in exactly one source file rather than in the header (i.e., move it from the header to exactly one source file).
    • Declare normals with constexpr and define and initialise it in the class definition:
      static constexpr Vec3f normals[7] = {{1, 0, 0},
                                           {0, 1, 0},
                                           {0, 0, 1},
                                           {SQRT3_3, SQRT3_3, SQRT3_3},
                                           {-SQRT3_3, SQRT3_3, SQRT3_3},
                                           {-SQRT3_3, -SQRT3_3, SQRT3_3},
                                           {SQRT3_3, -SQRT3_3, SQRT3_3}};
      Of course, I'm assuming that SQRT3_3 can be used in a constexpr context, e.g., it is itself a constexpr, a const initialised at compile time, an enum, a macro constant.
    Last edited by laserlight; 09-14-2020 at 04:35 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 20
    Last Post: 04-14-2019, 02:58 PM
  2. Replies: 2
    Last Post: 05-10-2017, 06:27 AM
  3. Replies: 8
    Last Post: 01-19-2009, 07:42 PM
  4. Replies: 7
    Last Post: 04-28-2008, 09:20 AM

Tags for this Thread