Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Include directive

From Wikipedia, the free encyclopedia
Text file processor instruction to include the content of one file into another

Aninclude directive instructs atext 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. TheC preprocessor (used withC,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 bycopy in order to include acopybook.

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

The include directive can supportencapsulation andreuse. 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 allowingdeclaration separate fromimplementation. 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 asGo,Python andHaskell supportmodularization via animport statement, which makes the compiler/interpreter load a module, resolving code through the linked module, not by including text. Compiled languages, such asRust andD, simply link allobject files at compile time. Similarly, C++ also introducedimport to importC++ modules, which uses.pcm files to store as intermediates similar to howprecompiled headers work. AlthoughJava hasimport andC# hasusing, these are not the same as an include directive. In fact, in these languages, classes are loaded on demand by aclass loader, and can be accessed simply by fully qualifying the class with itsnamespaces. 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.

Language support

[edit]

C/C++

[edit]

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 codelibraries 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 supportglobbing patterns, so for example#include"*.h" would not include all*.h files in the current directory.

Example

[edit]

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

#pragma onceintadd(int,int);inttriple(intx){returnadd(x,add(x,x));}

One drawback of this approach is that the function prototype must be present in each file that callsadd(). 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 fileAdd.h, the using source file becomes:

#include"Add.h"inttriple(intx){returnadd(x,add(x,x));}

Header file

[edit]

In C and C++, aheader file is asource code file that allowsprogrammers to share and reusedeclarations of acodebase – often implemented into separated, logically related groupings.

A header filedeclares programming elements such asfunctions,classes,variables, and preprocessormacros. 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 theimplementation.[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 aninclude guard in each header file.[4]

TheC standard library is declared as a collection of header files. TheC++ 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.hfile 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

[edit]

SinceC++20, C++ supports import semantics via theheader 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 ofC++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 optionalimport<vector>;// supporting this is mandated by the standardexportimport"MyHeader.h";

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

Modules

[edit]

Since C++20,modules were introduced and is imported usingimport. These have the same semantics to import as header units, but have finer grained control of exports. SinceC++26, they are not handled by the preprocessor at all. They must be markedmodule and each symbol must be markedexport or be in aexport block to be accessible by importing. The semantics of animport statement are:

exportoptional import module_name;

As ofC++23, theC++ standard library can be imported as a module by writingimportstd;.

// imports the C++ standard libraryimportstd;// imports a module named "com.acme.project.math.BigInteger"importcom.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.Loggerexportimportorg.wikipedia.util.logging.Logger;

Embed

[edit]

Added inC23 andC++26, the#embed directive is similar to the#include directive but is more appropriate for including/embedding binary resources into source code.

constunsignedchariconDisplayData[]={#embed "art.png"};// specify any type which can be initialized form integer constant expressions will doconstcharresetBlob[]={#embed "data.bin"};// attributes work just as wellconstsignedcharalignedDataString[]__attribute__((aligned(8)))={#embed "attributes.xml"};intmain(){return#embed </dev/urandom> limit(1);}

Objective-C

[edit]

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 theimport statement in C++ (which imports a module), or theMicrosoft Visual C++#import directive, which imports a type library.[8]

COBOL

[edit]

COBOL (and alsoRPG 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 isCOPY, and replacement is done using theREPLACING ... BY ... clause. An include directive has been present in COBOL since COBOL 60, but changed from the originalINCLUDE[9] toCOPY by 1968.[10]

Fortran

[edit]

Fortran does not require header filesper 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 ause 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

[edit]

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

Pascal

[edit]

MostPascal 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

  • {$ifilename.pas}
  • (*$Ifilename.inc*)
  • {$includefilename.inc}
  • (*INCLUDEfilename.pas*)

Where the$i or$include directive is notcase sensitive, andfilename.pas orfilename.inc is the name of the file to be included. (It has been common practice to name Pascal's include files with theextension.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

[edit]

InPHP, theinclude directive causes another PHP file to be included and evaluated.[11] Similar commands arerequire, which upon failure to include will produce afatal exception and halt the script,[12] andinclude_once andrequire_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

[edit]

Rust has theinclude! 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");fnmain(){// ... use items from generated_code.rs}

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

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

letmy_str:&'staticstr=include_str!("spanish.in");letbytes:&'static[u8]=include_bytes!("spanish.in");

Other languages

[edit]

Other notable languages with an include directive:

  • include ... (Fortran,MASM)
  • <!--#include ... --> (HTMLSSI)
  • var ... = require("...") (JavaScript withCommonJS)
  • <%@ include ... %> (JSP)
  • {$I ...} (UCSD Pascal,Turbo Pascal)
  • %include ... (PL/I)
  • /COPYQCPYLESRC,QBC (RPG IV – first argument is the filename, second argument is the copybook)
  • local ... = require("...") (Lua)

Modern languages (e.g.Haskell andJava) tend to avoid the include directive construct, preferringmodules and import/export semantics. Some of these languages (such as Java andC#) do not use forward declarations and, instead, identifiers are recognized automatically from source files and read directly fromdynamic library symbols (typically referenced withimport orusing directives).

See also

[edit]

References

[edit]
  1. ^C11 standard, 6.10.2 Source file inclusion, pp. 164–165
  2. ^Stallman, Richard M. (July 1992)."The C Preprocessor"(PDF). Archived fromthe original(PDF) on 4 September 2012. Retrieved19 February 2014.
  3. ^Alan Griffiths (2005)."Separating Interface and Implementation in C++". ACCU. Retrieved2013-05-07.
  4. ^Pike, Rob (21 Feb 1989),Notes on programming in C, Cat-v document archive, retrieved9 Dec 2011
  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"(PDF).
  7. ^"P1502R1 - Standard library header units for C++20".
  8. ^Microsoft Corporation."#import directive (C++)".learn.microsoft.com. Microsoft Learn. Retrieved6 December 2025.
  9. ^"COBOL Initial Specifications for a COmmon Business Oriented Language"(PDF).Department of Defense. April 1960. p. IX-9. Archived fromthe original(PDF) on 12 February 2014. Retrieved11 February 2014.
  10. ^"The COPY Statement".CODASYL COBOL Journal of Development 1968. July 1969.LCCN 73601243.
  11. ^"include".php.net. The PHP Group. Retrieved20 February 2014.
  12. ^"require".php.net. The PHP Group. Retrieved20 February 2014.
  13. ^"include in std - Rust".doc.rust-lang.org. Retrieved8 September 2025.
  14. ^"include_str in std - Rust".doc.rust-lang.org. Retrieved4 July 2025.

External links

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Include_directive&oldid=1330111634"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp