Microsoft MVP성태의 닷넷 이야기
VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [링크 복사], [링크+제목 복사],
조회: 10851
글쓴 사람
정성태 (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]

... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12431정성태11/27/20209170.NET Framework: 976. UnmanagedCallersOnly + C# 9.0 함수 포인터 사용 시 x86 빌드에서 오동작하는 문제파일 다운로드1
12430정성태11/27/20209912오류 유형: 686. Ubuntu - E: The repository 'cdrom://...' does not have a Release file.
12429정성태11/25/20209993디버깅 기술: 175. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우
12428정성태11/25/20208925VS.NET IDE: 154. Visual Studio - .NET Core App 실행 시 dotnet.exe 실행 화면만 나오는 문제
12427정성태11/24/202010067.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/20208656오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/20209705VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202010135VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202011076.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/20208869.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/20208599.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/20207797오류 유형: 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/20209000VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202011089오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/20208471오류 유형: 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/20209751오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/20209781.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202010851VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202010559.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202012825.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/20209788오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/20209737디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202011150.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202022447도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202011415.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202012984.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...