Search code examples
c++gccdlllinkerundefined-symbol

Linker error; static variable in struct not found


I'm working on (someone else's) code where a dynamic library is created from several files. The file "MyStaticVector.h" contains the definition/implementation of a static vector with a fixed (templated) length.

This is compiled into a library (.dll under Windows, .so under Linux). Compiling/linking runs successfully.

MyStaticVector.h:
----------------

template< unsigned VectorLength >
struct MyStaticVector
{
    static const unsigned uNumberOfElements = VectorLength;

    MyStaticVector()
    {
    }
}

My problem is, that this works under MSVC11/debug+release and GCC/release. But using GCC/debug, I get an error at runtime, that the symbol for "uNumberOfElements" con't be found. Can you explain, why?


Solution

  • The template parameters must be established at compile time - in this case, the compile time of the DLL. This is because each instance of the template will be a different class. It is at this point where it will create the symbols 'uNumberOfElements' for each value that it needs.

    Now, if you attempt to do use a class (or template instance) that didn't exist during compile time, then it'll try to use a class that it hasn't made, and the symbol won't exist.