_WIN32,Linux 有專有的宏__linux__,以現有的知識,我們很容易就想到了 if else,請看下面的代碼:
#include <stdio.h>
int main(){
if(_WIN32){
system("color 0c");
printf("http://c.biancheng.net\n");
}else if(__linux__){
printf("\033[22;31mhttp://c.biancheng.net\n\033[22;30m");
}else{
printf("http://c.biancheng.net\n");
}
return 0;
}
但這段代碼是錯誤的,在 Windows 下提示 __linux__ 是未定義的標識符,在 Linux 下提示 _Win32 是未定義的標識符。對上面的代碼進行改進:
#include <stdio.h>
int main(){
#if _WIN32
system("color 0c");
printf("http://c.biancheng.net\n");
#elif __linux__
printf("\033[22;31mhttp://c.biancheng.net\n\033[22;30m");
#else
printf("http://c.biancheng.net\n");
#endif
return 0;
}
#if、#elif、#else 和 #endif 都是預處理命令,整段代碼的意思是:如果宏 _WIN32 的值為真,就保留第 4、5 行代碼,刪除第 7、9 行代碼;如果宏 __linux__ 的值為真,就保留第 7 行代碼;如果所有的宏都為假,就保留第 9 行代碼。
#if 整型常量表達式1
程序段1
#elif 整型常量表達式2
程序段2
#elif 整型常量表達式3
程序段3
#else
程序段4
#endif
#include <stdio.h>
int main(){
#if _WIN32
printf("This is Windows!\n");
#else
printf("Unknown platform!\n");
#endif
#if __linux__
printf("This is Linux!\n");
#endif
return 0;
}
#ifdef 宏名
程序段1
#else
程序段2
#endif
#ifdef 宏名
程序段
#endif
#include <stdio.h>
#include <stdlib.h>
int main(){
#ifdef _DEBUG
printf("正在使用 Debug 模式編譯程序...\n");
#else
printf("正在使用 Release 模式編譯程序...\n");
#endif
system("pause");
return 0;
}
當以 Debug 模式編譯程序時,宏 _DEBUG 會被定義,預處器會保留第 5 行代碼,刪除第 7 行代碼。反之會刪除第 5 行,保留第 7 行。
#ifndef 宏名
程序段1
#else
程序段2
#endif
#include <stdio.h>
#define NUM 10
int main(){
#if NUM == 10 || NUM == 20
printf("NUM: %d\n", NUM);
#else
printf("NUM Error\n");
#endif
return 0;
}
運行結果:
#include <stdio.h>
#define NUM1 10
#define NUM2 20
int main(){
#if (defined NUM1 && defined NUM2)
//代碼A
printf("NUM1: %d, NUM2: %d\n", NUM1, NUM2);
#else
//代碼B
printf("Error\n");
#endif
return 0;
}
運行結果: