Microsoft MVP성태의 닷넷 이야기
VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [링크 복사], [링크+제목 복사],
조회: 20858
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

x64 빌드에서 extern "C"가 아닌 경우 __cdecl name mangling 적용

처음 알았군요. ^^; 간단하게 DLL 프로젝트를 만들어, 다음의 헤더 파일과 CPP로,

// 헤더 파일

           __declspec(dllexport) int __stdcall fnDll1(void);
extern "C" __declspec(dllexport) int __stdcall fnDll2(void);

#include "pch.h"
#include "Dll1.h"

__declspec(dllexport) int __stdcall fnDll1(void)
{
    return 0;
}

__declspec(dllexport) int __stdcall fnDll2(void)
{
    return 0;
}

빌드한 결과물에 대해 export 결과는 다음과 같습니다.

[x86]
?fnDll1@@YGHXZ
_fnDll2@0

[x64]
?fnDll1@@YAHXZ
fnDll2

extern "C"가 붙지 않은 fnDll1에 대해 각각 undname으로 풀어 보면,

// Visual C++ name mangling
// ; https://en.wikiversity.org/w/index.php?title=Visual_C%2B%2B_name_mangling&oldid=2371121

[x86]
?fnDll1@@YGHXZ ==> int __stdcall fnDll1(void)

[x64]
?fnDll1@@YAHXZ ==> "int __cdecl fnDll1(void)"

x64의 경우, __stdcall을 명시한 것에 상관없이 __cdecl로 나옵니다. (업데이트 2020-11-20) x64의 경우, extern "C"가 없는 경우 name mangling이 무조건 __cdecl 유형으로 나옵니다. (버그인지, 원래 이런 것인지 혹시 아시는 분은 덧글 부탁드립니다. ^^)

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/20/2024]

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

비밀번호

댓글 작성자
 



2020-11-20 08시31분
[수] 안녕하세요, 언제나 좋은 글 써주셔서 많이 도움 받고 있습니다.

제가 cpp쪽은 문외한이라 잘 이해했는지는 모르겠는데,
https://learn.microsoft.com/ko-kr/cpp/cpp/stdcall?view=msvc-160
이 글을 보니까
Functions declared using the __stdcall modifier return values the same way as functions declared using __cdecl.
On ARM and x64 processors, __stdcall is accepted and ignored by the compiler; on ARM and x64 architectures, by convention, arguments are passed in registers when possible, and subsequent arguments are passed on the stack.
이렇게 쓰여있는데 혹시 이것과 관련된 내용일까요?
__cdecl 항목에도 동일한 내용이 기록되어 있습니다.
[guest]
2020-11-20 09시39분
의견 주셔서 감사합니다. ^^ 제가 또 그 사실을 깜빡하고 있었군요. 예전에도 쓴 글이었는데,

C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (3) - x64 환경의 __fastcall과 Name mangling
; https://www.sysnet.pe.kr/2/0/11139

x64에서는 원래 (__fastcall 호출 규약만 있어서) 모든 호출 규약을 무시하는데, ... 제가 순간적으로 __cdecl이 적용되는 거에 혼란이 왔습니다. ^^;

그렇긴 한데, 어쨌든 그 문서에서도 x64의 경우 extern "C"가 없을 때 __cdecl이 적용된다는 것에 대한 내용은 아닙니다. 말씀하신데로 __cdecl 문서에서도 x64 빌드에서 그 옵션이 쓰여질 수는 있지만 무시한다는 내용입니다. 따라서 문서상으로 보면 extern "C"의 유무에 상관없이 __fastcall로 나와야 하는데.... 이상하게 __cdecl로 나온 것입니다. 이렇게 알고 나서 보니, 위의 링크에서 예시한 함수들 중에 아래의 2개가,

__declspec(dllexport) int __cdecl CDECL_Func(int value);
==> ?CDECL_Func@@YAHH@Z
==> int __cdecl CDECL_Func(int)

__declspec(dllexport) int __stdcall STD_Func(int value);
==> ?STD_Func@@YAHH@Z
==> int __cdecl STD_Func(int)

라고 풀이되는데, 그때도 역시 extern "C"가 없는 경우 __cdecl로 통일되어 나왔습니다. 그래도 관련 문서 중에 보니까,

https://learn.microsoft.com/en-us/cpp/build/reference/gd-gr-gv-gz-calling-convention

위의 내용에 "__cdecl Specifics"를 보면 ARM과 x64 환경에서는 "__fastcall Specifis"와 동일하게 인자 전달을 하는 것으로 설명하고 있습니다. 아마도 그렇다면 extern "C"가 없는 경우 비록 이름 자체에는 __cdecl을 포함한 name mangling이 되긴 했지만 내부 호출 규약은 __fastcall로 통일된 것에는 변함이 없는 듯합니다.
정성태
2020-11-20 10시16분
테스트 해보니까, 호출 규약 자체가 변한 것은 아니고 x64에서 extern "C"가 붙지 않은 경우 그냥 name mangling만 __cdecl로 하고 있습니다. 덕분에 혼란스러운 것을 정리할 수 있었습니다. ^^
정성태
2020-11-20 03시50분
[수] 와 빠른 피드백 멋지네요!
뭔가 약간 팬심 비슷한게 뭉게뭉게 솟아난 느낌입니다.
덧붙여주신 내용 덕에 한개 더 배워 갑니다. 감사합니다!
[guest]

... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12421정성태11/19/202016017.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/202016545오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/202016862VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202019020오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/202017434오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202018600오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202018175.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202020858VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202019544.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202021610.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202018169오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202018984디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202020652.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202035687도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202020756.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202021714.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202020200.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202020780.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018904.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202021161.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202020441VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202016478오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202019563.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202019708오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202019813.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202016157VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...