Microsoft MVP성태의 닷넷 이야기
VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [링크 복사], [링크+제목 복사],
조회: 10931
글쓴 사람
정성태 (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)
12208정성태4/12/20209970Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/20208954스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202011252오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/20208642스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/20208458스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202010484오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202013111개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202010911오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202011332VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/20209182오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202011930오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202011076VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20208998오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202010714.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202013032오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/20209722개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202012173개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012535개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208647오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013490개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015799Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208469오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209561오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202010239오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011646오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202010012오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...