Include a file: Difference between revisions

From Rosetta Code
Content added Content deleted
(added Nemerle)
(Added COBOL section. Added C++ to C section. Corrected PL/I and x86 syntax highlighting.)
Line 61: Line 61:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<code>get$"<i>module</i>"</code>
<lang bracmat>get$"<i>module</i>"</lang>


=={{header|C}}==
=={{header|C}} / {{header|C++}}==


In C, inclusion of other files is achieved via a preprocessor. The #include preprocessor directive tells the compiler to incorporate code from the included file. This is normally used near the top of a source file and is usually used to tell the compiler to include header files for the function libraries.
In C and C++, inclusion of other files is achieved via a preprocessor. The <code>#include</code> preprocessor directive tells the compiler to incorporate code from the included file. This is normally used near the top of a source file and is usually used to tell the compiler to include header files for the function libraries.


<lang c> /* Standard library header names are enclosed using chevron enclosures */
<lang c> /* Standard library header names are enclosed using chevron enclosures */
Line 74: Line 74:


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>/* The C# language specification does not give a mechanism for 'including' one source file within another,
<lang csharp>
/* The C# language specification does not give a mechanism for 'including' one source file within another,
* likely because there is no need - all code compiled within one 'assembly' (individual IDE projects
* likely because there is no need - all code compiled within one 'assembly' (individual IDE projects
* are usually compiled to separate assemblies) can 'see' all other code within that assembly.
* are usually compiled to separate assemblies) can 'see' all other code within that assembly.
*/
*/</lang>

</lang>
=={{header|COBOL}}==
In COBOL, code is included from other files by the <code>COPY</code> statement. The files are called copybooks, normally end with the file extension '.cpy' and may contain ''any'' valid COBOL syntax. The <code>COPY</code> statement takes an optional <code>REPLACING</code> clause allows any text within the copybook to be replaced with something else.
<lang cobol>COPY "copy.cpy". *> The full stop is mandatory, wherever the COPY is.
COPY "another-copy.cpy" REPLACING foo BY bar
SPACE BY ZERO
==text to replace== BY ==replacement text==.</lang>


=={{header|D}}==
=={{header|D}}==
Line 379: Line 384:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>
<lang pli>%include myfile;</lang>
%include myfile;
</lang>


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
Line 393: Line 396:
=={{header|Prolog}}==
=={{header|Prolog}}==


<lang Prolog>
<lang Prolog>consult('filename').</lang>
consult('filename').
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Line 445: Line 446:
{{works with|ILE RPG}}
{{works with|ILE RPG}}


<lang rpg>
<lang rpg> // fully qualified syntax:
// fully qualified syntax:
/include library/file,member
/include library/file,member


Line 458: Line 458:
/copy library/file,member
/copy library/file,member


//... farther like "include"
//... farther like "include"</lang>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 524: Line 523:


{{works with|FASM on Windows}}
{{works with|FASM on Windows}}
<lang x86 Assembly>
<lang asm>include 'MyFile.INC'</lang>
include 'MyFile.INC'
</lang>


{{works with|nasm}}
{{works with|nasm}}
<lang x86 Assembly>
<lang asm>%include "MyFile.INC"</lang>
%include "MyFile.INC"
</lang>


=={{header|XPL0}}==
=={{header|XPL0}}==

Revision as of 14:55, 6 August 2013

Task
Include a file
You are encouraged to solve this task according to the task description, using any language you may know.

The task is to demonstrate the language's ability to include source code from other files.

ACL2

For files containing only events (definitions and similar; no top-level function calls) which are admissible (note the lack of file extension): <lang Lisp>(include-book "filename")</lang> For all other files: <lang Lisp>(ld "filename.lisp")</lang>

Ada

<lang Ada>with Ada.Text_IO, Another_Package; use Ada.Text_IO;

 -- the with-clause tells the compiler to include the Text_IO package from the Ada standard 
 -- and Another_Package. Subprograms from these packages may be called as follows: 
 --               Ada.Text_IO.Put_Line("some text");
 --               Another_Package.Do_Something("some text"); 
 -- The use-clause allows the program author to write a subprogram call shortly as 
 --               Put_Line("some text");</lang>

AutoHotkey

<lang AutoHotkey>

  1. Include FileOrDirName
  2. IncludeAgain FileOrDirName

</lang>

AWK

