【问题标题】:What does "conditional inclusion" mean in C programming?C 编程中的“条件包含”是什么意思?
【发布时间】:2013-12-28 16:04:36
【问题描述】:

在使用 C 编程时,我遇到了一个与 C 预处理器相关的概念“条件包含”。我试图通过参考一些网页来理解这个概念,但到目前为止,我还无法清楚地了解所指的是什么。

有人可以用一个例子来解释这个概念吗?

【问题讨论】:

标签: c c-preprocessor


【解决方案1】:

考虑使用#ifdef 预处理器指令(代表#if defined)的这段代码。

#ifdef FLAG1
#include "header1.h"
#endif

现在,当您编译时,如果定义了 FLAG1(由于体系结构或通过 -D 标志 - 如在 gcc -DFLAG1 source.c 中),则将包含 header1。同样的

#ifdef FLAG1
// any valid C code
#endif

例如,人们可能会使用它们来实现跨平台实现(精简示例)——__linux__ 仅在 Linux 上编译时定义,_WIN32 仅在 Windows 上编译时定义:

#ifdef __linux__ /* "If the __linux__ preprocessor variable is defined..." */

    #define select_os select_linux
    #define spawn_os spawn_linux

    typedef int pidtype;
    typedef int fdtype;

#elif defined (_WIN32) /* "Else, if the _WIN32 preprocessor variable is defined..." */

    #include <windows.h>

    #define select_os select_windows
    #define spawn_os spawn_windows

    #define strdup _strdup

    typedef HANDLE pidtype;
    typedef int fdtype;

#endif

(缩进只是为了清楚起见,人们通常会忽略它。)

对于这个 API(包括这个文件的代码)的用户来说,无论代码是在什么操作系统上编译的,函数看起来都是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多