面试题答案
一键面试#include <stdio.h>
#ifdef _WIN32
#include <windows.h>
#endif
void show_message(const char* message) {
#ifdef _WIN32
MessageBox(NULL, message, "Message", MB_OK);
#else
printf("%s\n", message);
#endif
}
在上述代码中,通过条件编译指令 #ifdef
来区分不同平台。在Windows平台下,编译器会识别 _WIN32
这个预定义宏,从而编译 MessageBox
相关代码;在Linux平台下,由于没有定义 _WIN32
,会编译 printf
相关代码。如果在自定义的构建环境中,也可以手动定义宏来区分平台,例如使用 gcc -D _WIN32
来模拟Windows平台编译,不添加 -D _WIN32
则默认按Linux平台逻辑编译。