1

I have a static method in class as follows in file Convert.h

class Convert
{
    public :
    static string convertIntToStr(unsigned int integer);    
};

In Convert.cpp

string 
Convert::convertIntToStr(unsigned int integer) 
{
    ostringstream ostr;
    ostr <<  integer;
    return ostr.str();
}

I use this in some other class method in another .cpp file as Convert::convertIntToStr, but I get linking error, which says undefined reference to Convert::convertIntToStr(unsigned int). Could you please let me know what could be wrong?

jabaldonedo
  • 25,822
  • 8
  • 77
  • 77
mickeyj
  • 91
  • 7
  • 5
    Because you don't link with the object file that the function is defined in? – Some programmer dude Jun 23 '13 at 18:57
  • And do not use `using namespace std` in a real code. (I am sorry if I am wrong and you have omitted `std::` prefix for `string` and `ostringstream` just for the sake of this example.) – Kane Jun 23 '13 at 19:03
  • 2
    Please show your compiler invocation. If using an IDE, is Convert.cpp in the list of stuff to compile *and link*? – Thomas Matthews Jun 23 '13 at 19:05
  • 1
    @АнтонЕлькин: He also might have explicit `using std::string;` and `using std::ostringstream;` declarations. – celtschk Jun 23 '13 at 19:36
  • 1
    possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – interjay Jun 24 '13 at 08:59

1 Answers1

0

With multiple cpp file, you have to link the compiled object file into executable. In IDE like eclipse CDT or Visual stdio, It has been done for you.

To compile and link by yourself, with gcc for example, write Makefile:

CC=g++
CPPFLAGS=-fPIC -Wall -g -O2
all:executable

executable: convert.o other.o 
    $(CC)  $(CPPFLAGS) -o $@ $^

convert.o: convert.cpp
    $(RC) $^

other.o: other.cpp
    $(CC) -o $@ -c $^



.PHONY:clean

clean:
    rm *.o executable
lulyon
  • 6,707
  • 7
  • 32
  • 49