Include directive

Short description: Text file processor instruction to include the content of one file into another

An include directive instructs a text file processor to replace the directive text with the content of a specified file.

The act of including may be logical in nature. The processor may simply process the include file content at the location of the directive without creating a combined file.

Different processors may use different syntax. The C preprocessor (used with C, C++ and in other contexts) defines an include directive as a line that starts `#include` and is followed by a file specification. COBOL defines an include directive indicated by `copy` in order to include a copybook.

Generally, for C/C++ the include directive is used to include a header file, but can include any file. Although relatively uncommon, it is sometimes used to include a body file such as a .c file.

The include directive can support encapsulation and reuse. Different parts of a system can be segregated into logical groupings yet rely on one another via file inclusion. C and C++ are designed to leverage include while also optimizing build time by allowing declaration separate from implementation. The included information can be minimized to only declarations.

As directly including file content has significant drawbacks, such as excessive boilerplate or type/language syntax unawareness, newer languages have been designed without an include directive. Languages such as Go, Python and Haskell support modularization via an import statement, which makes the compiler/interpreter load a module, resolving code through the linked module, not by including text. Compiled languages, such as Rust and D, simply link all object files at compile time. Similarly, C++ also introduced `import` to import C++ modules, which uses .pcm files to store as intermediates similar to how precompiled headers work. Although Java has `import` and C# has `using`, these are not the same as an include directive. In fact, in these languages, classes are loaded on demand by a class loader, and can be accessed simply by fully qualifying the class with its namespaces. The import statements in these languages are used only to add a class to the current scope.

Although C# has the ability to use some preprocessor directives similar to those of the C preprocessor, it does not contain the `#include` directive.

## Contents

* 1 Language support
* 1.1 C/C++
* 1.1.1 Example
* 1.1.2 Header file
* 1.1.3 Header unit
* 1.1.4 Modules
* 1.1.5 Embed
* 1.2 Objective-C
* 1.3 COBOL
* 1.4 Fortran
* 1.5 Haskell
* 1.6 Pascal
* 1.7 PHP
* 1.8 Rust
* 1.9 Other languages
* 2 See also
* 3 References
* 4 External links

## Language support

### C/C++

Both C and C++ (pre-C++20) are typically used with the C preprocessor that replaces a `#include` directive line with the content of the file specified. A file path is either enclosed in double quotes (i.e. "Header.h") or angle brackets (i.e. <Header.h>).[1] Some preprocessors locate the include file differently based on the enclosing delimiters; treating a path in double-quotes as relative to the including file and a path in angle brackets as located in one of the directories of the configured system search path.[2]

Example include statements:

// include the C standard header 'stdio.h'; probably is a file with that name
#include <stdio.h>
// include the C++ standard header 'vector'; may or may not be a file
#include <vector>
// include a custom header file named 'MyHeader.h'
#include "MyHeader.h"

The include directive allows for the development of code libraries that:

* helps ensure that everyone uses the same version of a data layout definition or procedural code throughout a program
* easily cross-reference where components are used in a system
* easily central/general change programs when needed (only one file should be edited)
* save time by reusing data layouts

Include directives do not support globbing patterns, so for example `#include "*.h"` would not include all *.h files in the current directory.

#### Example

Given two C source files. One defines a function `add()` and another uses the function. Without using an include directive, the consuming file can declare the function locally as a function prototype:

#pragma once

int add(int, int);

