배경 매크로를 생성하는 난 내가 매크로 같은 기능을 작성하고자하는 거의 동일한 매크로 이름을 가진 두 개의 별도 제품을 가지고 프로젝트를
매크로 값을 빠르게 검색 할 수 있습니다. 필자는 getTranslation
매크로 함수를 작성하여 "function"에 제공되는 리터럴 텍스트를 가져 왔습니다.이 텍스트는 문자열과 문자열 접두어로 처리해야합니다 (아래 참조).매크로 기능은 접두사 (피 문자열 화 (stringification))
질문
내가 대신 전 처리기 매크로로 그 결과를 (중간에 밑줄과) 함께을 연결, 매크로에 공급되는 인수를 고려하고, 치료의이 작업을 수행 할 수있는 방법 끈?
코드 목록
/*******************************************************************************
* coconut.h
******************************************************************************/
#define COCONUT (PRODUCT_COCONUT)
#define COCONUT_FX_REGISTER (100)
#define COCONUT_BASE_REGISTER (101)
/*******************************************************************************
* pineapple.h
******************************************************************************/
#define PINEAPPLE (PRODUCT_PINEAPPLE)
#define PINEAPPLE_FX_REGISTER (200)
#define PINEAPPLE_BASE_REGISTER (201)
/*******************************************************************************
* test.c.
******************************************************************************/
#include <stdio.h>
#include "translation.h"
#include "coconut.h"
int main(void) {
int i = getTranslation(FX_REGISTER, COCONUT);
printf("Translation:%d.\n", i);
return 0;
}
/*******************************************************************************
* translation.h
******************************************************************************/
#define FX_REGISTER (0)
#define BASE_REGISTER (1)
#define getTranslationInternal(x, y) #y "_" #x
#define getTranslation(x, y) getTranslationInternal(x, y)
enum Products {
PRODUCT_COCONUT = 0,
PRODUCT_PINEAPPLE,
PRODUCT_MAX,
PRODUCT_INVALID = (-1)
};
컴파일러 경고
test.c: In function ‘main’:
test.c:10:45: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
int i = getTranslation(FX_REGISTER, COCONUT);
^
translation.h:7:39: note: in definition of macro ‘getTranslationInternal’
#define getTranslationInternal(x, y) #y "_" #x
^
test.c:10:10: note: in expansion of macro ‘getTranslation’
int i = getTranslation(FX_REGISTER, COCONUT);
샘플 실행
Translation:4195812.
'#define getTranslationInternal (x, y) y ## _ ## x'의 문제점은 무엇입니까? – rici
@rici 몇 가지 오류 : '오류 : 붙여 넣기' "(PRODUCT_COCONUT)"및 "_"은 유효한 전처리 토큰을 제공하지 않습니다. '및 "붙여 넣기"_ "및"("유효한 전처리 토큰을 제공하지 않습니다. – DevNull
'(y ## _ ## x') 매크로를 사용하여'COCONUT_FX_REGISTER'를 얻으려고하고'COCONUT_FX_REGISTER'가' (100)', 왜 당신은'4195812'를 기대하고 있습니까? – PSkocik