C ++ Undefined Link (even with enabled)

I cannot get this simple piece of code to compile without including the TestClass.cpp file explicitly in the main.cpp file. What am I doing wrong? Thanks in advance!

Here is the code:

TestClass.h

#ifndef TESTCLASS_H_ #define TESTCLASS_H_ class TestClass { public: static int foo(); }; #endif 

Testclass.cpp

 #include "TestClass.h" int TestClass::foo() { return 42; } 

main.cpp

 #include <iostream> #include "TestClass.h" using namespace std; int main() { cout << TestClass::foo() << endl; return 0; } 

Here is the error:

 g++ main.cpp -o main.app /tmp/ccCjOhpy.o: In function `main': main.cpp:(.text+0x18e): undefined reference to `TestClass::foo()' collect2: ld returned 1 exit status 
+4
c ++ include
Mar 26 '09 at 20:27
source share
2 answers

Include TestClass.cpp in the command line, so the linker can find the function definition:

 g++ main.cpp TestClass.cpp -o main.app 

Alternatively, compile each your own object file and then tell the compiler to link them together (it will send them to the linker)

 g++ -c main.cpp -o main.o g++ -c TestClass.cpp -o TestClass.o g++ main.o TestClass.o -o main.app 
+10
Mar 26 '09 at 20:29
source share

You do not compile or link to TestClass.cpp (where the implementation of foo() implemented). Therefore, the compiler complains that you are trying to use the undefined function.

0
Mar 26 '09 at 20:31
source share