Friday, 3 February 2017

c++ - How to solve the error LNK2019: unresolved external symbol - function?

I get this error, but I don't know how to fix it.


I'm using Visual Studio 2013. I made the solution name MyProjectTest
This is the structure of my test solution:


The structure


-function.h


#ifndef MY_FUNCTION_H
#define MY_FUNCTION_H
int multiple(int x, int y);
#endif

-function.cpp


#include "function.h"
int multiple(int x, int y){
return x*y;
}

-main.cpp


#include 
#include
#include "function.h"
using namespace std;
int main(){
int a, b;
cin >> a >> b;
cout << multiple(a, b) << endl;
system("pause");
return 0;
}

I'm a beginner; this is a simple program and it runs without error.
I read in the internet and became interested in the unit test, so I created a test project:


File > New > Project... > Installed > Templates > Visual C++ > Test > Native Unit Test Project >


Name: UnitTest1
Solution: Add to solution
Then the location auto-switched to the path of the current open solution
This is the folder structure of the solution:


Folder structure


I only edited file unittest1.cpp:


#include "stdafx.h"
#include "CppUnitTest.h"
#include "../MyProjectTest/function.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestEqual)
{
Assert::AreEqual(multiple(2, 3), 6);
// TODO: Your test code here
}
};
}

But I get error LNK2019: unresolved external symbol.
I know that the implementation of function multiple is missing.
I tried to delete the function.cpp file and I replaced the declaration with the definition, and it run. But writing both declaration and definition in the same file is not recommended.
How can I fix this error without doing that? Should I replace with #include "../MyProjectTest/function.cpp" in file unittest.cpp?
(I'm not good at English very much. Thanks)

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...