[c++] How can I 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 <iostream>
#include <cstdlib>
#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 on the Internet and became interested in the unit test, so I created a test project:

Menu 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 ran. 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 it with #include "../MyProjectTest/function.cpp" in file unittest.cpp?

This question is related to c++ testing error-handling lnk2019

The answer is


One option would be to include function.cpp in your UnitTest1 project, but that may not be the most ideal solution structure. The short answer to your problem is that when building your UnitTest1 project, the compiler and linker have no idea that function.cpp exists, and also have nothing to link that contains a definition of multiple. A way to fix this is making use of linking libraries.

Since your unit tests are in a different project, I'm assuming your intention is to make that project a standalone unit-testing program. With the functions you are testing located in another project, it's possible to build that project to either a dynamically or statically linked library. Static libraries are linked to other programs at build time, and have the extension .lib, and dynamic libraries are linked at runtime, and have the extension .dll. For my answer I'll prefer static libraries.

You can turn your first program into a static library by changing it in the projects properties. There should be an option under the General tab where the project is set to build to an executable (.exe). You can change this to .lib. The .lib file will build to the same place as the .exe.

In your UnitTest1 project, you can go to its properties, and under the Linker tab in the category Additional Library Directories, add the path to which MyProjectTest builds. Then, for Additional Dependencies under the Linker - Input tab, add the name of your static library, most likely MyProjectTest.lib.

That should allow your project to build. Note that by doing this, MyProjectTest will not be a standalone executable program unless you change its build properties as needed, which would be less than ideal.


In the Visual Studio solution tree, right click on the project 'UnitTest1', and then Add ? Existing item ? choose the file ../MyProjectTest/function.cpp.


Since I want my project to compile to a stand-alone EXE file, I linked the UnitTest project to the function.obj file generated from function.cpp and it works.

Right click on the 'UnitTest1' project ? Configuration Properties ? Linker ? Input ? Additional Dependencies ? add "..\MyProjectTest\Debug\function.obj".


I just ran into this problem in Visual Studio 2013. Apparently now, having two projects in the same solution and setting the the dependencies is not enough. You need to add a project reference between them. To do that:

  1. Right-click on the project in the solution explore
  2. Click Add => References...
  3. Click the Add New Reference button
  4. Check the boxes for the projects that this project relies on
  5. Click OK

It turned out I was using .c files with .cpp files. Renaming .c to .cpp solved my problem.


Another way you can get this linker error (as I was) is if you are exporting an instance of a class from a DLL file, but have not declared that class itself as import/export.

#ifdef  MYDLL_EXPORTS
   #define DLLEXPORT __declspec(dllexport)
#else
   #define DLLEXPORT __declspec(dllimport)
#endif

class DLLEXPORT Book // <--- This class must also be declared as export/import
{
    public:
        Book();
        ~Book();
        int WordCount();
};

DLLEXPORT extern Book book; // <-- This is what I really wanted, to export book object

So even though primarily I was exporting just an instance of the Book class called book above, I had to declare the Book class as export/import class as well otherwise calling book.WordCount() in the other DLL file was causing a link error.


Check the character set of both projects in Configuration Properties ? General ? Character Set.

My UnitTest project was using the default character set Multi-Byte while my libraries were in Unicode.

My function was using a TCHAR as a parameter.

As a result, in my library my TCHAR was transformed into a WCHAR, but it was a char* in my UnitTest: the symbol was different because the parameters were really not the same in the end.


In my case, set the cpp file to "C/C++ compiler" in "property"->"general", resolve the LNK2019 error.


I just discovered that LNK2019 occurs during compilation in Visual Studio 2015 if forgetting to provide a definition for a declared function inside a class.

The linker error was highly cryptic, but I narrowed it down to what was missing by reading through the error and provided the definition outside the class to clear this up.


In Visual Studio 2017 if you want to test public members, simply put your real project and test project in the same solution, and add a reference to your real project in the test project.

See C++ Unit Testing in Visual Studio from the MSDN blog for more details. You can also check Write unit tests for C/C++ in Visual Studio as well as Use the Microsoft Unit Testing Framework for C++ in Visual Studio, the latter being if you need to test non public members and need to put the tests in the same project as your real code.

Note that things you want to test will need to be exported using __declspec(dllexport). See Exporting from a DLL Using __declspec(dllexport) for more details.


For me it works if I add this line below in .vcxproj in the itemGroup cpp file, which is connected to the header file.

<ClCompile Include="file.cpp" />

Questions with c++ tag:

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++ How to enable C++17 compiling in Visual Studio? Remove from the beginning of std::vector Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? What is (x & 1) and (x >>= 1)? What are the new features in C++17? Visual Studio Code includePath Compiling an application for use in highly radioactive environments "No rule to make target 'install'"... But Makefile exists How to build and use Google TensorFlow C++ api Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) Converting std::__cxx11::string to std::string lvalue required as left operand of assignment error when using C++ How to overcome "'aclocal-1.15' is missing on your system" warning? MSVCP140.dll missing How to get image width and height in OpenCV? CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found Reading json files in C++ What exactly is std::atomic? Compile c++14-code with g++ Visual Studio 2015 doesn't have cl.exe Visual Studio 2013 error MS8020 Build tools v140 cannot be found CMake does not find Visual C++ compiler Casting int to bool in C/C++ C++ How do I convert a std::chrono::time_point to long and back How can I get the size of an std::vector as an int? Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); Fatal error: iostream: No such file or directory in compiling C program using GCC unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2 How to end C++ code How to change text color and console color in code::blocks? Error: stray '\240' in program invalid use of non-static member function Convert float to string with precision & number of decimal digits specified? enum to string in modern C++11 / C++14 / C++17 and future C++20 Passing capturing lambda as function pointer How do I add a library path in cmake? error: expected primary-expression before ')' token (C) undefined reference to 'std::cout' java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader fatal error: mpi.h: No such file or directory #include <mpi.h>