The awk extraction and reporting language does not support the use of include files. However, it is possible to provide the name of more than one source file at the command line:

<lang sh>awk -f one.awk -f two.awk</lang>

The functions defined in different source files will be visible from other scripts called from the same command line:

<lang awk># one.awk BEGIN {

 sayhello()

}

  1. two.awk

function sayhello() {

 print "Hello world"

}</lang>

However, it is not permissible to pass the name of additional source files through a hashbang line, so the following will will not work:

#!/usr/bin/awk -f one.awk -f two.awk

BASIC

Works with: QuickBASIC

The include directive must be in a comment and that the name of the file for inclusion is enclosed in single quotes (a.k.a. apostrophes).

Note that this will not work under QBasic.

<lang qbasic>REM $INCLUDE: 'file.bi' '$INCLUDE: 'file.bi'</lang>

See also: BBC BASIC, Gambas, IWBASIC, PowerBASIC, PureBasic, Run BASIC, ZX Spectrum Basic

BBC BASIC

<lang bbcbasic> CALL filepath$</lang> The file is loaded into memory at run-time, executed, and then discarded. It must be in 'tokenised' (internal) .BBC format.

Bracmat

<lang bracmat>get$"module"</lang>

C / C++

In C and C++, inclusion of other files is achieved via a preprocessor. The #include preprocessor directive tells the compiler to incorporate code from the included file. This is normally used near the top of a source file and is usually used to tell the compiler to include header files for the function libraries.

<lang c> /* Standard library header names are enclosed using chevron enclosures */

#include <stdlib.h>
/* User library header names are enclosed using doublequotes */
#include "mylib.h" </lang>

C#

<lang csharp>/* The C# language specification does not give a mechanism for 'including' one source file within another,

* likely because there is no need - all code compiled within one 'assembly' (individual IDE projects
* are usually compiled to separate assemblies) can 'see' all other code within that assembly.
*/</lang>

COBOL

In COBOL, code is included from other files by the COPY statement. The files are called copybooks, normally end with the file extension '.cpy' and may contain any valid COBOL syntax. The COPY statement takes an optional REPLACING clause allows any text within the copybook to be replaced with something else. <lang cobol>COPY "copy.cpy". *> The full stop is mandatory, wherever the COPY is. COPY "another-copy.cpy" REPLACING foo BY bar

                                 SPACE BY ZERO
                                 ==text to replace== BY ==replacement text==.</lang>

D

D has a module system, so usually there is no need of a textual inclusion of a text file: <lang d>import std.stdio;</lang>

To perform a textual inclusion: <lang d>mixin(import("code.txt"));</lang>

Delphi

<lang Delphi>uses SysUtils; // Lets you use the contents of SysUtils.pas from the current unit

{$Include Common} // Inserts the contents of Common.pas into the current unit {$I Common} // Same as the previous line, but in a shorter form</lang>

DWScript

In addition to straight inclusion, there is a filtered inclusion, in which the include file goes through a pre-processing filter. <lang Delphi> {$INCLUDE Common} // Inserts the contents of Common.pas into the current unit {$I Common} // Same as the previous line, but in a shorter form {$INCLUDE_ONCE Common} // Inserts the contents of Common.pas into the current unit only if not included already {$FILTER Common} // Inserts the contents of Common.pas into the current unit after filtering {$F Common} // Same as the previous line, but in a shorter form </lang>

Erlang

<lang Erlang> -include("my_header.hrl"). % Includes the file at my_header.erl </lang>

Euphoria

<lang Euphoria> include my_header.e </lang>

Forth

<lang forth>include matrix.fs</lang>

Other Forth systems have a smarter word, which protects against multiple inclusion. The name varies: USES, REQUIRE, NEEDS.

Fortran

<lang Fortran>include char-literal-constant</lang>

"The interpretation of char-literal-constant is processor dependent. An example of a possible valid interpretation is that char-literal-constant is the name of a file that contains the source text to be included." See section 3.4 Including source text of the ISO standard working draft (Fortran 2003).

Gambas

In gambas, files are added to the project via the project explorer main window which is a component of the integrated development environment.

GAP

<lang gap>Read("file");</lang>

Haskell

