C语言进阶课程学习记录-第22课 - 条件编译使用分析
- 条件编译基本概念
- 条件编译实验
- 条件编译本质
- 实验-ifdef
- include本质
- 实验-间接包含同一个头文件
- 解决重复包含的方法-ifndef
- 实验-条件编译的应用
- 小结
本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程,图片全部来源于课程PPT,仅用于个人学习记录
条件编译基本概念
条件编译实验
#include <stdio.h>#define C 1int main()
{const char* s;#if( C == 1 )s = "This is first printf...\n";#elses = "This is second printf...\n";#endifprintf("%s", s);return 0;
}/*output:
This is first printf...*/
条件编译本质
实验-ifdef
#include <stdio.h>int main()
{const char* s;#ifdef Cs = "This is first printf...\n";#elses = "This is second printf...\n";#endifprintf("%s", s);return 0;
}/*output:
This is second printf...*/
include本质
实验-间接包含同一个头文件
// global.h
//#ifndef _GLOBAL_H_
//#define _GLOBAL_H_
int global = 10;//D:\Users\cy\Test\global.h|4|error: redefinition of 'global'|//#endif// test.h//#ifndef _TEST_H_
//#define _TEST_H_
#include "global.h"
const char* NAME = "test.h";
char* hello_world(){ return "Hello world!\n";}//#endif#include <stdio.h>
#include "test.h"
#include "global.h"int main()
{const char* s = hello_world();int g = global;printf("%s\n", NAME);printf("%d\n", g);return 0;
}//error D:\Users\cy\Test\global.h|4|error: redefinition of 'global'|
// global.h
#ifndef _GLOBAL_H_
#define _GLOBAL_H_
int global = 10;
#endif// test.h#ifndef _TEST_H_
#define _TEST_H_
#include "global.h"
const char* NAME = "test.h";
char* hello_world(){ return "Hello world!\n";}#endif#include <stdio.h>
#include "test.h"
#include "global.h"int main()
{const char* s = hello_world();int g = global;printf("%s\n", NAME);printf("%d\n", g);return 0;
}/*output:
test.h
10*/
解决重复包含的方法-ifndef
实验-条件编译的应用
“product.h”
#define DEBUG 1
#define HIGH 1
#include <stdio.h>
#include "product.h"#if DEBUG#define LOG(s) printf("[%s:%d] %s\n", __FILE__, __LINE__, s)
#else#define LOG(s) NULL
#endif#if HIGH
void f()
{printf("This is the high level product!\n");
}
#else
void f()
{
}
#endifint main()
{LOG("Enter main() ...");f();printf("1. Query Information.\n");printf("2. Record Information.\n");printf("3. Delete Information.\n");#if HIGHprintf("4. High Level Query.\n");printf("5. Mannul Service.\n");printf("6. Exit.\n");#elseprintf("4. Exit.\n");#endifLOG("Exit main() ...");return 0;
}/*output:
[D:\Users\cy\Test\test1.c:143] Enter main() ...
This is the high level product!
1. Query Information.
2. Record Information.
3. Delete Information.
4. High Level Query.
5. Mannul Service.
6. Exit.
[D:\Users\cy\Test\test1.c:159] Exit main() ...*/
小结
通过编译器命令行能够定义预处理器使用的宏
条件编译可以避免重复包含头同一个头文件
条件编译是在工程开发中可以区别不同产品线的代码条件编译可以定义产品的发布版和调试版