0

So, I've tried to run the simplest C++ program imaginable in Visual Studio 2022:

main.cpp:

#include "TestClass.h"

int main() {
    TestClass().testMethod();
}

TestClass.h:

#pragma once
class TestClass {
public:
    void testMethod();
};

TestClass.cpp:

#include "TestClass.h"

inline void TestClass::testMethod() {

}

But for some reason, I get nothing but a linker error:

error LNK2019: unresolved external symbol "public: void __cdecl TestClass::testMethod(void)" (?testMethod@TestClass@@QEAAXXZ) referenced in function main

I know that there are tons of questions on Stack Overflow discussing that specific error, but I wasn't able to find anything that applied to my situation, except for this one, which doesn't have an answer.

All files are included in the project (everything was generated in Visual Studio), I do not get any warnings from IntelliSense, and every file on its own compiles just fine (using Ctrl+F7)

I have no clue what is going on and would appreciate any help.

Toasdn
  • 35
  • 1
  • 5
  • 4
    `inline void TestClass::testMethod() {` your bug is `inline` remove it and leave the rest. – drescherjm Apr 20 '22 at 18:19
  • Does this answer your question? [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Ken White Apr 20 '22 at 18:25
  • @drescherjm Removing `inline` doesn't change anything, besides, this is generated by VS2022 when "Move function definition" is executed – Toasdn Apr 20 '22 at 18:30
  • @KenWhite Thanks, but if one of the 37 answers has the solution that I need, I'm not capable of understanding and applying it correctly. – Toasdn Apr 20 '22 at 18:33
  • 1
    I just tried it with VS2022. The `inline` is the culprit for sure. Also, the `inline` generated by VS2022 is incorrect. [Apparently](https://stackoverflow.com/q/43245545/3740047), the function is meant for moving code to the header. – Sedenion Apr 20 '22 at 19:16
  • After restarting Visual Studio, everything worked without the `inline`. Thank you all! – Toasdn Apr 21 '22 at 09:09

1 Answers1

1

In C++ inline functions must have their body present in every translation unit from which they are called.

Removing inline doesn't change anything

Try to test it. I'm not the only one who proves that inline causes the lnk error. As Sedenion says, it's a usage error.

I recommend reporting this wrong behavior to Developer Community and posting the link in this thread.

Minxin Yu - MSFT
  • 2,234
  • 1
  • 3
  • 14
  • There already is a request to fix it: [https://developercommunity.visualstudio.com/t/Move-Definition-Location-should-not-add/1015726](https://developercommunity.visualstudio.com/t/Move-Definition-Location-should-not-add/1015726) – Toasdn Apr 21 '22 at 09:16