<lang Haskell>-- Due to Haskell's module system, textual includes are rarely needed. In -- general, one will import a module, like so: import SomeModule -- For actual textual inclusion, alternate methods are available. The Glasgow -- Haskell Compiler runs the C preprocessor on source code, so #include may be -- used:

  1. include "SomeModule.hs"</lang>

HTML

Current HTML specifications do not provide an include tag, Currently, in order to include content from another file, it is necessary to include content via an iframe. However, this is not supported in some browsers and looks very untidy in other browsers:

<lang html><iframe src="foobar.html"> Sorry: Your browser cannot show the included content.</iframe></lang>

There is an unofficial tag, but this will be ignored by most browsers:

<lang html><include>foobar.html</include></lang>

Icon and Unicon

Include another file of source code using the preprocessor statement: <lang Icon>$include "filename.icn"</lang>

IWBASIC

<lang IWBASIC>$INCLUDE "ishelllink.inc"</lang>

Further, external library or object files can be specified with the $USE statement, which is a compiler preprocessor command:

<lang IWBASIC>$USE "libraries\\mylib.lib"</lang>

IWBASIC also allows resources, files and data that are compiled with an application and embedded in the executable. However, resources in IWBASIC may be used only for projects, i.e., programs that have more than one source file.

Various resources are loaded as follows:

<lang IWBASIC>Success=LOADRESOURCE(ID,Type,Variable)</lang>

ID is either a numeric or string identifier to the resource, TYPE is a numeric or string type and it stores the info in variable. The standard Windows resource types can be specified and loaded in raw form using the following constants:

<lang IWBASIC>@RESCURSOR @RESBITMAP @RESICON @RESMENU @RESDIALOG @RESSTRING @RESACCEL @RESDATA @RESMESSAGETABLE @RESGROUPCURSOR @RESGROUPICON @RESVERSION</lang>

J

The usual approach for a file named 'myheader.ijs' would be:

<lang j>require 'myheader.ijs'</lang>

However, this has "include once" semantics, and if the requirement is to include the file even if it has been included earlier you would instead use:

<lang j>load 'myheader.ijs'</lang>


Java

To include source code from another file, you simply need to create an object of that other file, or 'extend' it using inheritance. The only requirement is that the other file also exists in the same directory, so that the classpath can lead to it. Since Java is quite particular about their "Class name is the same as file name" rule, if you want to use another file called Class2 in Class1, you don't need to be told a unique filename.

