Include directive

Many programming languages and other computer files have a directive, often called include, import, or copy, that causes the contents of the specified file to be inserted into the original file. These included files are called header files or copybooks. They are often used to define the physical layout of program data, pieces of procedural code, and/or forward declarations while promoting encapsulation and the reuse of code or data.

Header files

In computer programming, a header file is a file that allows programmers to separate certain elements of a program's source code into reusable files. Header files commonly contain forward declarations of classes, subroutines, variables, and other identifiers. Programmers who wish to declare standardized identifiers in more than one source file can place such identifiers in a single header file, which other code can then include whenever the header contents are required. This is to keep the interface in the header separate from the implementation.[1]

The C standard library and the C++ standard library traditionally declare their standard functions in header files.

Some newer compiled languages (such as Java and C#) do not use forward declarations; identifiers are recognized automatically from source files and read directly from dynamic library symbols. This means header files are not needed.

Purpose

The include directive allows libraries of code to be developed which help to:

  • 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 change programs when needed (only one file must be edited), and
  • save time by reusing data layouts.

Example

An example situation which benefits from the use of an include directive is when referring to functions in a different file. Suppose there is some C source file containing a function add, which is referred to in a second file by first declaring its external existence and type (with a function prototype) as follows:

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 all files that use the function. Another drawback is that if the return type or arguments of the function are changed, all of these prototypes would need to be updated. Putting the prototype in a single, separate file avoids these issues. Assuming the prototype is moved to the file add.h, the second source file can then become:

#include "add.h"

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

Now, every time the code is compiled, the latest function prototypes in add.h will be included in the files using them, avoiding potential errors.

Language support

C/C++

In the C and C++ programming languages, the #include preprocessor directive causes the compiler to replace that line with the entire text of the contents of the named source file (if included in quotes: "") or named header (if included in angle brackets: <>);[2] a header doesn't need to be a source file.[3] Inclusion continues recursively on these included contents, up to an implementation-defined nesting limit. Headers need not have names corresponding to files: in C++ standard headers are typically identified with words, like "vector", hence #include <vector>, while in C standard headers have identifiers in the form of filenames with a ".h" extension, as in #include <stdio.h>. A "source file" can be any file, with a name of any form, but is most commonly named with a ".h" extension and called a "header file" (sometimes ".hpp" or ".hh" to distinguish C++ headers), though files with .c, .cc, and .cpp extensions may also be included (particularly in the single compilation unit technique), and sometimes other extensions are used.

These two forms of #include directive can determine which header or source file to include in an implementation-defined way. In practice, what is usually done is that the angle-brackets form searches for source files in a standard system directory (or set of directories), and then searches for source files in local or project-specific paths (specified on the command line, in an environment variable, or in a Makefile or other build file), while the form with quotes does not search in a standard system directory, only searching in local or project-specific paths.[4] In case there is no clash, the angle-brackets form can also be used to specify project-specific includes, but this is considered poor form. The fact that headers need not correspond to files is primarily an implementation technicality, and is used to omit the .h extension in including C++ standard headers; in common use, "header" means "header file".

For example:

#include <stdio.h>  // Include the contents of the standard header 'stdio.h' (probably a file 'stdio.h').
#include <vector>  // Include the contents of the standard header 'vector' (probably a file 'vector.h').
#include "user_defined.h"  // Include the contents of the file 'user_defined.h'.

In C and C++, problems may be faced if two (or more) include files contain the same third file. One solution is to avoid include files from including any other files, possibly requiring the programmer to manually add extra include directives to the original file. Another solution is to use include guards.[5]

Since C++20, headers can also be imported as header units, that is, separate translation units synthesized from a header.[6] They are meant to be used alongside modules. The syntax used in that case is

exportoptional import header-name;

For example:

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

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

COBOL

COBOL (and also RPG IV) allows programmers to copy copybooks into the source of the program in a similar way to header files, but it also allows for the replacement of certain text in them with other 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[8] to COPY by 1968.[9]

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.

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.[10] Similar commands are require, which upon failure to include will produce a fatal exception and halt the script,[11] 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.

Other languages

There are many forms of the include directive, such as:

  • include ... (Fortran, MASM)
  • <!--#include ... --> (HTML SSI)
  • import ...; (Java)
  • import ... from ... (JavaScript as in ECMAScript)
  • var ... = require("...") (JavaScript with CommonJS)
  • <%@ include ... %> (JSP)
  • {$I ...} (UCSD Pascal, Turbo Pascal)
  • %include ... (PL/I)
  • import ... (Python)
  • /COPY QCPYLESRC,QBC (RPG IV – first argument is the filename, second argument is the copybook)
  • use ...; (Rust)
  • using ...; (C#)
  • local ... = require("...") (Lua)
  • import ...; (D)

Modern languages (e.g. Haskell and Java) tend to avoid copybooks or includes, preferring modules and import/export systems for namespace control. 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), meaning header files are not needed.

See also

References

  1. ^ Alan Griffiths (2005). "Separating Interface and Implementation in C++". ACCU. Retrieved 2013-05-07.
  2. ^ C11 standard, 6.10.2 Source file inclusion, pp. 164–165
  3. ^ 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.
  4. ^ Stallman, Richard M. (July 1992). "The C Preprocessor" (PDF). Archived from the original (PDF) on 4 September 2012. Retrieved 19 February 2014.
  5. ^ Pike, Rob (21 Feb 1989), Notes on programming in C, Cat-v document archive, retrieved 9 Dec 2011
  6. ^ "Merging Modules - P1103R3" (PDF).
  7. ^ "P1502R1 - Standard library header units for C++20".
  8. ^ "COBOL Initial Specifications for a COmmon Business Oriented Language" (PDF). Department of Defense. April 1960. p. IX-9. Archived from the original (PDF) on 12 February 2014. Retrieved 11 February 2014.
  9. ^ "The COPY Statement". CODASYL COBOL Journal of Development 1968. July 1969. LCCN 73601243.
  10. ^ "include". php.net. The PHP Group. Retrieved 20 February 2014.
  11. ^ "require". php.net. The PHP Group. Retrieved 20 February 2014.

Read other articles:

Pottery and porcelain from China Chinaware redirects here. For general information about the material, see Porcelain. Covered red jar with dragon and sea design from the Jiajing period (1521–1567) in the Ming dynasty Chinese ceramics show a continuous development since pre-dynastic times and are one of the most significant forms of Chinese art and ceramics globally. The first pottery was made during the Palaeolithic era. Chinese ceramics range from construction materials such as bricks and ...

Johnny & Associates Sede de Johnny & Associates en Akasaka, Tokio.Acrónimo J&ATipo PúblicaIndustria EntretenimientoForma legal kabushiki gaishaFundación Junio de 1962 (56 años)Fundador Johnny KitagawaSede central Minato (Japón)Área de operación MusicalPresidente Noriyuki HigashiyamaPropietario Julie Keiko FujishimaEmpleados 210Divisiones Johnny's EntertainmentJohnny's Jr.J StormJ-One RecordsFiliales J Stormsin etiquetarCoordenadas 35°40′12″N 139°43′47″E / ...

Halaman ini berisi artikel tentang unsur kimia. Untuk penggunaan litium sebagai obat, lihat Litium (medis). Untuk kegunaan lain, lihat Litium (disambiguasi). Litium,  3LiLitium yang mengapung dalam minyak Garis spektrum litiumSifat umumNama, lambanglitium, LiPengucapan/litium/[1] Penampilanputih keperakanLitium dalam tabel periodik Hidrogen Helium Lithium Berilium Boron Karbon Nitrogen Oksigen Fluor Neon Natrium Magnesium Aluminium Silikon Fosfor Sulfur Clor Argon Potas...

Die UCI Asia Tour 2018 ist die 14. Austragung des zur Saison 2005 vom Weltradsportverband UCI eingeführten asiatischen Straßenradsport-Kalenders unterhalb der UCI WorldTour, der zu den UCI Continental Circuits für Männer gehört. Die Eintagesrennen und Etappenrennen der UCI Asia Tour sind in drei UCI-Kategorien (HC, 1 und 2) eingeteilt. Bei jedem Rennen werden Punkte für eine Gesamtwertung der Fahrer, Mannschaften und Nationen vergeben. An der Mannschaftswertung nehmen die Professional C...

Rochet Frères & Cie Rechtsform Gründung 1898 Auflösung 1901 Sitz Lyon Branche Automobilhersteller Rochet Frères 1898 Rochet Frères, angeblich von 1903 Rochet Frères & Cie war ein französischer Hersteller von Automobilen.[1][2][3] Inhaltsverzeichnis 1 Unternehmensgeschichte 2 Modelle 3 Literatur 4 Einzelnachweise Unternehmensgeschichte Das Unternehmen aus Lyon begann 1898 mit der Produktion von Automobilen. Der Markenname lautete Rochet oder Rochet Frère...

Assinaboines Gebied van de Assiniboine De Assiniboine, Assiniboin of Hohe (endoniem: Nakota, Nakoda of Nakona) zijn een indiaans volk dat in het noorden van de Great Plains leeft. Tegenwoordig wonen ze voornamelijk in de Canadese provincie Saskatchewan. Cultureel gezien behoren de Assiniboine tot de prairie-indianen. Hun oorspronkelijke taal is Assiniboine, een taal van de Siouxtaalfamilie. De voorouders van de Assiniboine behoorden tot de Sioux, van wie ze zich omstreeks 1600 afsplitsten. Ze...

State flag of South Dakota Location of South Dakota on the U.S. map This is a list of prominent people who were born in or lived for a significant period in U.S. state of South Dakota. For a larger list by location, see People from South Dakota. This is a dynamic list and may never be able to satisfy particular standards for completeness. You can help by adding missing items with reliable sources. Academia Vine Deloria Jr., American Indian author, theologian, historian, and activist Alvin Han...

Kommilfoo kan verwijzen naar: Kommil Foo, een Vlaams cabaret-duo Kommilfoo (restaurant), een restaurant in Antwerpen Bekijk alle artikelen waarvan de titel begint met Kommilfoo of met Kommilfoo in de titel. Dit is een doorverwijspagina, bedoeld om de verschillen in betekenis of gebruik van Kommilfoo inzichtelijk te maken. Op deze pagina staat een uitleg van de verschillende betekenissen van Kommilfoo en verwijzingen daarnaartoe. Bent u hier via een pagina in Wikipedia...

Association football club in Bermuda Football clubPHC ZebrasFull nameThe Pembroke Hamilton Club Inc.Nickname(s)ZebrasShort namePHCFounded1950; 73 years ago (1950)GroundPHC Field,Warwick, BermudaCapacity2,000ChairmanMike TrottManagerWinston TrottLeagueBermudian Premier Division2022-20231st Home colours The Pembroke Hamilton Club Zebras is a Bermudian professional football club based in Hamilton, that participates in Bermudian Premier Division. They play their home games on PH...

ImagawayakiSajianKueTempat asalJepangBahan utamaadonan panekuk, selai kacang merah  Media: Imagawayaki Imagawayaki (kaitenyaki) sedang dipanggang di toko Gozasōrō, Sannomiya, Kobe. Imagawayaki (今川焼きcode: ja is deprecated ) adalah kue Jepang berisi selai kacang merah. Adonan kue berbentuk cair, dibuat dari campuran terigu, telur, gula, dan air. Imagawayaki dipanggang di atas loyang tembaga yang memiliki lubang-lubang berbentuk bundar. Sewaktu kue hampir matang, selai kacang ...

  لمعانٍ أخرى، طالع العزيمة (توضيح). العزيمة  -  قرية مصرية -  تقسيم إداري البلد  مصر المحافظة محافظة المنيا المركز سمالوط المسؤولون السكان التعداد السكاني 1349 نسمة (إحصاء 2006) معلومات أخرى التوقيت ت ع م+02:00  تعديل مصدري - تعديل   قرية العزيمة هي إحدي القرى ...

You can help expand this article with text translated from the corresponding article in Swedish. (April 2021) Click [show] for important translation instructions. View a machine-translated version of the Swedish article. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipe...

Football stadium in Holloway, London, England Emirates StadiumAshburton GroveUEFA LocationHighbury House, 75 Drayton Park, London, N5 1BUEngland[1]Coordinates51°33′24″N 0°6′22″W / 51.55667°N 0.10611°W / 51.55667; -0.10611Public transit Arsenal Holloway Road Finsbury Park Highbury & Islington Drayton ParkOwnerKroenke Sports & EntertainmentOperatorKroenke Sports & EntertainmentExecutive suites152Capacity60,704[4]Record attenda...

Inspiring narrative about a nation's past The Dispute of Minerva and Neptune (c. 1689 or 1706) by René-Antoine Houasse, depicting the founding myth of Athens A national myth is an inspiring narrative or anecdote about a nation's past. Such myths often serve as important national symbols and affirm a set of national values. A national myth may sometimes take the form of a national epic or be incorporated into a civil religion. A group of related myths about a nation may be referred to as the ...

50°41′31″N 01°18′49″W / 50.69194°N 1.31361°W / 50.69194; -1.31361 ChurchSt Mary's Church, CarisbrookeDenominationChurch of EnglandChurchmanshipBroad ChurchHistoryDedicationSt MaryAdministrationProvinceCanterburyDiocesePortsmouthParishCarisbrooke St Mary's Church, Carisbrooke is a parish church in the Church of England located in Carisbrooke, Isle of Wight. A service is held every Sunday morning at 8:00 and 9:30. History The church is medieval dating from th...

Superorder of insects Amphiesmenoptera Celastrina argiolus (Lepidoptera) Chaetopteryx villosa (Trichoptera) Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Arthropoda Class: Insecta Superorder: Panorpida (unranked): AmphiesmenopteraKiriakoff [nl; sv], 1948 Subgroups †Eocoronidae †Necrotauliidae Lepidoptera †Tarachoptera Trichoptera Amphiesmenoptera is an insect superorder, established by S. G. Kiriakoff,[1] but often credited to Willi Hennig in...

Valentin Stocker Valentin Stocker[1]Informasi pribadiNama lengkap Valentin StockerTanggal lahir 12 April 1989 (umur 34)Tempat lahir Lucerne, SwissTinggi 1,78 m (5 ft 10 in)Posisi bermain GelandangInformasi klubKlub saat ini Hertha BSCNomor 14Karier junior1996–2005 SC KriensKarier senior*Tahun Tim Tampil (Gol)2005–2008 Basel U21 37 (13)2008–2014 Basel 162 (41)2014– Hertha BSC 0 (0)Tim nasional‡2005 Swiss U-16 5 (1)2005–2006 Swiss U-17 11 (6)2006 Swiss U-...

Indian politician This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Annasaheb Shinde – news · newspapers · books · scholar · JSTOR (August 2021) (Learn how and when to remove this template message) Annasaheb Shindeअण्णासाहेब शिंदेMinister in the Ministry of Agriculture of the Govt...

Filipino pop/R&B singer, producer and media personality This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) Some of this article's listed sources may not be reliable. Please help this article by looking for better, more reliable sources. Unreliable citations may be challenged or deleted. (August 2020) (Learn how and when to remove this template message) This article may need to be rewritt...

2012 Leap Day tornado outbreakAerial view of damage from an EF2 tornado in Branson, Missouri. TypeTornado outbreakDurationFebruary 28–29, 2012 Highest windsStraight-line - 80 mph (130 km/h) in Cedar Vale, Kansas on February 28. Tornadoesconfirmed42 confirmedMax. rating1EF4 tornadoDuration oftornado outbreak226 hours, 17 minutes Largest hail3.00 in (7.6 cm) in Cherryvale, Kansas on February 28. Fatalities15 fatalities, 193 injuriesDamage$475 million[1] (estim...