简体   繁体   中英

Substitute #defined value in macro

#define PACKAGE Package123
#define TEST_SUITE_NAME_PACKAGE(Suite,Package) Suite##_##Package
#define TEST_SUITE_NAME(Suite) TEST_SUITE_NAME_PACKAGE(Suite,PACKAGE)
#define SUITE_NAME TEST_SUITE_NAME(UtilitiesTest)

I want SUITE_NAME to evaluate to UtilitiesTest_Package123 , but after many variations, I still get UtilitiesTest_PACKAGE .

Note: SUITE_NAME is to be used as an identifier, not a string. I messed around with # and ## operators, but nothing seems to work.

The preprocessor sometimes requires a surprising number of indirections:

#define PACKAGE Package123
#define PASTE(x,y) x##_##y
#define TEST_SUITE_NAME_PACKAGE(Suite,Package) PASTE(Suite,Package)
#define TEST_SUITE_NAME(Suite) TEST_SUITE_NAME_PACKAGE(Suite,PACKAGE)
#define SUITE_NAME TEST_SUITE_NAME(UtilitiesTest)

This PASTE approach is a common preprocessor trick for just this sort of situation.

Just add another level of indirection

#define PACKAGE Package123
#define TEST_SUITE_NAME_PACKAGE(Suite,Package) Suite##_##Package
#define _TEST_SUITE_NAME_PACKAGE(Suite, PACKAGE) TEST_SUITE_NAME_PACKAGE(Suite,PACKAGE)
#define TEST_SUITE_NAME(Suite) _TEST_SUITE_NAME_PACKAGE(Suite,PACKAGE)
#define SUITE_NAME TEST_SUITE_NAME(UtilitiesTest)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM