- 任何一个以#号开头的语句都是一个预处理命令,比如说#include<stdio.h>.
- 预处理器的另一个作用是检测当前的代码在哪个操作系统中进行,从而来产生平台相关的代码。
- 在Windows上,要伪造一个readline和add_history函数,而在Linux系统中就可以直接使用readline库提供给我们的函数。
- 为了实现系统的可移植性,我们需要把平台相关的代码包在#ifdef,#else和#endif预处理命令中。如果条件为真,包裹在#ifdef和#else之间的代码就会被执行,否则,#else和#endif之间的代码就会被执行。、
样例代码如下所示:
#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#include <string.h>
static char buffer[2048];
char *readline(char *prompt){
fputs(prompt, stdout);
fgets(buffer, 2048, stdin);
char *cpy = malloc(strlen(buffer)+1);
strcpy(cpy, buffer);
cpy[strlen(cpy) - 1] = '\0';
return cpy;
}
void add_history(char* unused) {}
#else
#include <readline/readline.h>
#include <readline/history.h>
#endif
int main(int argc, char** argv) {
puts("Lispy Version 0.1");
puts("Press Ctrl+c to Exit\n");
while (1) {
char* input = readline("lispy> ");
add_history(input);
printf("No you're a %s\n", input);
free(input);
}
return 0;
}