Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

정적 라이브러리 참조 시 "LNK2019 unresolved external symbol '...' referenced in function" 오류 발생

우연히 접하게 된 라이브러리 하나가 재미있는 구조로 되어 있습니다. ^^ 기본적으로는 C 정적 라이브러리인데, Win32 DLL로도 컴파일이 가능하게 소스코드가 유연하게 구성되어 있는데요.

실제로 간단하게 하나 만들어 보겠습니다. 정적 라이브러리 용도로 Win32 프로젝트를 선택해 다음과 같이 함수 하나를 추가해 둡니다.

// ================= My.h =============== 
#pragma once

#if defined(_MSC_VER) && defined(_USRDLL)
# ifdef LIB_EXPORTS
#  define LIB_DLLEXTERN __declspec(dllexport)
# else 
#  define LIB_DLLEXTERN __declspec(dllimport)
# endif
#else
# define LIB_DLLEXTERN 
#endif

#ifdef __cplusplus
extern "C"
{
#endif

LIB_DLLEXTERN int MyFunc(int input);

#ifdef __cplusplus
};
#endif

// ================= My.c =============== 

#include "My.h"

LIB_DLLEXTERN int MyFunc(int input)
{
    return input + 5;
}

보시는 바와 같이, Win32 정적 프로젝트(이름: StaticLib)이므로 LIB_DLLEXTERN은 빈 매크로로 설정됩니다. 반면 만약 이 소스코드를 Win32 DLL 프로젝트에 추가해 LIB_DLLEXTERN 상수와 함께 컴파일하면 __declspec(dllexport) 영향으로 MyFunc 함수가 외부로 노출이 가능해집니다.

이 함수를 이용하는 Win32 Console EXE 프로젝트를 만들어 테스트 해보면 당연히 잘 컴파일이 됩니다. (정적으로 링크됩니다.)

#include "stdafx.h"

#include "../StaticLib/My.h"

int main()
{
    int result = MyFunc(5);
    printf("%d\n", result);
    return 0;
}




문제는, 위의 정적 라이브러리를 Win32 DLL 프로젝트에서 참조할 때 발생합니다.

#include "stdafx.h"
#include "Win32Lib.h"

#include "../StaticLib/My.h"

WIN32LIB_API int fnWin32Lib(void)
{
    int result = MyFunc(5);
    return result;
}

StaticLib 정적 라이브러리를 추가한 Win32 DLL 프로젝트를 빌드하면 다음과 같은 링크 오류가 발생합니다.

Creating library C:\staticlib\x64\Debug\Win32Lib.lib and object C:\staticlib\x64\Debug\Win32Lib.exp
Win32Lib.obj : error LNK2019: unresolved external symbol __imp_MyFunc referenced in function "int __cdecl fnWin32Lib(void)" (?fnWin32Lib@@YAHXZ)
C:\staticlib\x64\Debug\Win32Lib.dll : fatal error LNK1120: 1 unresolved externals

문제를 간단히 했으니 쉽게 유추할 수 있지만, 수많은 소스 코드 파일을 담은 3rd-party 라이브러리를 정적 링크할 때 저런 오류가 나오면 도대체 뭐가 잘못된 것인지 ^^; 헤맬 수밖에 없습니다.

원인은 간단합니다. My.h 헤더 파일을 include한 Win32 DLL 프로젝트는 _USRDLL 상수가 정의되어 있으므로 __declspec(dllimport) 구문이 정의되어 버립니다.

#pragma once

#if defined(_MSC_VER) && defined(_USRDLL)
# ifdef LIB_EXPORTS
#  define LIB_DLLEXTERN __declspec(dllexport)
# else 
#  define LIB_DLLEXTERN __declspec(dllimport)
# endif
#else
# define LIB_DLLEXTERN 
#endif

#ifdef __cplusplus
extern "C"
{
#endif

LIB_DLLEXTERN int MyFunc(int input);

#ifdef __cplusplus
};
#endif

따라서, DLL 프로젝트 측에서는 "__declspec(dllimport) int MyFunc(int input);" 시그니처를 가진 함수를 찾으려고 시도하지만 링커는 정적 라이브러리 파일(.lib)로부터 그 함수를 찾을 수 없으므로 LNK2019 오류를 내뱉는 것입니다.

문제의 원인을 좀 더 자세히 설명해보면!

"__declspec(dllimport)"로 인해 calling convention이 바뀌는 것은 아닙니다. 단지 dllimport가 지정된 경우 Visual C++ 컴파일러는 그것이 DLL로부터 export된 함수라고 가정하고 DLL 컴파일 시에 생성된 Import Library의 정보를 바탕으로 링크를 시도하는데 이때 해당 .lib 파일에 정의된 이름이 "__imp_[function]" 과 같은 식으로 정의됩니다. 하지만, 우리가 제공했던 .lib 파일은 DLL의 Import Lib 파일이 아닌 순수 정적 링크를 위한 .lib 파일이기 때문에 __imp_.... 식의 이름을 포함하고 있지 않아 LNK2019 오류로 이어진 것입니다.

어찌 보면, 정적 라이브러리 파일과 (DLL의) Import 라이브러리 파일의 확장자를 동일하게 해버려서 온 혼란의 하나겠지요!

해결 방법은, 추가하려는 정적 파일의 헤더 파일을 수정하거나... 아니면 다음과 같이 임시로 _USRDLL 상수를 해제해 버리면 됩니다.

#include "stdafx.h"
#include "Win32Lib.h"

#undef _USRDLL
#include "../StaticLib/My.h"

WIN32LIB_API int fnWin32Lib(void)
{
    int result = MyFunc(5);
    return result;
}

(첨부한 파일은 이 글의 재현 코드입니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 7/10/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12386정성태10/28/202011059Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20208816오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202010068오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202011012.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208623오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010306VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207771오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202010754.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010216.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011540디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208271오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209590Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(¥)' 기호로 나오는 경우 [1]
12374정성태10/14/202014197.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/20209473.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202011361.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
12371정성태10/13/202010087개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202010952Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
12369정성태10/12/202013761Windows: 176. Raymond Chen이 한글날에 밝히는 윈도우의 한글 자모 분리 현상 [3]
12368정성태10/12/20209827오류 유형: 668. VSIX 확장 빌드 - The "GetDeploymentPathFromVsixManifest" task failed unexpectedly.
12367정성태10/12/202022583오류 유형: 667. Ubuntu - Temporary failure resolving 'kr.archive.ubuntu.com' [2]
12366정성태10/12/202011621.NET Framework: 950. C# 9.0 - (4) 원시 크기 정수(Native ints) [1]파일 다운로드1
12365정성태10/12/202010552.NET Framework: 949. C# 9.0 - (3) 람다 메서드의 매개 변수 무시(Lambda discard parameters)파일 다운로드1
12364정성태10/11/202011758.NET Framework: 948. C# 9.0 - (2) localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)파일 다운로드1
12363정성태10/11/202012649.NET Framework: 947. C# 9.0 - (1) 대상으로 형식화된 new 식(Target-typed new expressions) [2]파일 다운로드1
12362정성태10/11/20209456VS.NET IDE: 151. Visual Studio 2019에 .NET 5 rc/preview 적용하는 방법
12361정성태10/11/202011054.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...