Johan Elmander
Johan Elmander

Reputation: 656

how to use a static vector inside a static function

I am try to use vector<int> myVector2, however, I have trouble it to use on a static function (foo). I use Qt and here is the default code below:

   Mainwindow.h
---------------------------------------------------
#include <QMainWindow>
#include <vector>
#include <iostream>
#include <QString>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    static std::vector<int> myVector2;
    static void foo();
private:
    Ui::MainWindow *ui;

};

.....

mainwindow.cpp
------------------------------
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foo;

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::foo(){
    MainWindow::myVector2.push_back(3);

}

I just added static std::vector<int> myVector2; static void foo(); to header and void MainWindow::foo(){ MainWindow::myVector2.push_back(3); } on the above code. when I compile it, I get such error:

mainwindow.o: In function `MainWindow::foo()':
mainwindow.cpp:(.text+0xe7): undefined reference to `MainWindow::myVector2'
mainwindow.cpp:(.text+0xee): undefined reference to `MainWindow::myVector2'
mainwindow.cpp:(.text+0x10e): undefined reference to `MainWindow::myVector2'
mainwindow.cpp:(.text+0x126): undefined reference to `MainWindow::myVector2'
collect2: error: ld returned 1 exit status
make: *** [ddd] Error 1
14:46:36: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project ddd (kit: Desktop)
When executing step 'Make'

if I remove static before the vector and function, then it compiles fine but I want these two to be accessible directly.

How is it possible to fix the above code?

Upvotes: 0

Views: 1539

Answers (3)

Tomek
Tomek

Reputation: 4659

Add

std::vector<int> MainWindow::myVector2;

to mainwindow.cpp.

BTW:

This

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foo;

}

probably should be:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foo(); // <- note () here;

}

Upvotes: 5

masoud
masoud

Reputation: 56519

You need to define that vector, put this outside the class declaration in the implementation file (.cpp):

std::vector<int> MainWindow::myVector2;

Upvotes: 1

Alex F
Alex F

Reputation: 43331

Add this to mainwindow.cpp:

std::vector<int> MainWindow::myVector2;

When you declare static myVector2 in MainWindow class, this is kind of forward declararion. You need to create the variable in one of .cpp file to get it working.

Upvotes: 1

Related Questions