Here's the body of main.cpp
#include "Header.h"
int main()
{
auto f = Foo();
f.bar();
return 0;
}
Here's the body of Header.h
class Foo {
public:
void bar();
};
Here's the body of Source.cpp
#include <iostream>
class Foo {
public:
void bar() {
std::cout << "Foo.bar() called\n";
}
};
void t() {
auto f = Foo();
f.bar(); // If this line isn't here, the project won't compile
}
When I comment out f.bar();
in Source.cpp, I receive the following error upon compilation. It's telling me that f.bar()
in main()
is unresolved:
Error LNK2019 unresolved external symbol "public: void __thiscall Foo::bar(void)" (?bar@Foo@@QAEXXZ) referenced in function _main ...
I understand that it's common to define methods outside of class scope, and indeed the following version of Source.cpp compiles successfully--
#include <iostream>
#include "Header.h"
void Foo::bar() {
std::cout << "Foo.bar() called\n";
}
Nonetheless, I don't understand what's wrong with the original version. It feels like something mysterious and magical is going on that I don't fully understand.
Foo::bar()
is called but it doesn't have a body. β Hatted RoosterFoo
twice. β Hayt