Just this would be enough. <lang Java> public class Class1 extends Class2 { //code here } </lang>

You could also consider creating an instance of Class2 within Class1, and then using the instance methods. <lang Java> public class Class1 { Class2 c2=new Class2(); static void main(String[] args) { c2.func1(); c2.func2(); } } </lang>

JavaScript

Following example, if loaded in an HTML file, loads the jQuery library from a remote site <lang javascript>var s = document.createElement('script'); s.type = 'application/javascript';

// path to the desired file s.src = 'http://code.jquery.com/jquery-1.6.2.js'; document.body.appendChild(s);</lang> Most be noted that it can also request HTTP source and eval() the source

With jQuery

Library: jQuery

<lang javascript>$.getScript("http://example.com/script.js");</lang>

LabVIEW

In LabVIEW, any VI can be used as a "SubVI" by changing the icon and wiring the terminals to the front panel. This cannot be explained concisely in code; instead, see the documentation.

Lua

To include a header file myheader.lua:

<lang lua> require "myheader" </lang>

m4

<lang m4>include(filename)</lang>

Maple

For textual inclusion, analogous to the C preprocessor, use the "$include" preprocessor directive. (The preprocessor is not a separate program, however.) This is frequently useful for large project development. <lang Maple>$include <somefile></lang> Or <lang Maple>$include "somefile"</lang> It is also possible to read a file, using the "read" statement. This has rather different semantics. <lang Maple>read "somefile":</lang>

Mathematica

<lang Mathematica> Get["myfile.m"] </lang>

Matlab / Octave

Matlab and Octave look for functions in *.m and *.mex included in the "path". New functions can be included, either by storing a new function in an existing path, or by extending the existing path to a new directory. When two functions have the same name, the function found first in the path takes precedence. The later is shown here:

<lang MATLAB>

 % add a new directory at the end of the path
 path(path,newdir);  
 addpath(newdir,'-end');  % same as before
 % add a new directory at the beginning
 addpath(newdir);
 path(newdir,path);       % same as before

</lang>

Maxima

<lang maxima>load("c:/.../source.mac")$

/* or if source.mac is in Maxima search path (see ??file_search_maxima), simply */ load(source)$</lang>

Modula-2

<lang modula2>IMPORT InOut, NumConv, Strings;</lang>

Nemerle

To include classes, static methods etc. from other namespaces, include those namespaces with the using keyword <lang Nemerle>using System.Console;</lang> using is for accessing code that has already been compiled into libraries. Nemerle also allows for creating partial classes (and structs), the source code of which may be split amongst several files as long as the class is marked as partial in each place that part of it is defined. An interesting feature of partial classes in Nemerle is that some parts of partial classes may be written in C# while others are written in Nemerle. <lang Nemerle>public partial class Foo : Bar // all parts of a partial class must have same access modifier; { // the class that a partial class inherits from only needs to ... // be specified in one location }</lang>

OCaml

In script mode and in the interactive loop (the toplevel) we can use: <lang ocaml>#use "some_file.ml"</lang>

In compile mode (compiled to bytecode or compiled to native code) we can use: <lang ocaml>include Name_of_a_module</lang>

ooRexx

ooRexx has a package system and no ability for textual inclusion of other text files. Importing of other packages is done via the ::requires directive. <lang ooRexx>

 ::requires "regex.cls"

</lang>

OpenEdge/Progress

Curly braces indicate that a file should be included. The file is searched across all PROPATH directory entries. <lang progress>{file.i}</lang>

Arguments can be passed to the file being included:

<lang progress>{file.i super}</lang>

Openscad

<lang openscad>//Include and run the file foo.scad include <foo.scad>;

//Import modules and functions, but do not execute use <bar.scad>;</lang>

PARI/GP

Files can be loaded in GP with the read, or directly in gp with the metacommand \r.

PARI can use the standard C #include, but note that if using gp2c the embedded GP; commands must be in the original file.

Pascal

See Delphi

Perl

Here we include the file include.pl into our main program:

main.perl:

<lang perl>#!/usr/bin/perl do "include.pl"; # Utilize source from another file sayhello();</lang>

include.pl: <lang perl>sub sayhello {

 print "Hello World!";

}</lang>

From documentation:

If "do" cannot read the file, it returns undef and sets $! to the error.
If "do" can read the file but cannot compile it, it returns undef and sets
an error message in $@.
If the file is successfully compiled, "do" returns the value of the last
expression evaluated.

Perl 6

Perl 6 provides a module system that is based primarily on importation of symbols rather than on inclusion of textual code: <lang perl6>use MyModule;</lang> However, one can evaluate code from a file: <lang perl6>require 'myfile.p6';</lang> One can even do that at compile time: <lang perl6>BEGIN require 'myfile.p6'</lang> None of these are true inclusion, unless the require cheats and modifies the current input string of the parser. To get a true textual inclusion, one could define an unhygienic textual macro like this: <lang perl6>macro include(AST $file) { slurp $file.eval } include('myfile.p6');</lang>

PHP

There are different ways to do this in PHP. You can use a basic include: <lang PHP>include("file.php")</lang> You can be safe about it and make sure it's not included more than once: <lang PHP>include_once("file.php")</lang> You can crash the code at this point if the include fails for any reason by using require: <lang PHP>require("file.php")</lang> And you can use the require statement, with the safe _once method: <lang PHP>require_once("file.php")</lang>

PicoLisp

The function 'load' is used for recursively executing the contents of files. <lang PicoLisp>(load "file1.l" "file2.l" "file3.l")</lang>

PL/I

<lang pli>%include myfile;</lang>

PowerBASIC

Note that PowerBASIC has the optional modifier ONCE which is meant to insure that no matter how many times the file may be included in code, it will only be inserted by the compiler once (the first time the compiler is told to include that particular file).

Note also that #INCLUDE and $INCLUDE function identically.

<lang powerbasic>#INCLUDE "Win32API.inc"

  1. INCLUDE ONCE "Win32API.inc"</lang>

Prolog

<lang Prolog>consult('filename').</lang>

PureBasic

IncludeFile will include the named source file at the current place in the code. <lang PureBasic>IncludeFile "Filename"</lang> XIncludeFile is exactly the same except it avoids including the same file several times. <lang PureBasic>XIncludeFile "Filename"</lang>

IncludeBinary will include a named file of any type at the current place in the code. IncludeBinary don't have to, but should preferably be done inside a data block. <lang PureBasic>IncludeBinary "Filename"</lang>

Python

Python supports the use of execfile to allow code from arbitrary files to be executed from a program (without using its modules system).

<lang Python>import mymodule</lang>

includes the content of mymodule.py

Names in this module can be accessed as attributes:

<lang Python>mymodule.variable</lang>

R

<lang R>source("filename.R")</lang>

Racket

Including files is usually discouraged in favor of using modules, but it is still possible:

<lang racket>

  1. lang racket

(include "other-file.rkt") </lang>

Retro

<lang Retro>include filename.ext</lang>

REXX

The REXX language does not include any directives to include source code from other files. A workaround is to use a preprocessor that take the source and the included modules and builds a temporary file containing all the necessary code, which then gets run by the interpreter.

Some variants of REXX may provide implementation specific solutions.

RPG

Works with: ILE RPG

<lang rpg> // fully qualified syntax:

     /include library/file,member
     // most sensible; file found on *libl:
     /include file,member
     // shortest one, the same library and file:
     /include member
     
     // and alternative:
     /copy library/file,member
     //... farther like "include"</lang>

Ruby

Note that in Ruby, you don't use the file extension. .rb is assumed. <lang Ruby>require 'file'</lang>

Run BASIC

You don't use the file extension. .bas is assumed. <lang runbasic>run SomeProgram.bas",#include ' this gives it a handle of #include render #include ' render will RUN the program with handle #include</lang>

Seed7

The Seed7 language is defined in the include file seed7_05.s7i. Therefore seed7_05.s7i must be included before other language features can be used (only comments can be used before). The first include directive (the one which includes seed7_05.s7i) is special and it must be introduced with the $ character. <lang seed7>$ include "seed7_05.s7i";</lang> All following include directives don't need a $ to introduce them. <lang seed7> include "float.s7i";</lang>

Smalltalk

there is no such thing as source-file inclusion in Smalltalk. However, in a REPL or anywhere in code, source code can be loaded with: <lang smalltalk>aFilename asFilename readStream fileIn</lang> or: <lang smalltalk>Smalltalk fileIn: aFilename</lang> In Smalltalk/X, which supports binary code loading, aFilename may either be sourcecode or a dll containing a precompiled class library.

Tcl

The built-in source command does exactly inclusion of code into the currently executing scope, subject to minor requirements of being well-formed Tcl script that is sourced in the first place (and the ability to introspect via info script): <lang tcl>source "foobar.tcl"</lang>

Note that it is more usually considered good practice to arrange code into packages that can be loaded in with more regular semantics (including version handling, only-once semantics, integration of code written in other languages such as C, etc.) <lang tcl>package require foobar 1.3</lang> In the case of packages that are implemented using Tcl code, these will actually be incorporated into the program using the source command, though this is formally an implementation detail of those packages.

UNIX Shell

With Bourne-compatible shells, the dot operator includes another file.

Works with: Bourne Shell

<lang bash>. myfile.sh # Include the contents of myfile.sh </lang>

C Shell

<lang csh>source myfile.csh</lang>

Vala

Importing/including is done during compilation. For example, to compile the program called "maps.vala" with the package "gee":

valac maps.vala --pkg gee-1.0

Functions can be called then using Gee.<function> calls: <lang vala> var map = new Gee.HashMap<string, int> (); </lang>

or with a using statement: <lang vala> using Gee;

var map = new HashMap<string, int>(); </lang>

x86 Assembly

Works with: FASM on Windows

<lang asm>include 'MyFile.INC'</lang>

Works with: nasm

<lang asm>%include "MyFile.INC"</lang>

XPL0

<lang XPL0>include c:\cxpl\stdlib; DateOut(0, GetDate)</lang>

Example output:

09-28-12

ZX Spectrum Basic

It is possible to include the contents of another program using the merge command. However, line numbers that coincide with those of the original program shall be overwritten, so it is best to reserve a block of line numbers for merged code:

<lang zxbasic>10 GO TO 9950 5000 REM We reserve line numbers 5000 to 8999 for merged code 9000 STOP: REM In case our line numbers are wrong 9950 REM Merge in our module 9955 MERGE "MODULE" 9960 REM Jump to the merged code. Pray it has the right line numbers! 9965 GO TO 5000 </lang>