code

LNK2019 오류를 해결하는 방법 : 해결되지 않은 외부 기호-기능?

codestyles 2020. 9. 12. 10:03
반응형

LNK2019 오류를 해결하는 방법 : 해결되지 않은 외부 기호-기능?


이 오류가 발생하지만 해결 방법을 모르겠습니다.

저는 Visual Studio 2013을 사용하고 있습니다. 솔루션 이름을 MyProjectTest로 지정했습니다. 이것은 테스트 솔루션의 구조입니다.

구조

- 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;
}

저는 초보자입니다. 이것은 간단한 프로그램이며 오류없이 실행됩니다. 나는 인터넷에서 읽고 단위 테스트에 관심이 생겨서 테스트 프로젝트를 만들었습니다.

파일> 새로 만들기> 프로젝트 ...> 설치됨> 템플릿> Visual C ++> 테스트> 네이티브 단위 테스트 프로젝트>

이름 : UnitTest1 솔루션 : 솔루션에 추가 그런 다음 현재 열려있는 솔루션의 경로로 자동 전환 된 위치 다음은 솔루션의 폴더 구조입니다.

폴더 구조

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)


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 Visual Studio solution tree right click on the project 'UnitTest1' then Add -> Existing item -> choose the file ../MyProjectTest/function.cpp


Since I want my project to compile to a standalone EXE, I linked the UnitTest project to the function.obj file generated from the 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 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 was causing a link 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 down what was missing by reading through the error and provided the definition outside the class to clear this up.


This happened to me so I thought I might share my solution, as simple as it was:

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 libs where in Unicode.
My function was using a TCHAR as parameter. As a result in my lib my TCHAR was transformed into a WCHAR but it was a char* on my UnitTest: the symbol were different because the parameters were really not the same in the end.


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

<ClCompile Include="file.cpp" />

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.

자세한 내용 은 MSDN 블로그 에서 Visual Studio의 C ++ 단위 테스트 를 참조하세요. 또한 확인할 수 있습니다 Visual Studio에서 C / C ++에 대한 쓰기 단위 테스트를 뿐만 아니라 Visual Studio에서 사용 C에 대한 Microsoft 유닛 테스트 프레임 워크 ++ , 후자의 존재는 당신이 아닌 공공 회원들과 동일한 프로젝트에서 테스트를 넣어 필요성을 테스트해야하는 경우 실제 코드로.

테스트하려는 항목은 __declspec(dllexport). 자세한 내용은 __declspec (dllexport)사용하여 DLL에서 내보내기 를 참조하십시오.

참고 URL : https://stackoverflow.com/questions/19886397/how-to-solve-the-error-lnk2019-unresolved-external-symbol-function

반응형