• 条件编译使用


    基本概念

    • 条件编译的行为类似于C语言中的if...else...
    • 条件编译是预编译指示命令,用于控制是否编译某段代码
    #include<stdio.h>
    #define C 1
    int main()
    {
    	# if(C == 1)
    	printf("This is first print...
    ");
    	# else
    	printf("This is second printf...
    ");
    	#endif
    
    	return 0;
    }
    

    条件编译的本质

    • 预编译器根据条件编译指令有选择的删除代码
    • 编译器不知道代码分支的存在
    • if...else...语句在运行期进行分支判断
    • 条件编译指令在预编译期进行分支判断
    • 可以通过命令行定义宏
      • gcc -Dmacro=value file.c
      • gcc -Dmacro file.c

    例子1:通过命令行定义宏

    #include<stdio.h>
    // #define C 1
    int main()
    {
    	# if(C == 1)
    	printf("This is first print...
    ");
    	# else
    	printf("This is second printf...
    ");
    	#endif
    
    	return 0;
    }
    

    编译命令:gcc -DC=1 test.c

    #include的本质

    • #include的本质是将已经存在的文件内容嵌入到当前文件中
    • #include的间接包含同样会产生嵌入文件内容的操作

    问题:间接包含同一个头文件是否会产生编译错误?
    条件编译可以解决头文件重复包含的编译错误

    条件编译的意义

    • 条件编译使得我们可以按照不同的条件编译不同的代码段,因而可以产生不同的目标代码
    • #if...#else...#endif被预编译器处理,而if..else..语句被编译器处理,必然被编译进目标代码
    • 实际工程中条件编译主要用于以下两种情况:
      • 不同的产品线共用一份代码
      • 区分编译产品的调试版和发布版

    例子2:产品线区分及调试代码应用
    product.h

    #define DEBUG 1
    #define HIGH 1
    

    main.c

    #include <stdio.h>  
    #include "product.h"  
      
    #if DEBUG  
        #define LOG(s) printf("[%s:%d] %s
    ", __FILE__, __LINE__, s)  
    #else  
        #define LOG(s) NULL  
    #endif  
      
    #if HIGH  
    void f()  
    {  
        printf("This is the high level product!
    ");  
    }  
    #else  
    void f()  
    {  
    }  
    #endif  
      
    int main()  
    {  
        LOG("Enter main() ...");  
          
        f();  
          
        printf("1. Query Information.
    ");  
        printf("2. Record Information.
    ");  
        printf("3. Delete Information.
    ");  
          
        #if HIGH  
        printf("4. High Level Query.
    ");  
        printf("5. Mannul Service.
    ");  
        printf("6. Exit.
    ");  
        #else  
        printf("4. Exit.
    ");  
        #endif  
          
        LOG("Exit main() ...");  
          
        return 0;  
    }  
    

    小结

    • 通过编译器命令行能够定义预处理器使用的宏
    • 条件编译可以避免重复包含同一个头文件
    • 条件编译是在工程开发中可以区别不同产品线的代码
    • 条件编译可以定义产品的发布版和调试版
  • 相关阅读:
    使用webdriver出现的问题:[18796:1808:0730/131103.313:ERROR:install_util.cc(600)] Failed to read HKLMSOFTWAREPoliciesGoogleChromeMachineLevelUserCloudPolicyEnrollmentToken: 系统找不到指定的文件。 (0x2) DevTools lis
    1130 host is not allowed to connect to
    Mysql误删了root用户怎么办
    猫眼电影爬取
    sklearn之聚类的均值漂移算法
    sklearn之聚类K均值算法
    基于支持向量机的分类模型和回归模型案例
    超参数处理之网格搜素
    redis基础之有序集合应用
    Sklearn之支持向量机分类
  • 原文地址:https://www.cnblogs.com/yanyun888/p/9213117.html
Copyright © 2020-2023  润新知