A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© flywithde 中级黑马   /  2015-8-1 17:23  /  377 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

条件编译:
      发生在预处理阶段,在编译之前做的事情
      核心:根据条件编译指定的代码
      条件不同,编译的部分也不同,生成的目标文件(.o)大小也不一样
     (if-else)#if  #elif #else #endif     #ifdef:判断某个宏是否定义     #ifndef:判断某个宏是否没有定义
范例1:
    #include <stdio.h>
    #define SCORE 99
    int main(int argc, const char * argv[]) {
    #if SCORE < 60
        printf("E\n");
    #elif SCORE <= 69
        printf("D\n");
    #elif SCORE <= 79                             SCORE 是宏定义,注意每个条件编译都要和#endif配对使用
        printf("C\n");
    #elif SCORE <= 89
        printf("B\n");
    #else
        printf("A\n");
    #endif
    }

范例2:
    #include <stdio.h>
    #define DEBUG1 1
    #define DEBUG2 0
    int main(int argc, const char * argv[]) {
    int a = 0;
    //ifdef检测宏是否定义
    #ifdef DEBUG1   //DEBUG 系统已经定义了这个宏了
       a = 10;
    #else
       a = 10000;
    #endif  
    //ifndef 检测宏是否定义    ifndef 如果没有定义
    #ifndef DEBUG2
    a = 100;
    #else
    a = -1;
    #endif
    printf("%d\n",a);
    return 0;
    }

条件编译控制是否显示debug信息:
    #include <stdio.h>
    #define DEBUG1 1
    #if DEBUG1 == 1
    //显示调试信息format:形参  ...:代表可以有1个参数或多个参数    ##:表示可以有0个或者1个参数
         __VA_ARGS__:形参
    #define Log(format,...) printf(format,## __VA_ARGS__)
    #else
    //不显示调试信息
    #define Log(format,...)
    #endif
    void test(){
        int a  = 10,b=3;
        Log("test--->%d,%d\n",a,b);
    }
    int main(int argc, const char * argv[]) {
        //DEBUG1 == 1   显示调试信息
        //DEBUG1 == 0   不显示调试信息
        Log("xxxxxxxxxx-->\n");
        test();
        return 0;
    }

1 个回复

倒序浏览
收藏着以后忘了再拿出来看
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马