int triple(int x) {
return add(x, add(x, x));

One drawback of this approach is that the function prototype must be present in each file that calls `add()`. Another drawback is that if the signature changes, then each consuming file needs to be updated. Putting the prototype in a single, separate file avoids these issues. If the prototype is moved to a header file Add.h, the using source file becomes:

#include "Add.h"

int triple(int x) {
return add(x, add(x, x));

#### Header file

In C and C++, a header file is a source code file that allows programmers to share and reuse declarations of a codebase – often implemented into separated, logically related groupings.

A header file declares programming elements such as functions, classes, variables, and preprocessor macros. A header file allows the programmer to use programming elements in multiple body files based on the common declaration in the header file. Declarations in a header file allow body files to use implementations without including the implementation code directly. The header keeps the interface separate from the implementation.[3]

Compilation errors may occur if multiple header files include the same file. One solution is to avoid including files in header files – possibly requiring excessive include directives in body files. Another solution is to use an include guard in each header file.[4]

The C standard library is declared as a collection of header files. The C++ standard library is similar, but the declarations may be provided by the compiler without reading an actual file.

C standard header files are named with a .h file name extension, as in `#include <stdio.h>`. Typically, custom C header files have the same extension. Custom C++ header files tend to have more variety of extensions, including .hpp, .hh, .h++ and .hxx.

A C++ standard library name in angle brackets (i.e. <vector>) results in declarations being included but may not be from a file.[5]

#### Header unit

Since C++20, C++ supports import semantics via the header unit, that is, separate translation units synthesized from a header.[6] They are meant to be used as a transitional state towards total adoption of modules.

`import`, as of C++26, is not a preprocessor directive. It is thus not handled by the C preprocessor. `import` does not copy code into a file like `#include`, but rather links the translation unit during compile time.

Example:

import <stdio.h>; // supporting this is optional
import <vector>; // supporting this is mandated by the standard
export import "MyHeader.h";

Header units are provided for all the C++ standard library headers.[7]

#### Modules

Since C++20, modules were introduced and is imported using `import`. These have the same semantics to import as header units, but have finer grained control of exports. Since C++26, they are not handled by the preprocessor at all. They must be marked `module` and each symbol must be marked `export` or be in a `export` block to be accessible by importing. The semantics of an `import` statement are:

exportoptional import module_name;

As of C++23, the C++ standard library can be imported as a module by writing `import std;`.

// imports the C++ standard library
import std;

// imports a module named "com.acme.project.math.BigInteger"
import com.acme.project.math.BigInteger;

// imports a module named "org.wikipedia.util.logging.Logger", and re-exports it
// any file that imports this module will transitively import org.wikipedia.util.logging.Logger
export import org.wikipedia.util.logging.Logger;

#### Embed

Added in C23 and C++26, the `#embed` directive is similar to the `#include` directive but is more appropriate for including/embedding binary resources into source code.

const unsigned char iconDisplayData[] = {
#embed "art.png"

// specify any type which can be initialized form integer constant expressions will do
const char resetBlob[] = {
#embed "data.bin"

// attributes work just as well
const signed char alignedDataString[] __attribute__ ((aligned (8))) = {
#embed "attributes.xml"

int main() {
return
#embed </dev/urandom> limit(1)

### Objective-C

Objective-C, like C, also uses header files and has an `#include` directive. However, it also has a `#import` directive, which behaves the same as `#include`, the only difference being that `#import` guarantees the inclusion of the file will never happen more than once, without the use of #include guards or #pragma once.

The Objective-C `#import` directive should not be confused for the `import` statement in C++ (which imports a module), or the Microsoft Visual C++ `#import` directive, which imports a type library.[8]

### COBOL

COBOL (and also RPG IV) allows programmers to copy copybooks into the source of the program – which is similar to including but allows for replacing text. The COBOL keyword for inclusion is `COPY`, and replacement is done using the `REPLACING ... BY ...` clause. An include directive has been present in COBOL since COBOL 60, but changed from the original `INCLUDE`[9] to `COPY` by 1968.[10]

### Fortran

Fortran does not require header files per se. However, Fortran 90 and later have two related features: `include` statements and modules. The former can be used to share a common file containing procedure interfaces, much like a C header, although the specification of an interface is not required for all varieties of Fortran procedures. This approach is not commonly used; instead, procedures are generally grouped into modules that can then be referenced with a `use` statement within other regions of code. For modules, header-type interface information is automatically generated by the compiler and typically put into separate module files, although some compilers have placed this information directly into object files. The language specification itself does not mandate the creation of any extra files, even though module procedure interfaces are almost universally propagated in this manner.

### Haskell

The Haskell language, which can use the C preprocessor by writing `{-# LANGUAGE CPP #-}`, has access to the `#include` directive.

### Pascal

Most Pascal compilers support the `$i` or `$include` compiler directive, in which the `$i` or `$include` directive immediately follows the start of a comment block in the form of

* `{$i filename.pas}`
* `(*$I filename.inc*)`
* `{$include filename.inc}`
* `(*INCLUDE filename.pas*)`

Where the `$i` or `$include` directive is not case sensitive, and filename.pas or filename.inc is the name of the file to be included. (It has been common practice to name Pascal's include files with the extension .inc, but this is not required.) Some compilers, to prevent unlimited recursion, limit invoking an include file to a certain number, prohibit invoking itself or any currently open file, or are limited to a maximum of one include file at a time, e.g. an include file cannot include itself or another file. However, the program that includes other files can include several, just one at a time.

### PHP

In PHP, the `include` directive causes another PHP file to be included and evaluated.[11] Similar commands are `require`, which upon failure to include will produce a fatal exception and halt the script,[12] and `include_once` and `require_once`, which prevent a file from being included or required again if it has already been included or required, avoiding the C's double inclusion problem.

### Rust

Rust has the `include!` macro, which behaves essentially the same as `#include` from C. It parses the item either as an expression or an item, depending on the context.[13]

include!("generated_code.rs");

fn main() {
// ... use items from generated_code.rs

However, unlike C, this is not the usual method of separating and including code. Instead, Rust uses modules, which preserve namespaces and encapsulation.

Rust also supports an `include_str!` macro which instead allows an entire file to be included and stored into a string.[14] There is similarly a `include_bytes!` macro.

let my_str: &'static str = include_str!("spanish.in");
let bytes: &'static [u8] = include_bytes!("spanish.in");

### Other languages

Other notable languages with an include directive:

* `include ...` (Fortran, MASM)
* `<!--#include ... -->` (HTML SSI)
* `var ... = require("...")` (JavaScript with CommonJS)
* `<%@ include ... %>` (JSP)
* `{$I ...}` (UCSD Pascal, Turbo Pascal)
* `%include ...` (PL/I)
* `/COPY QCPYLESRC,QBC` (RPG IV - first argument is the filename, second argument is the copybook)
* `local ... = require("...")` (Lua)

Modern languages (e.g. Haskell and Java) tend to avoid the include directive construct, preferring modules and import/export semantics. Some of these languages (such as Java and C#) do not use forward declarations and, instead, identifiers are recognized automatically from source files and read directly from dynamic library symbols (typically referenced with `import` or `using` directives).

## See also

* Application programming interface - Set of subroutine definitions, protocols, and tools for building software and applications
* Class implementation file - File implementing the methods of a class
* Header-only
* Interface Definition Language
* File inclusion vulnerability - Type of web vulnerability
* Modular programming - Organizing code into modules
* One Definition Rule - Rule of programming language C++
* #pragma once - Preprocessor directive in C and C++
* Precompiled header - Optimized type of file in computer programming
* Modules (C++)
* Transclusion
* Unity build - Technique to speed up C/C++ project builds

## References

1. ↑ C11 standard, 6.10.2 Source file inclusion, pp. 164–165
2. ↑ Stallman, Richard M. (July 1992). "The C Preprocessor". http://docs.freebsd.org/info/cpp/cpp.pdf.
3. ↑ Alan Griffiths (2005). "Separating Interface and Implementation in C++". ACCU. http://accu.org/index.php/journals/269. Retrieved 2013-05-07.
4. ↑
5. ↑ C11 standard, 7.1.2 Standard headers, p. 181, footnote 182: "A header is not necessarily a source file, nor are the `<` and `>` delimited sequences in header names necessarily valid source file names.
6. ↑ "Merging Modules - P1103R3". https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1103r3.pdf.
7. ↑ "P1502R1 - Standard library header units for C++20". https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1502r1.html.
8. ↑ Microsoft Corporation. "#import directive (C++)". Microsoft Learn. https://learn.microsoft.com/en-us/cpp/preprocessor/hash-import-directive-cpp.
9. ↑ "COBOL Initial Specifications for a COmmon Business Oriented Language". Department of Defense. April 1960. p. IX-9. http://bitsavers.trailing-edge.com/pdf/codasyl/COBOL_Report_Apr60.pdf.
10. ↑ CODASYL COBOL Journal of Development 1968. July 1969. https://archive.org/details/codasylcoboljour00conf.
11. ↑ "include". The PHP Group. http://www.php.net/manual/en/function.include.php.
12. ↑ "require". The PHP Group. https://www.php.net/manual/en/function.require.php.
13. ↑ "include in std - Rust". https://doc.rust-lang.org/std/macro.include.html.
14. ↑ "include_str in std - Rust". https://doc.rust-lang.org/std/macro.include_str.html.

## External links

* Organizing Code Files (the potential pitfalls and guidelines for using header files in C++)
* C++ header file inclusion rules

fr:Bibliothèque standard du C#Les en-têtes de la bibliothèque C ISO

0.00

(0 votes)

Original source: https://en.wikipedia.org/wiki/Include directive. Read more

|

Retrieved from "https://handwiki.org/wiki/index.php?title=Include_directive&oldid=4225865"