рефераты конспекты курсовые дипломные лекции шпоры

Реферат Курсовая Конспект

Conditional Compilation

Conditional Compilation - раздел Философия, Data Structures and Algorithms in C++ Beyond Macro Substitution, A More Important Reason To Use #define Is To Suppo...

Beyond macro substitution, a more important reason to use #define is to support conditional compilation. Using #define, and some other preprocessor directives, we can instruct the compiler to compile only certain sections of our source code. This is useful in many circumstances, one of which is for inserting debugging code that can be easily enabled and disabled. Below we see an example that uses the #define, #if, and #endif directives.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: #include <iostream>#include <cstdlib> #define DEBUG using namespace std; int main(int argc, char* argv[]) { #if defined(DEBUG) cerr << "Debugging enabled" << endl;#endif int arr[10]; for (int i = 0; i < 10; i++) { arr[i] = i; #if defined(DEBUG) cerr << "i = " << i << endl; cerr << "arr[i] = " << arr[i] << endl;#endif } return EXIT_SUCCESS;}
Listing 4 Conditional compilation

The #if preprocessor directive works similar to a regular if-statement, except that it has to paired with an #endif directive. These two directives partition a section of source code that can be conditionally compiled. The preprocessor evaluates the value that follows the #if. If this value evaluates to true (non-zero), the preprocessor includes the source code block. If it evaluates to false, the preprocessor omits the source code block. In the above listing, defined(DEBUG) follows the #if directives. The preprocessor evaluates this to true only if we have defined an identifier named DEBUG. Since we have defined DEBUG in line 4, the source code blocks partitioned by the #if and #endif pairs will be compiled. The power of this technique is apparent when we realize all we have to do to disable the debugging code found throughout the program is remove the definition of DEBUG from the program. This causes the preprocessor to omit the debugging code.

Conditional compilation is also often used to prevent multiple definitions of classes and functions that are contained in header files. Including a header file more than once in a program can cause class and function redefinition problems. We can prevent this with a technique that uses conditional compilation. Below we see in line 1 the #if directive used to check if the program has defined the identifier _PERSON_H_. If it has not been defined, then the rest of the source code in the example is processed. If it has been defined, the source code is skipped by the preprocessor. The key to this technique is in line 2, where the program defines _PERSON_H_. If we had a program that had several source code files that all included the following header file, the conditional compilation would ensure that the content of the file is included only once. The first time the file was included would result in the definition of _PERSON_H_, which would then prevent the inclusion of the contents of the file a second time.

1: 2: 3: 4: 5: 6: 7: 8: 9: #if !defined(_PERSON_H_)#define _PERSON_H_ class Person { // Class declaration...}; #endif
Listing 5 Preventing multiple declarations

Shortcut conditional compilation constructs exist that we can use in place of the defined operator. The directive #ifdef identifier is equivalent to #if defined(identifier). Likewise, the directive #ifndef identifier is equivalent to #if !defined(identifier).

– Конец работы –

Эта тема принадлежит разделу:

Data Structures and Algorithms in C++

Compiling and Running a C Program C Background History C is a modern object oriented programming language that supports... Table Different problems with similar solutions Each of the problems... Vectors...

Если Вам нужно дополнительный материал на эту тему, или Вы не нашли то, что искали, рекомендуем воспользоваться поиском по нашей базе работ: Conditional Compilation

Что будем делать с полученным материалом:

Если этот материал оказался полезным ля Вас, Вы можете сохранить его на свою страничку в социальных сетях:

Все темы данного раздела:

Assessments
· Multiple-Choice Quiz 1 Recommended Exercise 1 1.3.1 Data Types Fundamental Data Types As in most other programming languages including Java, C+

Strings
In C++, the string data type provides the necessary abstraction to allow C++ programmers to work with character strings. The Java counterpart is actually two separate classes. Unlike its J

Strings
В C ++, тип данных string обеспечивает необходимую абстракцию, чтобы позволить программистам работать со строками символов. В Java фактически образуют два отдельных класса. В отличие от Ja

Creating New Data Type Names
It is possible in C++ for a programmer to create additional names for existing data types. Creating another name uses the keyword typedef. The syntax to create a new name is as follows. typed

Создание новых имен типов данных.
В C++ есть возможность создать дополнительно к существующим собственные типы данных с новым именем. Для этого необходимо использовать ключевое слово typedef. Синтаксис, чтобы создать новое имя след

