1

I am just coding various scenarios for static, const and global variables, to see where they work and where they don't.

Following code is giving me weird collect2: error: ld returned 1 exit status.

Code:

#include <iostream>
#include <string>
#include <vector>

using namespace std;
const static int gl = 4;
class Static{
    private:
            int nonStatic;
            const static int count = 10;
            //constexpr static string str;
            static vector<string> svec;
    public:
            static vector<string> initVector();
            void printVector();
            Static(int s=0): nonStatic(s){}
            ~Static(){}

};

vector<string> Static::initVector()
{
        for(int i=0; i<5; i++)
    {
            string str;
            cin>>str;
            svec.push_back(str);
    }
}

void Static::printVector()
{
    for(auto const i: svec)
            cout<<i;
}

int main()
{
    Static state(4);
    return 0;
}

It shows the following ld error message:

/tmp/ccsX2Fre.o: In function `Static::initVector[abi:cxx11]()':
StaticTests.cpp:(.text+0x4e): undefined reference to `Static::svec[abi:cxx11]'
/tmp/ccsX2Fre.o: In function `Static::printVector()':
StaticTests.cpp:(.text+0xc4): undefined reference to `Static::svec[abi:cxx11]'
collect2: error: ld returned 1 exit status
StewieGGriffin
  • 349
  • 1
  • 4
  • 14

1 Answers1

4

static std::vector<std::string> svec; declares a static object named svec of type std::vector<std::string>. You have to define it as well. After the definition of Static add the definition:

std::vector<std::string> Static::svec;

And to answer the next question, the declaration of count is also a definition because it has an initializer. As long as you don't take its address you don't need a separate definition.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165