954,178 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

[Linker error] undefined reference to...

////////////////////////
/////counter.h file/////
////////////////////////
#ifndef _COUNTER_H
#define _COUNTER_H
class Counter{

    private:
       int counter;
       int limit;
       static int nCounters;
    public:
        Counter(int arg, int arg);
        void increment();
        void decrement();
        int getValue();
        static int getNCounters();
};
#include "counter.cpp"
#endif

//////////////////////////
/////counter.cpp file/////
//////////////////////////
#include <string>
#include "counter.h"

Counter::Counter(int a, int b){
   counter=a;
   limit=b;
   if (&nCounters==NULL){
   nCounters=0;
   }  
   nCounters++;
}

void Counter::increment()
{
    if (counter<limit) counter++;

 }
void Counter::decrement()
{
  if(counter>0) counter--;
}

int Counter::getValue(){
return counter;
}

int Counter::getNCounters(){
int dummy=nCounters;
return dummy;
}


I'm getting a linker error every time I try to access nCounters.
so i get this result when compiling:
[Linker error] undefined reference to `Counter::nCounters'
[Linker error] undefined reference to `Counter::nCounters'
[Linker error] undefined reference to `Counter::nCounters'
ld returned 1 exit status

bamcclur
Newbie Poster
20 posts since Nov 2009
Reputation Points: 11
Solved Threads: 4
 

Add this line of code into your "counter.pp" file

int Counter::nCounters = 0;
sfuo
Practically a Master Poster
655 posts since Jul 2009
Reputation Points: 164
Solved Threads: 99
 

Make sure that you include all the necessary files to compile the project. I would also consider if you need the variables to be static, if that is the case you should declare them at the top of the counter.cpp file.

zortec
Junior Poster
144 posts since Nov 2009
Reputation Points: 21
Solved Threads: 16
 

Pop int Counter::nCounters; at the top of your counter.cpp file. http://www.cs.loyola.edu/~lawrie/CS301/F03/StaticClassMembers.htm

Also, you don't need to include your cpp file in your h file.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

Wow that's like a 3-way tie there...

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

from the replies you have received, I think you should be satisfied, so kindly mark this thread as solved and add some reputation points to those who helped.
"Show me your code and I will tell you who you are.."-Tkud

tkud
Posting Whiz in Training
235 posts since Sep 2009
Reputation Points: 13
Solved Threads: 46
 

Thanks for the help.

bamcclur
Newbie Poster
20 posts since Nov 2009
Reputation Points: 11
Solved Threads: 4
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You