Reputation: 11908
I have some simple hypothetical static class in C++:
#ifndef __STAT_H_
#define __STAT_H_
class Stat {
private:
static vector<int> v;
public:
static void add_num(int num);
static void clear_nums();
static void get_count();
};
#endif
And the ccp file is so:
#include "Stat.h"
vector<int> v;
void Stat::add_num(int num) {
v.push_back(num);
}
void Stat::clear_nums() {
v.clear();
}
int Stat::get_num_count() {
return v.size();
}
Now when I include in main.cpp file "Stat.h" and try to use some static method:
Stat::add_num(8);
the error during compilation is
undefined reference to 'Stat::add_num(int)'
What can be the problem in this case? Thank you.
EDIT: sorry about addresses vector, it should be v there
Upvotes: 0
Views: 797
Reputation: 59489
Here's my take on your program, just for reference sake.
Stat.h
#ifndef STAT_H
#define STAT_H
#include <vector>
using std::vector;
class Stat
{
public:
static void add_num(int num);
static void clear_nums();
static int get_count();
private:
static vector<int> v;
};
#endif
Stat.cpp
#include "Stat.h"
vector<int> Stat::v;
void Stat::add_num(int num) { v.push_back(num); }
void Stat::clear_nums() { v.clear(); }
int Stat::get_count() { return v.size(); }
main.cpp
#include "Stat.h"
int main()
{
Stat s;
s.add_num(8);
}
Makefile
CC = g++
OBJS = Stat.o
DEBUG = -g
CFLAGS = -Wall -c $(DEBUG)
LFLAGS = -Wall $(DEBUG)
all: build clean
build: $(OBJS)
$(CC) main.cpp $(LFLAGS) $(OBJS) -o stat
Stat.o: Stat.h
$(CC) $(CFLAGS) Stat.cpp
clean:
-rm -f *.o
Upvotes: 1
Reputation: 45410
You need to link Stat.o in g++ command, say:
g++ -c -o Stat.o Stat.cpp
g++ -o Stat main.cpp Stat.o
I guess in your Stat.cpp:
vector<int> v;
should be:
vector<int> Stat::v;
There is no compile error if you define local v in Stat.cpp but I guess you intent to use Stat::v
Upvotes: 1
Reputation: 800
It sounds like you have not included stat.cpp in compilation. So your linker cannot find an implementation for the static methods.
Upvotes: 3