I keep getting undefined references to static members every time I try to compile the following code:
main.cpp:
#include <iostream>
#include <iomanip>
#include "Obj1.h"
using namespace std;
int main(){
double value;
cout << "Enter shared val: ";
cin >> value;
obj1::initialize(value); //static member function called
obj1 object;
cout << "\nValue: " << object.getSharedVal();//prints static member var
}
Obj1.h:
#ifndef OBJ1_H
#define OBJ1_H
class obj1{
private:
static double sharedVal;
double val;
public:
obj1(){
val = 0;
}
void add(double d){
val += d;
sharedVal += d;
}
double getVal() const{
return val;
}
double getSharedVal() const{
return sharedVal;
}
static void initialize(double);
};
#endif
Obj1.cpp:
#include "Obj1.h"
double obj1::sharedVal = 0; //define static members outside class.
void obj1::initialize(double d){
sharedVal += d;
}
When I try to compile main.cpp (with g++ main.cpp
), I get the following errors:
/tmp/cc51LhbE.o: In function `main':
objectTester.cpp:(.text+0x45): undefined reference to `obj1::initialize(double)'
/tmp/cc51LhbE.o: In function `obj1::getSharedVal() const':
objectTester.cpp:(.text._ZNK4obj112getSharedValEv[_ZNK4obj112getSharedValEv]+0xc): undefined reference to `obj1::sharedVal'
collect2: error: ld returned 1 exit status
Why does this error appear?
Additionally: I'm using Geany Text Editor in Ubuntu 16.04, a text editor I am completely new to. I also notice in .h files for Geany, keywords such as private, public, and class are not boldfaced like .cpp files. Why is this?