Questions with testing tag:

Test process.env with Jest How to configure "Shorten command line" method for whole project in IntelliJ Jest spyOn function called Simulate a button click in Jest Mockito - NullpointerException when stubbing Method toBe(true) vs toBeTruthy() vs toBeTrue() How-to turn off all SSL checks for postman for a specific site What is the difference between smoke testing and sanity testing? ReferenceError: describe is not defined NodeJs How to properly assert that an exception gets raised in pytest? How do you print in a Go test using the "testing" package? How do I install jmeter on a Mac? How to run only one unit test class using Gradle Select a date from date picker using Selenium webdriver Exception in thread "main" java.lang.Error: Unresolved compilation problems How to identify and switch to the frame in selenium webdriver when frame does not have id How can I solve the error LNK2019: unresolved external symbol - function? How to select option in drop down protractorjs e2e tests Selenium and xpath: finding a div with a class/id and verifying text inside Integration Testing POSTing an entire object to Spring MVC controller How to type in textbox using Selenium WebDriver (Selenium 2) with Java? How can I test that a variable is more than eight characters in PowerShell? Spring Test & Security: How to mock authentication? What is the difference between mocking and spying when using Mockito? iOS Simulator to test website on Mac Switch tabs using Selenium WebDriver with Java How to check if a string array contains one string in JavaScript? Automated testing for REST Api How to check whether dynamically attached event listener exists or not? ScalaTest in sbt: is there a way to run a single test without tags? How to test an SQL Update statement before running it? Load vs. Stress testing Verify a method call using Moq Selenium: Can I set any of the attribute value of a WebElement in Selenium? Is there any publicly accessible JSON data source to test with real world data? How to test code dependent on environment variables using JUnit? How to mock private method for testing using PowerMock? WebDriver: check if an element exists? How to test my servlet using JUnit How to create unit tests easily in eclipse How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes? What's the difference between unit, functional, acceptance, and integration tests? Trying to mock datetime.date.today(), but not working How to write a test which expects an Error to be thrown in Jasmine? Gradle: How to Display Test Results in the Console in Real Time? Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows) What's the difference between a mock & stub? Writing unit tests in Python: How do I start? Difference between acceptance test and functional test? jquery (or pure js) simulate enter key pressed for testing

Questions with error-handling tag:

must declare a named package eclipse because this compilation unit is associated to the named module Error:Failed to open zip file. Gradle's dependency cache may be corrupt What does 'index 0 is out of bounds for axis 0 with size 0' mean? What's the source of Error: getaddrinfo EAI_AGAIN? Error handling with try and catch in Laravel What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? Raise error in a Bash script Javascript Uncaught TypeError: Cannot read property '0' of undefined Multiple values in single-value context IndexError: too many indices for array REST API error code 500 handling How do I debug "Error: spawn ENOENT" on node.js? How to check the exit status using an if statement Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android How to handle ETIMEDOUT error? Is there a TRY CATCH command in Bash #1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version Why is "except: pass" a bad programming practice? How can I solve the error LNK2019: unresolved external symbol - function? 400 BAD request HTTP error code meaning? Eclipse returns error message "Java was started but returned exit code = 1" live output from subprocess command Is it not possible to stringify an Error using JSON.stringify? PHP Notice: Undefined offset: 1 with array when reading data How to get error message when ifstream open fails Error:attempt to apply non-function Notice: Undefined variable: _SESSION in "" on line 9 ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration How to capture no file for fs.readFileSync()? Reference - What does this error mean in PHP? Handling a timeout error in python sockets Disabling Strict Standards in PHP 5.4 When should I use Write-Error vs. Throw? Terminating vs. non-terminating errors What is the difference between `throw new Error` and `throw someObject`? Powershell: How can I stop errors from being displayed in a script? Does Python have an argc argument? vba error handling in loop php return 500 error but no error log Error: could not find function ... in R How to catch integer(0)? Enabling error display in PHP via htaccess only Fastest way to check if a string is JSON in PHP? Deploying website: 500 - Internal server error How to fix Error: "Could not find schema information for the attribute/element" by creating schema Warning: implode() [function.implode]: Invalid arguments passed Where does PHP store the error log? (php5, apache, fastcgi, cpanel) In Python try until no error Raise warning in Python without interrupting program How do I log errors and warnings into a file? How to do error logging in CodeIgniter (PHP)

Questions with lnk2019 tag:

How can I solve the error LNK2019: unresolved external symbol - function? Error LNK2019: Unresolved External Symbol in Visual Studio LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup