1:为什么要条件编译
—般情况下,C语言源程序中的每一行代码.都要参加编译。但有时候出于对程序代码优化的考虑.希望只对其中一部分内容进行编译.此时就需要在程序中加上条件,让编译器只对满足条件的代码进行编译,将不满足条件的代码舍弃,这就是条件编译(conditional compile) ----------百度百科
2:条件边缘的几种形式
指令 用途
# 空指令,无任何效果
#include 包含一个源代码文件
#define 定义宏
#undef 取消已定义的宏
#if 如果给定条件为真,则编译下面代码
#ifdef 如果宏已经定义,则编译下面代码
#ifndef 如果宏没有定义,则编译下面代码
#elif 如果前面的#if给定条件不为真,当前条件为真,则编译下面代码,其实就是else if的简写
#endif 结束一个#if……#else条件编译块
#error 停止编译并显示错误信息
#if 表达式
语句序列①
[#else
语句序列②]
#endif
#ifdef 标识符
语句序列①
[#else
语句序列②]
#endif
条件编译在各处源码中到处存在,理解如何使用条件编译对我们理解源码尤其重要 下面是liunx源码中socket头文件
#ifndef _SYS_SOCKET_H
#define _SYS_SOCKET_H 1
#include <features.h>
__BEGIN_DECLS
#include <bits/types/struct_iovec.h>
#define __need_size_t
#include <stddef.h>
/* This operating system-specific header file defines the SOCK_*, PF_*,
AF_*, MSG_*, SOL_*, and SO_* constants, and the `struct sockaddr',
`struct msghdr', and `struct linger' types. */
#include <bits/socket.h>
#ifdef __USE_MISC
# include <bits/types/struct_osockaddr.h>
#endif
/* The following constants should be used for the second parameter of
`shutdown'. */
enum
{
SHUT_RD = 0, /* No more receptions. */
#define SHUT_RD SHUT_RD
SHUT_WR, /* No more transmissions. */
#define SHUT_WR SHUT_WR
SHUT_RDWR /* No more receptions or transmissions. */
#define SHUT_RDWR SHUT_RDWR
};
/* This is the type we use for generic socket address arguments.
With GCC 2.7 and later, the funky union causes redeclarations or
uses with any of the listed types to be allowed without complaint.
G++ 2.7 does not support transparent unions so there we want the
old-style declaration, too. */
#if defined __cplusplus || !__GNUC_PREREQ (2, 7) || !defined __USE_GNU
# define __SOCKADDR_ARG struct sockaddr *__restrict
# define __CONST_SOCKADDR_ARG const struct sockaddr *
#else
#ifndef _SYS_SOCKET_H //如果没定义sys/socket.h
#define _SYS_SOCKET_H //定义头文件
防止头文件包含
#if defined __cplusplus || !__GNUC_PREREQ (2, 7) || !defined __USE_GNU
# define __SOCKADDR_ARG struct sockaddr *__restrict
# define __CONST_SOCKADDR_ARG const struct sockaddr *
//如果满足了defined __cplusplus || !__GNUC_PREREQ (2, 7) || !defined __USE_GNU
就定义
# define __SOCKADDR_ARG struct sockaddr *__restrict
# define __CONST_SOCKADDR_ARG const struct sockaddr *
总结:总的来说就算if ifdef ifndef define 混着用, 自己以后写项目的时候也要注意这样写 减小内存开销,加快编译速度