tags:

views:

483

answers:

2

Hello!

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

+6  A: 

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
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!
@Scott - This is why you should spend some time in command line ;). It make clear things IDE hides from you...
Darius Kucinskas
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
i agree. that would be consistent too. i will change my answer. good catch
Johannes Schaub - litb
A: 

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