为什么要使用预处理器指令呢? [英] Why should one bother with preprocessor directives?

查看:98
本文介绍了为什么要使用预处理器指令呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这问题似乎相当简单,但是从工程的未来(非计算机科学)的背景下,我不确定什么的S '的片段均一些C ++代码。

This question may seem rather basic, but coming from an engineering (non computer-science) background, I was unsure about what the snippets of '#'s were in some C++ code.

一个快速搜索我带到简洁,充分解释的 CPLUSPLUS 教程预处理指令页。

A quick search led me to the concise, well-explained cplusplus tutorial page on preprocessor directives.

但是,为什么用预处理指令在所有概念烦恼呢?这难道不是可以编写等效代码,可以赋值常量,定义子程序/功能/宏和处理错误?

But why bother with the concept of preprocessor directives at all? Is it not possible to write equivalent code that can assign values to constants, define subroutines/function/macros and handle errors?

我想我最终想知道什么时候是很好的做法,使用这样的预处理指令,而当它不是。

I guess I ultimately want to know when it is good practice to use such preprocessor directives, and when it is not.

推荐答案

您使用预处理指令时,你需要外面做些什么的实际应用范围。例如,你会看到预处理做包括或基于该架构的可执行文件正在修建不包括代码。例如:

You use preprocessor directives when you need to do something outside of the scope of the actual application. For instance, you'll see preprocessing done to include or not include code based on the architecture the executable is being built for. For example:

#ifdef _WIN32 // _WIN32 is defined by Windows 32 compilers
#include <windows.h>
#else
#include <unistd.h>
#endif



预处理指令还用于防护件包括使类/功能等等没有定义一次以上。

Preprocessor directives are also used to guard includes so that classes/functions etc. are not defined more than once.

#ifndef MY_CLASS_6C1147A1_BE88_46d8_A713_64973C9A2DB7_H_
#define MY_CLASS_6C1147A1_BE88_46d8_A713_64973C9A2DB7_H_
    class MyClass {
    ....
    };
#endif

另一个用途是在代码和库中嵌入版本控制。

Another use is for embedding versioning inside of code and libraries.

在Makefile中有以下行:

In the Makefile you have something along the lines of:

-D MY_APP_VERSION=4.5.1

在代码中有

cout << "My application name version: " << MY_APP_VERSION << endl;

这篇关于为什么要使用预处理器指令呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