Include a file: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 1,283: Line 1,283:
{{omit from|GUISS}}
{{omit from|GUISS}}
{{omit from|NetRexx}}
{{omit from|NetRexx}}
{{omit from|VBA}}
{{omit from|Visual Basic}}


[[Category:Basic language learning]]
[[Category:Basic language learning]]

Revision as of 17:54, 15 March 2019

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

Demonstrate the language's ability to include source code from other files.

360 Assembly

The COPY instruction includes source statements from the SYSLIB library. <lang 360asm> COPY member</lang>

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

Some remarks are necessary here. Ada does not define how the source code is stored in files. The language rather talks about compilation units. A compilation unit "imports" another compilation unit by using context clauses - these have the syntax "with CU1, CU2, ...;". All compilers I know of require in their standard mode exactly one compilation unit per file; also file naming conventions vary. However GNAT e.g. has a mode that can deal with files holding several compilation units and any file name conventions. <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>

ALGOL 68

The formal definition of Algol68 make numerous references to the standard prelude and postlude.

At the time the language was formally defined it was typical for code to be stored on decks of punched cards (or paper tape). Possibly because storing code on disk (or drum) was expensive. Similarly card decks can be read sequentially from just one card reader. It appears the Algol68 "standard" assumed all cards could be simply stacked before and after the actual source code, hence the references "prelude" and "postlude" in the formal standard.

ALGOL 68G

In the simplest case a file can be included as follows: <lang algol68>PR read "file.a68" PR</lang>

But in the Algol68 formal reports - it appears - the intention was to have a more structure approach.

Works with: ALGOL 68 version Revision 1 - one extension to language used - PRAGMA READ - a non standard feature similar to C's #include directive.
Works with: ALGOL 68G version Any - tested with release algol68g-2.7.

File: prelude/test.a68<lang algol68># -*- coding: utf-8 -*- # BEGIN

  1. Exception setup code: #
 on value error(stand out, (REF FILE f)BOOL: GOTO value error not mended);
  1. Block setup code: #
 printf(($"Prelude test:"l$))</lang>File: postlude/test.a68<lang algol68># -*- coding: utf-8 -*- #
  1. Block teardown code: #
 printf(($"Postlude test."l$))

EXIT

  1. Exception code: #
 value error not mended: SKIP

END</lang>File: test/include.a68<lang algol68>#!/usr/bin/a68g --script #

  1. -*- coding: utf-8 -*- #

PR read "prelude/test.a68" PR; printf($4x"Hello, world!"l$); PR read "postlude/test.a68" PR</lang>

Output:
Prelude test:
    Hello, world!
Postlude test.

Other implementations: e.g. ALGOL 68RS and ALGOL 68G
Note that actual source code inclusion with parsing can be avoided because of a more generalised separate compilation method storing declaration specifications in a data dictionary. Different to #include found in C where the include file needs to be parsed for each source file that includes it.

ALGOL 68RS

This British implementation of the language has various ways to include it's own source code and and integrate with code compiled from other languages.

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d.

In order to support a top-down programming style ALGOL 68RS provided the here and context facilities.

A program could be written with parts to be filled in later marked by a here tag followed by a keeplist of declarations to be made available.

program (pass1, pass2) compiler
begin
   string source := ...;
   tree parsetree;
...
   here pass1 (source, parsetree);
...
   instructions insts;
   here pass2 (parsetree, insts);
...
end
finish

The code to be executed in the context of the here tags would be written as:

program pass1 implementation
context pass1 in compiler
begin
  ...   { code using "source" and "parsetree" }
end
finish

here is similar to the ALGOL 68C environ and context is equivalent to the ALGOL 68C using.

ALGOL 68C

Separate compilation in ALGOL 68C is done using the ENVIRON and USING clauses. The ENVIRON saves the complete environment at the point it appears. A separate module written starting with a USING clause is effectively inserted into the first module at the point the ENVIRON clause appears.

Example of ENVIRON clause
A file called mylib.a68: <lang algol68>BEGIN

  INT dim = 3; # a constant #
  INT a number := 120; # a variable #
  ENVIRON EXAMPLE1;
  MODE MATRIX = [dim, dim]REAL; # a type definition #
  MATRIX m1;
  a number := ENVIRON EXAMPLE2;
  print((a number))

END</lang>

Example of USING clause
A file called usemylib.a68: <lang algol68>USING EXAMPLE2 FROM "mylib" BEGIN

 MATRIX m2; # example only #
 print((a number)); # declared in mylib.a68 #
 print((2 UPB m1)); # also declared in mylib.a68 #
 ENVIRON EXAMPLE3;  # ENVIRONs can be nested #
 666

END</lang>

AntLang

AntLang is made for interactive programming, but a way to load files exists. Even if it is really primitive, i. e. file get's current environment and manipulates it. <lang AntLang>load["script.ant"]</lang>

Applesoft BASIC

Chain PROGRAM TWO to PROGRAM ONE. First create and save PROGRAM TWO. Then, create PROGRAM ONE and run it. PROGRAM ONE runs and then "includes" PROGRAM TWO which is loaded and run using the Binary program CHAIN from the DOS 3.3 System Master. Variables from PROGRAM ONE are not cleared so they can be used in PROGRAM TWO. User defined functions should be redefined in PROGRAM TWO. See "Applesoft: CHAIN and user-defined functions Issues" http://support.apple.com/kb/TA41069

<lang ApplesoftBASIC}> 10 REMPROGRAM TWO

20  DEF  FN A(X) = X * Y
30  PRINT  FN A(2)

SAVE PROGRAM TWO</lang> <lang ApplesoftBASIC}> 10 REMPROGRAM ONE

20 Y = 6
30  DEF  FN A(X) = X * Y
40  PRINT  FN A(2)
50 D$ =  CHR$ (4)
60  PRINT D$"BLOADCHAIN,A520"
70  CALL 520"PROGRAM TWO"

SAVE PROGRAM ONE RUN</lang>

Output:
12

12

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
Works with: Gawk

GNU Awk has an @include which can include another awk source file at that point in the code.

<lang awk>@include "filename.awk"</lang>

This is a parser-level construct and so must be a literal filename, not a variable or expression. If the filename is not absolute then it's sought in an $AWKPATH list of directories. See the gawk manual for more.

Axe

This will cause the program called OTHER to be parsed as if it was contained in the source code instead of this line. <lang axe>prgmOTHER</lang>

BaCon

other.bac <lang freebasic>other = 42</lang> including.bac <lang freebasic>' Include a file INCLUDE "other.bac" PRINT other</lang>

Output:
prompt$ bacon including.bac
Converting 'including.bac'... done, 4 lines were processed in 0.005 seconds.
Compiling 'including.bac'... cc  -c including.bac.c
cc -o including including.bac.o -lbacon -lm
Done, program 'including' ready.
prompt$ ./including
42

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

Batch File

<lang dos> call file2.bat </lang>

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>

ChucK

<lang>Machine.add(me.dir() + "/MyOwnClassesDefinitions.ck");</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 and other library header names are enclosed between chevrons */

  1. include <stdlib.h>

/* User/in-project header names are usually enclosed between double-quotes */

  1. include "myutil.h"</lang>

Although it is often conventional and idiomatic for a project to use its own headers in the style described on the second line above, it's also possible to tell most compilers using various flags (e. g. GCC and Clang accept -I) to treat an arbitrary directory as a system/library include folder, thereby allowing any contained files to be included using the angle bracket syntax.

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>

Clipper

The 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 clipper> #include "inkey.ch" </lang>

Clojure

Just as in Common Lisp: <lang clojure>(load "path/to/file")</lang>

This would rarely be used for loading code though, since Clojure supports modularisation (like most modern languages) through namespaces and code is typically located/loaded via related abstractions. It's probably more often used to load data or used for quick-and-dirty experiments in the REPL.

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>

Common Lisp

<lang lisp>(load "path/to/file")</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>

Déjà Vu

<lang dejavu>#with the module system: !import!foo

  1. passing a file name (only works with compiled bytecode files):

!run-file "/path/file.vu"</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>

Emacs Lisp

