Please nominate your Qt Champions for 2021!

Linker Error when linking member variables from different file

  • Hi,

    so in Qt Creator I get a weird linker error when I want to link a member variable from a different file. Pretty much like this:


    @class Class {
    static double vector[10];


    @double Class::vector[] = {

    It always get this:

    class.obj : error LNK2001: unresolved external symbol "private: static double * Class::vector" (?vector@Class@@0PANA)
    debug\Class.exe : fatal error LNK1120: 1 unresolved externals

    I don't know what's wrong with the linker. It works perfectly fine for a regular projekt in Visual Studio.

  • It's kind of unusual to have the class declaration in "Class.h" but the definition (implementation) of class' members not in "Class.cpp" but some other .cpp file. Anyway, this of course should not be the reason for an error, as long as the .cpp file where it is implemented is actually compiled and linked into the project. Are you 100% sure that this is happening?

    And why it says "private" in the error message, when it's declared public?

    Do you include "Class.h" from "Vector.cpp" ???

  • I put it in a different cpp file, because the array is very large, so it won't mess up the header file. I just put in 10 for testing. I also tried around with private/public. seems I messed up the copy&paste.

    How can I make sure it's compiled properly?

    I added vector.cpp to sources in the .pro file and it includes class.h.
    Is there something else I need to do?

  • Can't you see from the compiler and linker logs whether "vector.cpp" is compiled to "vector.o" and whether "vector.o" is linked in?

    BTW: What I mean is that "normally" you would put the class' declaration into a file called "Class.h" and all of its member variables and functions into a file called "Class.cpp". If Class::vector definition is so large that you don't want to have it in "Class.cpp", you could put it into a separate file called "Class_private.h", which you include from "Class.cpp" (not from "Class.h").

  • Oh I see. So I followed your advice and now it compiles and links without errors. Thanks

Log in to reply