宏不会在字符串文字内扩展.相反,您可以使用另一个宏将宏扩展为字符串文字,并使用字符串文字串联来创建所需的字符串:
#define STR2(x) STR(x)
#define STR(x) #x
const char *cmd = "mode con lines=" STR2(WINY) " cols=" STR2(WINX);
system(cmd);
Run Code Online (Sandbox Code Playgroud)
STR2将提供的参数(例如WINY)扩展为它定义的内容,然后将其传递给STR. STR只使用字符串化宏运算符,其结果是字符串文字.在将代码标记化并编译为目标代码之前,编译器将相邻的字符串文字连接成单个字符串.
如果宏比简单数字更复杂,那么您需要手动构造一个字符串.在C++中,最简单的方法是使用ostringstream(from <sstream>):
std::ostringstream oss;
oss << "mode con lines=" << WINY << " cols=" << WINX;
system(oss.str().c_str());
Run Code Online (Sandbox Code Playgroud)