Write this code in: file1.el <lang Emacs Lisp> (defun sum (ls)

 (apply '+ ls) )

</lang> In the directory of file1.el, we write this new code in: file2.el <lang Emacs Lisp> (add-to-list 'load-path "./") (load "./file1.el") (insert (format "%d" (sum (number-sequence 1 100) ))) </lang> Output:

5050

Erlang

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

Euphoria

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

Factor

<lang Factor> USING: vocaba vocabb... ; </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).

Included content may itself involve further inclusions but should not start with any attempt at the continuation of a statement preceding the include line nor should there be any attempt at the line following the include being a continuation of whatever had been included. It is not considered to be a statement (and so should not have a statement label) in Fortran itself but something a Fortran compiler might recognise, however a trailing comment on that line may be accepted. The exact form (if supported at all) depends on the system and its file naming conventions, especially with regard to spaces in a file name. The file name might be completely specified, or, relative as in INCLUDE "../Fortran/Library/InOutCom.for" Further, Fortran allows text strings to be delimited by apostrophes as well as by quotes and there may be different behaviour for the two sorts, if recognised. For instance, the relative naming might be with reference to the initial file being compiled, or, with reference to the directory position of the file currently being compiled - it being the source of the current include line - as where file InOutCom.for contained an inclusion line specifying another file in the same library collection.

Different compilers behave differently, and standardisation attempts have not reached back to earlier compilers.

FreeBASIC

File to be included : <lang freebasic>' person.bi file Type Person

 name As String
 age As UInteger
 Declare Operator Cast() As String

End Type

Operator Person.Cast() As String

 Return "[" + This.name + ", " + Str(This.age) + "]"

End Operator</lang>

Main file : <lang freebasic>' FB 1.05.0 Win 64

' main.bas file

  1. include "person.bi"

Dim person1 As Person person1.name = "Methuselah" person1.age = 969 Print person1 Print Print "Press any key to quit" Sleep</lang>

Output:
[Methuselah, 969]

Furryscript

Use a word with a slash at the end to import; how the file is found is based on the implementation (normally the "furinc" directory is looked at for include files).

The file is imported into a new namespace. Use the same name at the beginning and a slash, but now include something else afterward, and now means that name inside of that namespace.

FutureBasic

FB has powerful tools to include files in a project. Its "include resources" statement allows you to specify any number of files for copying into the built application package's Contents/Resources/ directory. <lang futurebasic> include resources "SomeImage.png" include resources "SomeMovie.mpeg" include resources "SomeSound.aiff" include resources "SomeIcon.icns" include resources "Info.plist" //Custom preference file to replace FB's generic app preferences </lang> Including C or Objective-C headers (i.e. files with the .h extension) or source files (files with the .c or .m extension) requires a different 'include' syntax:

include "HeaderName.h"  // do not use 'include resources' to include C/Objective-C headers
include "CSourceFile.c"
include "ObjectiveCImplementationFile.m"

Another special case are Objective-C .nib or .xib files. These are loaded with:

include resources "main.nib"

However, .nib files are copied to the built application's Contents/Resources/en.lproj/ directory.


Mac OS X frameworks may be specified with the 'include library' statement, which has two forms:

include library "Framework/Header.h"
include library "Framework" // optional short form, expanded internally to: include library "Framework/Framework.h"

After including a Framework, you must notify the compiler of specific functions in the Framework that your code will be using with FB's "toolbox fn" statement as shown in this example:

include library "AddressBook/AddressBookUI.h"
// tell FBtoC the functions
toolbox fn ABPickerCreate() = ABPickerRef

Special treatment for C static libraries (*.a): The include statement copies the library file to the build_temp folder; you must also place the name of the library file in the preferences 'More compiler options' field [this causes it to be linked]. The example below is for a library MyLib that exports one symbol (MyLibFunction).

include "MyLib.a"
BeginCDeclaration
// let the compiler know about the function
void MyLibFunction( void ); // in lieu of .h file
EndC
// let FBtoC know about the function
toolbox MyLibFunction()
MyLibFunction() // call the function

An include file can also contain executable source code. Example: Suppose we create a file "Assign.incl" which contains the following lines of text:

dim as long a, b, c

a = 3
b = 7

Now suppose we write a program like this:

include "Assign.incl"
c = a + b
print c

When we compile this program, the result will be identical to this:

dim as long a, b, c
a = 3
b = 7
c = a + b
print c

Other include cases are detailed in FB's Help Center.

Gambas

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

Gambas

Here a file is loaded into a variable <lang gambas>Public Sub Form_Open() Dim sFile As String

sFile = File.Load("FileToLoad")

End </lang>

GAP

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

Gnuplot

<lang gnuplot>load "filename.gnuplot"</lang>

This is the same as done for each file named on the command line. Special filename "-" reads from standard input.

<lang gnuplot>load "-" # read standard input</lang>

If the system has popen then piped output from another program can be loaded,

<lang gnuplot>load "< myprogram" # run myprogram, read its output load "< echo print 123"</lang>

call is the same as load but takes parameters which are then available to the sub-script as $0 through $9

<lang gnuplot>call "filename.gnuplot" 123 456 "arg3"</lang>

Harbour

The 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 visualfoxpro>#include "inkey.ch"</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

Pure JavaScript in browsers with the DOM

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>

With AMD (require.js)

<lang javascript>require(["jquery"], function($) { /* ... */ });</lang>

CommonJS style with node.js (or browserify)

Library: node.js

<lang javascript>var $ = require('$');</lang>

ES6 Modules

<lang javascript>import $ from "jquery";</lang>

jq

Works with: jq version with "include"

jq 1.5 has two directives for including library files, "include" and "import". A library file here means one that contains jq function definitions, comments, and/or directives.

The main difference between the two types of directive is that included files are in effect textually included at the point of inclusion, whereas imported files are imported into the namespace specified by the "import" directive. The "import" directive can also be used to import data.

Here we illustrate the "include" directive on the assumption that there are two files:

Include_a_file.jq <lang jq>include "gort";

hello</lang>

gort.jq <lang>def hello: "Klaatu barada nikto";</lang>

Output:

<lang sh>$ jq -n -c -f Include_a_file.jq Klaatu barada nikto.</lang>

Julia

Julia's include function executes code from an arbitrary file: <lang Julia>include("foo.jl")</lang> or alternatively include_string executes code in a string as if it were a file (and can optionally accept a filename to use in error messages etcetera).

Julia also has a module system: <lang Julia>import MyModule</lang> imports the content of the module MyModule.jl (which should be of the form module MyModule ... end, whose symbols can be accessed as MyModule.variable, or alternatively <lang Julia>using MyModule</lang> will import the module and all of its exported symbols

Kotlin

The closest thing Kotlin has to an #include directive is its import directive. This doesn't import source code as such but makes available names defined in another accessible package as if such names were defined in the current file i.e. the names do not need to be fully qualified except to resolve a name clash.

Either a single name or all accessible names in a particular scope (package, class, object etc.) can be imported.

For example: <lang scala>fun f() = println("f called")</lang>

We can now import and invoke this from code in the default package as follows:

<lang scala>// version 1.1.2

import package1.f // import f from package `package1`

fun main(args: Array<String>) {

   f()  // invoke f without qualification

}</lang>

Output:
f called

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.

LabVIEW

<lang Lasso>web_response -> include('my_file.inc')</lang>

Lasso

<lang Lasso>include('myfile.lasso')</lang>

Lingo

<lang lingo>-- load Lingo code from file fp = xtra("fileIO").new() fp.openFile(_movie.path&"someinclude.ls", 1) code = fp.readFile() fp.closeFile()

-- create new script member, assign loaded code m = new(#script) m.name = "someinclude" m.scriptText = code

-- use it instantly in the current script (i.e. the script that contained the above include code) script("someinclude").foo()</lang>

Logtalk

<lang logtalk>

- object(foo).
   :- include(bar).
- end_object.

</lang>

Lua

To include a header file myheader.lua:

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

M2000 Interpreter

Without use of New in Load we get any cached file with same name. Using load from M2000 command line we always load file, but from code interpreter use a cache to hold it for next load. <lang M2000 Interpreter> Document A$={ Module Global Beta {

     Print "This is Beta"
     x=10
     Print x
     }
     Print "This is statement to execute"
     Beta  ' this call not happen

} Save.Doc A$, "TestThis.Gsb" Module checkit {

     \\ we can delete Global
     \\ usinf New Modules we get latest TestThis, excluding statements calling modules.
     Load New Modules TestThis
     \\ check if Beta exist
     Print Module(Beta)=True
     \\ so now we call Beta
     Beta
     Print Valid(x)=False ' x is local to beta

} Checkit \\ now Beta erased (after return form Checkit) Print Module(Beta)=False </lang>

Running code of a module, as code is inline and not in that module. Now X is a variable in CheckIt <lang M2000 Interpreter> \\ we can delete global Module Global alfa {

     Print "this is alfa"
     X=10

} Module Checkit {

     Inline Code alfa
     Print X=10

} Checkit </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 / Wolfram Language

<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>

Modula-3

<lang modula3>IMPORT IO, Text AS Str; FROM Str IMPORT T</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>

NewLISP

<lang NewLISP>;; local file (load "file.lsp")

URLs (both http
// and file
// URLs are supported)

(load "http://www.newlisp.org/code/modules/ftp.lsp")</lang>

Nim

After import someModule an exported symbol x can be accessed as x and as someModule.x. <lang nim>import someModule import strutils except parseInt import strutils as su, sequtils as qu # su.x works import lib.pure.strutils, lib/pure/os, "lib/pure/times" # still strutils.x</lang>

OASYS Assembler

Use an equal sign at the beginning of a line to include a file: =util.inc

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>

Oforth

In order to load a file with name filename : <lang Oforth>"filename" load</lang>

In order to load a package with name pack : <lang Oforth>import: pack</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>

Phix

<lang Phix>include arwen.ew</lang> Phix also supports relative directory includes, for instance if you include "..\demo\arwen\arwen.ew" then anything that arwen.ew includes will be looked for in the appropriate directory.

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>

PowerShell

<lang PowerShell> <#

   A module is a set of related Windows PowerShell functionalities, grouped together as a convenient unit (usually saved in a
   single directory). By defining a set of related script files, assemblies, and related resources as a module, you can
   reference, load, persist, and share your code much easier than you would otherwise.
  1. >

Import-Module -Name MyModule


<#

   When you dot source a script (or scriptblock), all variables and functions defined in the script (or scriptblock) will
   persist in the shell when the script ends.
  1. >

. .\MyFunctions.ps1 </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>

RapidQ

<lang vb> $INCLUDE "RAPIDQ.INC" </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.

The REXX Compiler for CMS and TSO supports a directive to include program text before compiling the program <lang rexx>/*%INCLUDE member */</lang>

Including a file at time of execution

On the other hand, since REXX is a dynamic language, you can (mis)use some file IO and the INTERPRET statement to include another source file:

Works with: ARexx

<lang rexx> /* Include a file and INTERPRET it; this code uses ARexx file IO BIFs */ say 'This is a program running.' if Open(other,'SYS:Rexxc/otherprogram.rexx','READ') then do

  say "Now we opened a file with another chunk of code. Let's read it into a variable."
  othercode=
  do until EOF(other)
     othercode=othercode || ReadLn(other) || ';'
     end
  call Close(other)
  say 'Now we run it as part of our program.'
  interpret othercode
  end

say 'The usual program resumes here.' exit 0 </lang> Note:   due to the way most REXX interpreters work, functions and jumps (SIGNALs) inside an INTERPRETED program won't work.   Neither are   labels   recognized, which would then exclude the use of those subroutines/functions.

There are also other restrictions such as multi-line statements and comments (more than one line).

Another possibility of errors is the creation of an extremely long value which may exceed the limit for a particular REXX interpreter.

Calling an external program

Usually, including a file in another is not necessary with REXX, since any script can be called as a function:

Program1.rexx <lang rexx> /* This is program 1 */ say 'This is program 1 writing on standard output.' call Program2 say 'Thank you, program 1 is now ending.' exit 0 </lang> Program2.rexx <lang rexx> /* This is program 2 */ say 'This is program 2 writing on standard output.' say 'We now return to the caller.' return </lang> If a REXX interpreter finds a function call, it first looks in the current program for a function or procedure by that name, then it looks in the standard function library (so you may replace the standard functions with your own versions inside a program), then it looks for a program by the same name in the standard paths. This means that including a file in your program is usually not necessary, unless you want them to share global variables.

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>

Ring

<lang Ring>Load 'file.ring'</lang>

Ruby

Note that in Ruby, you don't use the file extension. Ruby will first check for a Ruby (.rb) file of the specified name and load it as a source file. If an .rb file is not found it will search for files in .so, .o, .dll or other shared-library formats and load them as Ruby extension. require will search in a series of pre-determined folders, while require_relative behaves the same way but searches in the current folder, or another specified folder.

<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>

Rust

The compiler will include either a 'test.rs' or a 'test/mod.rs' (if the first one doesn't exist) file. <lang rust>mod test

fn main() {

   test::some_function();

}</lang>

Additionally, third-party libraries (called crates in rust) can be declared thusly: <lang rust>extern crate foo; fn main() {

   foo::some_function();

}</lang>

Scala

Some remarks are necessary here. Scala does not define how the source code is stored in files. The language rather talks about compilation units.

In a Scala REPL[1] it's possible to save and load source code.

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. The float.s7i library can be included with: <lang seed7> include "float.s7i";</lang>

Sidef

Include a file in the current namespace: <lang ruby>include 'file.sf';</lang>

Include a file as module (file must exists in SIDEF_INC as Some/Name.sm): <lang ruby>include Some::Name;

  1. variables are available here as: Some::Name::var_name</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.

SNOBOL4

Works with: SNOBOL4
Works with: Spitbol

<lang SNOBOL4>-INCLUDE "path/to/filename.inc"</lang>

SPL

<lang spl>$include.txt</lang>

Standard ML

Works with: SML/NJ

<lang sml>use "path/to/file";</lang>

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>

Bash

<lang shell>. myfile.sh source myfile.sh</lang>

GNU Bash has both . and the C-Shell style source. See Bash manual on source

Ursa

Ursa can read in and execute another file using the import statement, similar to Python. <lang ursa>import "filename.u"</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>

VBScript

VBScript doesn't come with an explicit include (unless you use the wsf form). Fortunately vbscript has the Execute and ExecuteGlobal commands which allow you to add code dynamically into the local (disappears when the code goes out of scope) or global namespaces. Thus, all you have to do to include code from a file is read the file into memory and ExecuteGlobal on that code. Just pass the filename to this sub and all is golden. If you want an error to occur if the file is not found then just remove the FileExists test.

<lang vb> Include "D:\include\pad.vbs"

Wscript.Echo lpad(12,14,"-")

Sub Include (file)

  dim fso: set fso = CreateObject("Scripting.FileSystemObject")
  if fso.FileExists(file) then ExecuteGlobal fso.OpenTextFile(file).ReadAll

End Sub </lang> If you use the wsf form you can include a file by <lang vbscript> <script id="Connections" language="VBScript" src="D:\include\ConnectionStrings.vbs"/>

</lang>

If you use the following form then you can define an environment variable, %INCLUDE% and make your include library more portable as in

<lang vbscript> Include "%INCLUDE%\StrFuncs.vbs"

Function Include ( ByVal file )

   Dim wso: Set wso = CreateObject("Wscript.Shell")
   Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
   ExecuteGlobal(fso.OpenTextFile(wso.ExpandEnvironmentStrings(file)).ReadAll)

End Function </lang>

Verbexx

<lang verbexx>/*******************************************************************************

  • /# @INCLUDE file:"filename.filetype"
  • - file: is just the filename
  • - actual full pathname is VERBEXX_INCLUDE_PATH\filename.filetype
  • where VERBEXX_INCLUDE_PATH is the contents of an environment variable
  • /# @INCLUDE file:"E:\xxx\xxx\xxx\filename.filetype"
  • - file: specifies the complete pathname of file to include
  • @INCLUDE verb can appear only in pre-processor code (after /# /{ etc.)
                                                                                                                                                              • /

/{ //////////////////////////////////////////////// start of pre-processor code

   @IF (@IS_VAR include_counter) 
       else:{@VAR include_counter global: = 0};  // global, so all code sees it
   include_counter++; 
   @SAY "    In pre-processor -- include counter = " include_counter; 
  
   @IF (include_counter < 3) 
       then:{@INCLUDE file:"rosetta\include_a_file.txt"};     // include self

}/ ////////////////////////////////////////////////// end of pre-processor code

@SAY "Not in pre-processor -- include_counter = " include_counter; /] Output: In preprocessor -- include_counter = 1

            In preprocessor -- include_counter = 2
            In preprocessor -- include_counter = 3 
        Not in preprocessor -- include_counter = 3 
        Not in preprocessor -- include_counter = 3
        Not in preprocessor -- include_counter = 3</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>

Output:
09-28-12

zkl

<lang zkl>include(vm.h.zkl, compiler.h.zkl, zkl.h.zkl, opcode.h.zkl);</lang>

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>