Microsoft MVP성태의 닷넷 이야기
VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [링크 복사], [링크+제목 복사]
조회: 9924
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

C++의 연산자 동의어(operator synonyms), 대체 토큰

이상하군요, 분명히 전에 컴파일이 잘 되었는데,

#import "mscorlib.tlb" raw_interfaces_only              \
    high_property_prefixes("_get","_put","_putref")     \
    rename("ReportEvent", "InteropServices_ReportEvent") 

이번엔 위의 import 구문으로 생성한 헤더 파일의 "or" 식별자에서,

struct __declspec(uuid("03ec7d10-17a5-3585-9a2e-0596fcac3870"))
ITrackingHandler : IDispatch
{
    //
    // Raw methods provided by interface
    //

      virtual HRESULT __stdcall MarshaledObject (
        /*[in]*/ VARIANT obj,
        /*[in]*/ struct _ObjRef * or ) = 0;
      virtual HRESULT __stdcall UnmarshaledObject (
        /*[in]*/ VARIANT obj,
        /*[in]*/ struct _ObjRef * or ) = 0;
      virtual HRESULT __stdcall DisconnectedObject (
        /*[in]*/ VARIANT obj ) = 0;
};

이렇게 (경고와 함께) 오류가 발생합니다.

3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\netfx_host.cpp(13,1): warning C4279: 'or': identifier in type library 'mscorlib.tlb' is a keyword; use the 'rename' qualifier
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12974,35): error C2143: syntax error: missing ')' before '||'
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12974,35): error C2143: syntax error: missing ';' before '||'
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12974,35): error C2059: syntax error: '||'
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12974,38): error C2059: syntax error: ')'
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12974,43): error C2238: unexpected token(s) preceding ';'
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12977,35): error C2143: syntax error: missing ')' before '||'
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12977,35): error C2143: syntax error: missing ';' before '||'
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12977,35): error C2059: syntax error: '||'
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12977,38): error C2059: syntax error: ')'
3>E:\DotNetSamples\Cpp\netfx_host\netfx_host\x64\Debug\mscorlib.tlh(12977,43): error C2238: unexpected token(s) preceding ';'

C++에 or 연산자가 있는지 처음 알았군요. ^^; 그래서 검색해 보니,

Keywords (C++)
; https://learn.microsoft.com/en-us/cpp/cpp/keywords-cpp

"Standard C++ keywords" 영역에 "The extended operator synonyms are keywords when /permissive- or /Za (Disable language extensions) is specified. They aren't keywords when Microsoft extensions are enabled."라는 주석으로 "or"이 등록되어 있습니다.

좀 더 자세한 정보는 해당 예약어의 문서에 있습니다.

Logical OR operator: ||
; https://learn.microsoft.com/en-us/cpp/cpp/logical-or-operator-pipe-pipe

C++ specifies or as an alternative spelling for ||. In C, the alternative spelling is provided as a macro in the <iso646.h> header. In C++, the alternative spelling is a keyword; use of <iso646.h> or the C++ equivalent <ciso646> is deprecated. In Microsoft C++, the /permissive- or /Za compiler option is required to enable the alternative spelling.


"alternative spelling"이라고도 표현하는데 아마도 적절한 한글 번역으로는 "대체 토큰"으로 하는 듯합니다.

C 대체 토큰
; https://ko.wikipedia.org/wiki/C_%EB%8C%80%EC%B2%B4_%ED%86%A0%ED%81%B0




정리해 보면, 일단 표준 입장에서는 C의 경우 iso646.h 헤더를 이용해 매크로로 정의되어 있지만 C++의 경우에는 분명하게 대체 토큰은 예약어라는 것입니다.

그럼 Visual C++의 경우에는 어떨까요? 일단 "Microsoft extensions"을 따르는 (기본) 모드에서는 예약어로 취급받지 않습니다. 그래서 그런 경우에는 iso646.h (또는, ciso646) 파일을 include시켜,

// iso646.h standard header

// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#pragma once
#ifndef _ISO646
#define _ISO646
#include <yvals_core.h>
#if _STL_COMPILER_PREPROCESSOR

#if !defined(__cplusplus) || defined(_MSC_EXTENSIONS)
#define and &&
#define and_eq &=
#define bitand &
#define bitor |
#define compl ~
#define not !
#define not_eq !=
#define or ||
#define or_eq |=
#define xor ^
#define xor_eq ^=
#endif // !defined(__cplusplus) || defined(_MSC_EXTENSIONS)
#endif // _STL_COMPILER_PREPROCESSOR
#endif // _ISO646

매크로 정의로 취급할 수 있습니다. 하지만 현재 C++ 언어상 예약어로 취급하기 때문에 Visual C++에서도 위와 같이 헤더 파일로 처리하는 것은 deprecated라고 하며, 대신 "Microsoft extensions" 모드에서도 예약어로 취급할 수 있도록 "Configuration Properties / C/C++ / Language" 범주의 "Conformance mode"로,

/permissive- (Standards conformance)
; https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance

포함시켰으므로, 이 값을 "Yes (/permissive-)"로 설정하면 예약어로 받아들이게 됩니다.

혹은, 아예 "Microsoft extensions" 모드를 끄면 되는데 그 옵션이 바로 "Disable Language Extensions"로 "Yes (/Za)" 값을 설정하는 것입니다.




그런데, 더욱 재미있는 글이 있군요. ^^

C++ - 대체 토큰 사용하기
; https://jacking75.github.io/cpp_alternative_tokens/

그러니까, and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq 외에도 6개가 더 있는 것입니다.

<% == {
%> == }
<: == [
:> == ]
%: == #
%:%: == ##

설마... 하는 마음으로 Visual C++로 코딩을 했더니... 정말 컴파일이 됩니다. ^^; (대신 에디터의 자동 들여 쓰기가 인식을 못해 살짝 불편합니다.)

#include <iostream>
#include <functional>

using namespace std;

%:define USE_DEBUG

int main()
{
    <%
        bool b1 = true;
        bool b2 = true;

        bool result1 = b1 and b2;
        bool result2 = b1 or b2;

        printf("%d, %d\n", result1, result2);

        function<int(int, int)> f = <::>(int a, int b) { return a + b; };
    %>

    <%
        bool b1 = true;
        bool b2 = true;

        bool result1 = b1 and b2;
        bool result2 = b1 or b2;

        printf("%d, %d\n", result1, result2);
    %>
}

저런 의미에서 봤을 때, "연산자 동의어"는 대체 토큰의 일부라고 볼 수 있을 것입니다.




그런데... 왜 이런 걸 굳이 만들었을까... 궁금했는데 위키 문서에 다음과 같은 글이 있군요. ^^

대체 토큰을 통하여 프로그래머에게 하여금 일부 국제 표준과 비쿼티 키보드에선 입력하기 어려울 수 있는 C언어의 비트 및 논리 연산자를 쓸 수 있도록 해준다. 많은 지역적 차이로 구성된 7비트 문자가 담긴 ISO/IEC 646 표준을 참조하는 이 헤더 파일의 이름 중 일부는 C 연산자에 의해 쓰이는 문장 부호를 대체하는 악센트 문자가 있다.





대체 토큰에 정신이 팔려, 원래 오류가 난 코드의 해결책을 이제서야 쓰는군요. ^^ 당연히 /permissive- 옵션을 해제하거나 하는 등의 방법을 써도 되지만, import 구문에서 제공하는 rename을 다시 한번 적용하면 됩니다. 이렇게!

#import "mscorlib.tlb" raw_interfaces_only              \
    high_property_prefixes("_get","_put","_putref")     \
    rename("ReportEvent", "InteropServices_ReportEvent") \
    rename("or", "_or_")




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/14/2022]

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

비밀번호

댓글 작성자
 



2023-01-10 11시30분
On leading underscores and names reserved by the C and C++ languages
; https://devblogs.microsoft.com/oldnewthing/20230109-00/?p=107685
정성태

1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13347정성태5/10/20233931.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233778오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235057.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236327.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234200디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234123.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20233909닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20233930오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234617닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234103닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234626Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234386.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234514.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234166Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233626Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233721Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233744오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233414Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233622Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233259VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233685VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235054.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234403스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234238.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234137개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20234936VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...