13

I cannot get this simple piece of code to compile without including the TestClass.cpp file explicitly in my 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
Arc676
  • 4,445
  • 3
  • 28
  • 44

2 Answers2

21

Include TestClass.cpp into the commandline, so the linker can find the function definition:

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

Alternatively, compile each to their own object file, then tell the compiler to link them together (it will forward 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
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • 1
    How strange! I have never encountered this problem before. I am new to C++ and I think I have always had an IDE do this for me. No wonder! Thanks! –  Mar 26 '09 at 20:31
  • 3
    @Scott - This is why you should spend some time in command line ;). It make clear things IDE hides from you... – Darius Kucinskas Mar 26 '09 at 20:42
  • I have to disagree with renaming the files. As it is, the files are named after what they contain, consistent with the case of the contents (function "main" and class "TestCase"). – camh Mar 26 '09 at 22:04
  • i agree. that would be consistent too. i will change my answer. good catch – Johannes Schaub - litb Mar 26 '09 at 22:32
0

You're not compiling and linking against TestClass.cpp (where the implementation of foo() is). The compiler is thus complaining that your trying to use an undefined function.

Assaf Lavie
  • 73,079
  • 34
  • 148
  • 203