Jump to content

Directive (programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Jgaughan (talk | contribs) at 20:15, 25 August 2004 (Initial). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

A directive is an instruction to a programming language compiler about how to compile a program. Rather than providing code per se, a programmer uses a directive to modify how or even if code is compiled.

Overview

Directives are used in several languages such as ASM, C and C++. In ASM, directives generally tell the assembler the target platform, delineate segments, et al. In C++, directives are used for conditional compiling, macros and including other files.

Examples

C/C++

There are several preprocessor directives in C and C++. The following are a few examples, but do not illustrate every directive or every situation in which one might find them. Note the lack of semicolons at the end of the lines: directives are instructions to the preprocessor, not the compiler, and they follow their own language grammar and rules.

#include <iostream>

This is the most common form for most programmers. It instructs the preprocessor to read a file from disk and insert its contents into the source code file. In this case it reads the general I/O streams header from the compiler's standard header directory.

#define PI (3.14159)
cout << (2.0 * PI) << endl;

Macros are, essentially, preprocessor variables that are expanded inline into the source code. This example defines a macro named PI that is expanded to 3.14159 everywhere it is found in the code. This is deprecated in most cases, as C and C++ both provide constants that are more efficient and provide strong typing.

#if defined LINUX
// Do some Linux stuff here
#elif defined WINDOWS
// Do some Windows stuff here
#endif

Another common directive, this generally is used for conditional compilation. This example shows a directive that chooses two sets of code to include in the preprocessor output depending on which operating system macro is defined.