Constructors
Constructors are the methods of a class that define what actions to take when creating an object. A C++ class can have multiple constructors. This allows variation in object instantiation since dif

The Destructor
A destructor is a special member function of a C++ class called when an object's lifetime ends. Like a copy constructor, only one destructor can exist for a class. Since they execute when an object

Declaration vs. Definition
In this discussion on the specification of classes in C++, the term "definition" has been used regarding functions. When we "define" a function, we dictate the function's behavi

Basic Syntax
Класс - основная единица абстракции в C++. Давайте сначала рассмотрим простой класс, определенный в Java, и затем соответствующую версию в C++. ………………………………………………………………………………… Сле

Constructors
Конструктор создает и инициализирует новый экземпляр класса. В C++ класс может иметь несколько конструкторов. Это позволяет вносить изменение в экземпляры класса включая типы параметров и значения,

Declaration vs. Definition
В обсуждении о спецификации классов, термин "definition" ("определение") был использован относительно функции. Когда мы "definition" функцию, мы определяем поведение ф

Streams
Input and output in C++ is based on the concept of a stream. A stream is a sequence of bytes that flow from something to something else. The process of output involves moving bytes, one at a time,

Using the Standard Streams
Three specific streams are always available throughout the lifetime of every C++ program. These are the standard input, standard output, and standard error streams. Each of these standard streams h

File Input and Output
File based input and output is similar to the mechanisms for keyboard and screen I/O. The main difference is that programmers must explicitly open and close files. In pseudocode, a generic program

Some Common Pitfalls
  A common mistake for many new C++ programmers is to reverse the << and >> operators. A good way to remember which operator to use is to think of them as arrows. You alwa

Streams
Ввод и вывод в C ++ основан на понятии потока. Поток - последовательность байтов, которые вытекают из одного в другое. Процесс продукции вовлекает байты, по одному, с программы на устройство. Это у

Using the Standard Streams
Три определенных потока всегда доступны всюду в C ++ программах. Это standard input, standard output, and standard error потоки. У каждого из этих стандартных потоков есть определенное использовани

File Input and Output
Файл вход и выход подобен механизмам для ввода / вывода экрана и клавиатуры. Главное различие - то, что программисты должны явно открыть и закрыть файлы. В псевдокоде главная программа, которая чит

Some Common Pitfalls
Частая ошибка для многих новых C ++ программисты состоит в том, чтобы полностью изменить << и >> операторы. Хороший способ помнить, какой оператор использовать должен думать о них как о

Text Substitution
The preprocessor is a tool that C++ programmers use to manipulate the contents of source code files prior to compilation. In the most general sense, the preprocessor performs text substitution and

File Inclusion
File inclusion is a feature of the C++ preprocessor that allows a source code file to use shared code. We consider shared code to be classes or functions declared in other files. In C++, we can onl

Macro Substitution
The C++ preprocessor can perform a programmer defined text substitution throughout an entire source code file. This is known as macro substitution. Programmers define a macro using the #define prep

An Example: Assumption Verification
Verifying assumptions using assertions is an example of a common use of the preprocessor and its features. An assertion is a statement placed in source code to verify an assumption. Usually, progra

Text Substitution
Препроцессор это инструмент, чтобы управлять содержанием файлов исходного текста до компиляции. В самом общем смысле препроцессор выполняет текстовую замену и текстовую модификацию. Высокоуровневые

File Inclusion
Включение файла - особенность C++ препроцессор, который позволяет файлу исходного текста использовать разделенные коды. Мы полагаем, что разделенный код это классы или функции, объявленные в других

Macro Substitution
C++ препроцессор может определить текстовую замену всюду по всему файлу исходного текста. Это известно как макро-замена. Программисты реализуют макро-замену директивой #define препроцессора, котора

Conditional Compilation
Вне макро-замены важная причина использовать #define состоит в том, чтобы поддержать условную трансляцию. Используя #define, и некоторые другие директивы препроцессора, мы можем проинструктировать

An Example: Assumption Verification
Подтверждение предположений, используя утверждения является примером обычного использования препроцессора и его особенностей. assertion - утверждение, помещенное в исходный текст, чтобы проверить п

Хотите получать на электронную почту самые свежие новости?
Education Insider Sample
Подпишитесь на Нашу рассылку
Наша политика приватности обеспечивает 100% безопасность и анонимность Ваших E-Mail
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги