C++ Undefined Reference (Even with Include)

2020-07-06 06:47发布

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

标签: c++ include
2条回答
Bombasti
2楼-- · 2020-07-06 07:17

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.

查看更多
对你真心纯属浪费
3楼-- · 2020-07-06 07:24

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
查看更多
登录 后发表回答