Include a file

From Rosetta Code
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.

See Also




360 Assembly

The COPY instruction includes source statements from the SYSLIB library.

         COPY  member

6502 Assembly

There are two different directives for including files: include and incbin. include is for assembly code that will be converted to machine code that the computer can run. incbin is for binary data such as graphics, which the assembler will convert as-is to binary and does not attempt to translate it into machine code.

For this example, the file "foo.txt" is a file containing only the following: RTS

;main.asm
org $8000
include "foo.txt"
;eof

A hexdump of the resulting machine code would look like this:

HEXDUMP OF 
$8000: 60 00 00 00 00 00 00 00 `.......

Now compare it to the following:

;main.asm
org $8000
incbin "foo.txt"
;eof
HEXDUMP OF 
$8000:  52 54 53 00 00 00 00 00 RTS.....

As you can see, when incbin was used the assembler made no attempt to translate the assembly mnemonic into machine instructions. While anything that incbin can do, include can do also, using data blocks, it is often much easier to use incbin if you have a separate graphics creation program that can output graphics data into a raw binary form. Graphics data often contains hundreds of redundant bytes which can be very painful and time-consuming to type by hand.

Unlike high-level languages, the location of the include or incbin statement matters. This of course depends on the assembler, but generally speaking, there are a few limitations:

  • If you include a macro after that macro is used in your source code, the assembler may raise an error message. If your macros are always before your code this isn't a problem.
  • When you include or incbin a file, unless your assembler has linker support, the assembler treats the include statement as though you copied and pasted the entire contents of that file at the location in your document where the include/incbin statement is.
  • include/incbin statements can be nested, i.e. an included file can contain its own included files, but there is a limit with how deep you can go. Nesting includes is never actually required, as the example below demonstrates:
;main.asm
include "Subroutines.asm"
;eof

;Subroutines.asm
include "math.asm"
;eof

;math.asm
;eof

The above is assembled identically to:

;main.asm
include "Subroutines.asm"
include "math.asm"
;eof

68000 Assembly

Translation of: 6502 Assembly

There are two different directives for including files: include and incbin. include is for assembly code that will be converted to machine code that the computer can run. incbin is for binary data such as graphics, which the assembler will convert as-is to binary and does not attempt to translate it into machine code.

Unless you're using a linker to arrange your various files into an executable, the location of your include and incbin directives imply the memory location of the code or data you're including. For example:

org $00000000
;512 bytes containing anything really
include "myFile.asm"  ;assuming no org or align directives are in this file, 
                      ;its starting memory location is guaranteed to be $00000200 (512 in decimal)

This can become a problem if you have data that is not intended to be executed directly after a block of code, with nothing preventing "fallthrough." For example:

foo:
LEA myData,A0
MOVE.W (A0)+,D0

MyData:
include "dataTables.inc" ;a list of defined data constants that aren't supposed to be executed as instructions

Since there was no control flow instruction stopping the program counter from reaching the included file, the bytes stored in it will be executed as though they were genuine Motorola 68000 CPU instructions, even if they're not. The CPU cannot tell the difference between data and instructions, and thus the programmer must ensure that the program counter never reaches anything that wasn't meant to be executed. The easiest fix for this would be:

foo:
LEA myData,A0
MOVE.W (A0)+,D0
RTS ;return from subroutine, preventing the CPU from executing the data below.

MyData:
include "dataTables.inc" ;a list of defined data constants that aren't supposed to be executed as instructions

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
'file constant include : includeConstantesARM64.inc'
/*******************************************/
/* Constantes                              */
/*******************************************/
.equ STDIN,  0                // Linux input console
.equ STDOUT, 1                // linux output console
.equ OPEN,   56               // call system Linux 64 bits
.equ CLOSE,  57               // call system Linux 64 bits
.equ READ,   63               // call system Linux 64 bits 
.equ WRITE,  64               // call system Linux 64 bits 
.equ EXIT,   93               // call system Linux 64 bits 
.equ HEAPSIZE,   100000
.equ CHARPOS,       '@'       // position character

/*  file */
.equ O_RDONLY, 0
.equ O_WRONLY, 0x0001    
.equ O_RDWR,   0x0002          // open for reading and writing

.equ O_CREAT,  0x040           // create if nonexistant
.equ O_TRUNC,  0x0400          // truncate to zero length
.equ O_EXCL,   0x0800          // error if already exists 

.equ AT_FDCWD,    -100
'file fonctions include : includeARM64.inc'
/*   File include fonctions   */
.data
ptzZoneHeap:   .quad zZoneHeap
.bss
.align 8
zZoneHeap:              .skip HEAPSIZE
zEndZoneHeap:
.text
/******************************************************************/
/*     String display with  size compute                          */ 
/******************************************************************/
/* x0 contains string address (string ended with zero binary) */
affichageMess:
    stp x0,x1,[sp,-16]!        // save  registers
    stp x2,x8,[sp,-16]!        // save  registers
    mov x2,0                   // size counter
1:                             // loop start
    ldrb w1,[x0,x2]            // load a byte
    cbz w1,2f                  // if zero -> end string
    add x2,x2,#1               // else increment counter
    b 1b                       // and loop
2:                             // x2 =  string size
    mov x1,x0                  // string address
    mov x0,STDOUT              // output Linux standard
    mov x8,WRITE               // code call system "write"
    svc 0                      // call systeme Linux
    ldp x2,x8,[sp],16          // restaur  2 registres
    ldp x0,x1,[sp],16          // restaur  2 registres
    ret                        // retour adresse lr x30
/******************************************************************/
/*     Decimal conversion unsigned                             */ 
/******************************************************************/
/* x0 contains the value  */
/* x1 contains the address of receiving area  length >= 21 */
/* the receiving area return a string ascii left aligned */
/* and with final zero */
/* x0 return length string whitout zero final  */
.equ LGZONECONV,   20
conversion10:
    stp x5,lr,[sp,-16]!        // save  registers
    stp x3,x4,[sp,-16]!        // save  registers
    stp x1,x2,[sp,-16]!        // save  registers
    mov x4,#LGZONECONV         // position last digit
    mov x5,#10                 // decimal conversion
1:                             // loop begin
    mov x2,x0                  // copy starting number or successive quotients
    udiv x0,x2,x5              // division by ten
    msub x3,x0,x5,x2           //compute remainder
    add x3,x3,#48              // digit
    sub x4,x4,#1               // previous position
    strb w3,[x1,x4]            // store digit ascii
    cbnz x0,1b                 // end if quotient = zero
    mov x2,LGZONECONV          // compute string length (20 - dernière position)
    sub x0,x2,x4               // no instruction rsb in 64 bits !!!
                               // move result to area begin
    cbz x4,3f                  // full area ?
    mov x2,0                   // start position
2:    
    ldrb w3,[x1,x4]            // load digit
    strb w3,[x1,x2]            // store digit
    add x4,x4,#1               // next position origin
    add x2,x2,#1               // and next position destination
    cmp x4,LGZONECONV - 1      // end ?
    ble 2b                     // else loop
3: 
    mov w3,0
    strb w3,[x1,x2]             // zero final
100:
    ldp x1,x2,[sp],16          // restaur des  2 registres
    ldp x3,x4,[sp],16          // restaur des  2 registres
    ldp x5,lr,[sp],16          // restaur des  2 registres
    ret                        // retour adresse lr x30
/******************************************************************/
/*     Decimal conversion signed                             */ 
/******************************************************************/
/* x0 contains the value  */
/* x1 contains the address of receiving area  length >= 21 */
/* the receiving area return a string ascii left aligned */
/* et avec un zero final */
/* x0 return length string whitout zero final  */
.equ LGZONECONVS,   21
conversion10S:
    stp x5,lr,[sp,-16]!        // save  registers
    stp x3,x4,[sp,-16]!        // save  registers
    stp x1,x2,[sp,-16]!        // save  registers
    cmp x0,0                   // is negative ?
    bge 11f                    // no 
    mov x3,'-'                 // yes
    neg x0,x0                  // number inversion 
    b 12f
11:
    mov x3,'+'                 // positive number
12:
    strb w3,[x1]
    mov x4,#LGZONECONVS         // position last digit
    mov x5,#10                 // decimal conversion 
1:                             // loop conversion start
    mov x2,x0                  // copy starting number or successive quotients
    udiv x0,x2,x5              // division by ten
    msub x3,x0,x5,x2           //compute remainder
    add x3,x3,#48              // conversion ascii
    sub x4,x4,#1               // previous position
    strb w3,[x1,x4]            // store digit
    cbnz x0,1b                 // end if quotient = zero

    mov x2,LGZONECONVS          // compute string length (21 - dernière position)
    sub x0,x2,x4               // no instruction rsb in 64 bits !!!
                               // move result to area begin
    cmp x4,1
    beq 3f                     // full area ?
    mov x2,1                   // no -> begin area 
2:    
    ldrb w3,[x1,x4]            // load a digit
    strb w3,[x1,x2]            // and store at begin area
    add x4,x4,#1               // last position
    add x2,x2,#1               // et begin last postion
    cmp x4,LGZONECONVS - 1      // end ?
    ble 2b                     // no -> loop 
3: 
    mov w3,0
    strb w3,[x1,x2]            // zero final
    add x0,x0,1                // string length must take into account the sign
100:
    ldp x1,x2,[sp],16          // restaur  2 registers
    ldp x3,x4,[sp],16          // restaur  2 registers
    ldp x5,lr,[sp],16          // restaur  2 registers
    ret                        // return address lr x30
/******************************************************************/
/*     conversion  hexadecimal register                           */ 
/******************************************************************/
/* x0 contains value and x1 address zone receptrice   */
conversion16:
    stp x0,lr,[sp,-48]!        // save  registres
    stp x1,x2,[sp,32]          // save  registres
    stp x3,x4,[sp,16]          // save  registres
    mov x2,#60                 // start bit position
    mov x4,#0xF000000000000000 // mask
    mov x3,x0                  // save entry value
1:                             // start loop
    and x0,x3,x4               // value register and mask
    lsr x0,x0,x2               // right shift
    cmp x0,#10                 // >= 10 ?
    bge 2f                     // yes
    add x0,x0,#48              // no is digit
    b 3f
2:
    add x0,x0,#55              // else is a letter A-F
3:
    strb w0,[x1],#1            // load result  and + 1 in address
    lsr x4,x4,#4               // shift mask 4 bits left
    subs x2,x2,#4              // decrement counter 4 bits <= zero  ?
    bge 1b                     // no -> loop

100:                           // fin standard de la fonction
    ldp x3,x4,[sp,16]          // restaur des  2 registres
    ldp x1,x2,[sp,32]          // restaur des  2 registres
    ldp x0,lr,[sp],48          // restaur des  2 registres
    ret    
/******************************************************************/
/*     conversion ascii string to number                          */ 
/******************************************************************/
/* x0 contains string address ended by 0x0 or 0xA */
/* x0 return the number  */ 
conversionAtoD:
    stp x5,lr,[sp,-16]!        // save  registers
    stp x3,x4,[sp,-16]!        // save  registers
    stp x1,x2,[sp,-16]!        // save  registers
    mov x1,#0
    mov x2,#10             // factor ten
    mov x4,x0              // save address in x4
    mov x3,#0              // positive signe by default
    mov x0,#0              // init résult to zéro
    mov x5,#0
1:                         // loop to remove space at begin of string
    ldrb w5,[x4],1         // load in w5 string octet 
    cbz w5,100f            // string end -> end routine
    cmp w5,#0x0A           // string end -> end routine
    beq 100f
    cmp w5,#' '            // space ?
    beq 1b                 // yes -> loop
2:
    cmp x5,#'-'            // first character is -
    bne 3f
    mov x3,#1              // negative number
    b 4f                   // previous position
3:                         // begin loop compute digit
    cmp x5,#'0'            // character not a digit
    blt 4f
    cmp x5,#'9'            // character not a digit
    bgt 4f
                           // character is a digit
    sub w5,w5,#48

    mul x0,x2,x0           // multiply last result by factor
    smulh x1,x2,x0         // hight 
    cbnz x1,99f            // overflow ?
    add x0,x0,x5           // no -> add to result
4:
    ldrb w5,[x4],1         // load new octet and increment to one
    cbz w5,5f              // string end -> end routine
    cmp w5,#0xA            // string end ?
    bne 3b                 // no -> loop
5:
    cmp x3,#1              // test register x3 for signe
    cneg x0,x0,eq          // if equal egal negate value
    cmn x0,0               // carry to zero no error
    b 100f
99:                        // overflow
    adr x0,szMessErrDep
    bl  affichageMess
    cmp x0,0               // carry to one  error
    mov x0,#0              // if error return zéro
100:
    ldp x1,x2,[sp],16      // restaur  2 registers
    ldp x3,x4,[sp],16      // restaur  2 registers
    ldp x5,lr,[sp],16      // restaur  2 registers
    ret                    // retur address lr x30
szMessErrDep:      .asciz "Number too large: overflow of 64 bits. :\n"
.align 4                   // instruction to realign the following routines
/***************************************************/
/*   reserve heap area                             */
/***************************************************/
// x0 contains size in byte to reserve */
// x0 returne  begin address of area */
reserverPlace:              // INFO: reserverPlace
    stp x1,lr,[sp,-16]!     // save  registers
    stp x2,x3,[sp,-16]!     // save  registers
    mov x1,x0
    tst x1,#0b111           // size multiple of 8 ?
    beq 1f                  // yes
    and x1,x1,0xFFFFFFFFFFFFFFF8 // else align to 8 superior
    add x1,x1,8
1:
    ldr x2,qAdrptzZoneHeap
    ldr x0,[x2]
    add x1,x1,x0            //  size too large ?
    ldr x3,qAdrzEndZoneHeap
    cmp x1,x3
    blt 2f                  // no it is ok
    adr x0,szMessErrTas     // yes -> error
    bl affichageMess
    mov x0,#-1
    b 100f
2:
    str x1,[x2]            // store new pointer
100:                       // fin standard de la fonction
    ldp x2,x3,[sp],16      // restaur  2 registers
    ldp x1,lr,[sp],16      // restaur  2 registers
    ret                    // retur address lr x30
qAdrptzZoneHeap:       .quad ptzZoneHeap
qAdrzEndZoneHeap:      .quad zEndZoneHeap
szMessErrTas:          .asciz "Error : heap not large !!!\n"
.align 4
/***************************************************/
/*   liberer place sur le tas                     */
/***************************************************/
// r0 contains begin address area 
libererPlace:               // INFO: libererPlace
    stp x1,lr,[sp,-16]!     // save  registers
    ldr x1,qAdrzZoneHeap
    cmp x0,x1
    blt 99f
    ldr x1,qAdrzEndZoneHeap
    cmp x0,x1
    bge 99f
    ldr x1,qAdrptzZoneHeap
    str x0,[x1]
    b 100f
99:
    adr x0,szMessErrTas1
    bl affichageMess
    mov x0,-1
100:
    ldp x1,lr,[sp],16      // restaur  2 registers
    ret                    // retur address lr x30
qAdrzZoneHeap:    .quad zZoneHeap
szMessErrTas1:    .asciz "Error : address  < or > heap addresses !!!\n"
.align 4

/******************************************************************/
/*   insert string at character insertion  */ 
/******************************************************************/
/* x0 contains the address of string 1 */
/* x1 contains the address of insertion string   */
/* x0 return the address of new string  on the heap */
/* or -1 if error   */
strInsertAtCharInc:
    stp x2,lr,[sp,-16]!                      // save  registers
    stp x3,x4,[sp,-16]!                      // save  registers
    stp x5,x6,[sp,-16]!                      // save  registers
    stp x7,x8,[sp,-16]!                      // save  registers
    mov x3,#0                                // length counter 
1:                                           // compute length of string 1
    ldrb w4,[x0,x3]
    cmp w4,#0
    cinc  x3,x3,ne                           // increment to one if not equal
    bne 1b                                   // loop if not equal
    mov x5,#0                                // length counter insertion string
2:                                           // compute length to insertion string
    ldrb w4,[x1,x5]
    cmp x4,#0
    cinc  x5,x5,ne                           // increment to one if not equal
    bne 2b                                   // and loop
    cmp x5,#0
    beq 99f                                  // string empty -> error
    add x3,x3,x5                             // add 2 length
    add x3,x3,#1                             // +1 for final zero
    mov x6,x0                                // save address string 1
    mov x0,x3
    bl reserverPlace
    cmp x0,#-1                               // allocation error
    beq 99f
    mov x5,x0                                // save address heap for output string
    mov x2,0
    mov x4,0               
3:                                           // loop copy string begin 
    ldrb w3,[x6,x2]
    cmp w3,0
    beq 99f
    cmp w3,CHARPOS                           // insertion character ?
    beq 5f                                   // yes
    strb w3,[x5,x4]                          // no store character in output string
    add x2,x2,1
    add x4,x4,1
    b 3b                                     // and loop
5:                                           // x4 contains position insertion
    add x8,x4,1                              // init index character output string
                                             // at position insertion + one
    mov x3,#0                                // index load characters insertion string
6:
    ldrb w0,[x1,x3]                          // load characters insertion string
    cmp w0,#0                                // end string ?
    beq 7f                                   // yes 
    strb w0,[x5,x4]                          // store in output string
    add x3,x3,#1                             // increment index
    add x4,x4,#1                             // increment output index
    b 6b                                     // and loop
7:                                           // loop copy end string 
    ldrb w0,[x6,x8]                          // load other character string 1
    strb w0,[x5,x4]                          // store in output string
    cmp x0,#0                                // end string 1 ?
    beq 8f                                   // yes -> end
    add x4,x4,#1                             // increment output index
    add x8,x8,#1                             // increment index
    b 7b                                     // and loop
8:
    mov x0,x5                                // return output string address 
    b 100f
99:                                          // error
    mov x0,#-1
100:
    ldp x7,x8,[sp],16                        // restaur  2 registers
    ldp x5,x6,[sp],16                        // restaur  2 registers
    ldp x3,x4,[sp],16                        // restaur  2 registers
    ldp x2,lr,[sp],16                        // restaur  2 registers
    ret

'Main program '
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program include.s   */

/*******************************************/
/* Constantes file                             */
/*******************************************/
.include "../includeConstantesARM64.inc"

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessResult:  .asciz "Number = "
szRetourLigne: .asciz "\n"
/*******************************************/
/* Uninitialized data                       */
/*******************************************/
.bss
sZoneConv:                   .skip 100
.text
.global main 
main:

    mov x0,1000                  // number 
    ldr x1,qAdrsZoneConv
    bl conversion10S              // result decimal conversion
    ldr x0,qAdrszMessResult
    bl affichageMess              // call function display
    ldr x0,qAdrsZoneConv
    bl affichageMess              // call function display
    ldr x0, qAdrszRetourLigne
    bl affichageMess
    mov x0,0                      // return code OK
100:                              // standard end programm
    mov x8,EXIT                   // request to exit program
    svc 0                         // perform the system call
qAdrszMessResult:            .quad szMessResult
qAdrsZoneConv:               .quad sZoneConv
qAdrszRetourLigne:           .quad szRetourLigne
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
.include "../includeARM64.inc"

ACL2

For files containing only events (definitions and similar; no top-level function calls) which are admissible (note the lack of file extension):

(include-book "filename")

For all other files:

(ld "filename.lisp")

Action!

INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

PROC Main()
RETURN
Output:

Screenshot from Atari 8-bit computer

INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

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.

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");

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:

PR read "file.a68" PR

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

# -*- coding: utf-8 -*- #
BEGIN
# Exception setup code: #
  on value error(stand out, (REF FILE f)BOOL: GOTO value error not mended);
# Block setup code: #
  printf(($"Prelude test:"l$))

File: postlude/test.a68

# -*- coding: utf-8 -*- #
# Block teardown code:  #
  printf(($"Postlude test."l$))
EXIT 
# Exception code: #
  value error not mended: SKIP
END

File: test/include.a68

#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

PR read "prelude/test.a68" PR;
printf($4x"Hello, world!"l$);
PR read "postlude/test.a68" PR
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:

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

Example of USING clause
A file called usemylib.a68:

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

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.

load["script.ant"]

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

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

SAVE PROGRAM TWO
 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
Output:
12

12

ARM Assembly

Works with: as version Raspberry Pi
'file constantes.inc'
/************************************/
/* Constantes                       */
/************************************/
.equ STDOUT, 1              @ Linux output console
.equ EXIT,   1              @ Linux syscall end program
.equ WRITE,  4              @ Linux syscall write 
.equ BRK,    0x2d           @ Linux syscall heap
.equ MKDIR, 0x27            @ Linux Syscal  create directory
.equ CHGDIR, 0xC            @ Linux Syscal  change directory
.equ CREATE, 0x8            @ Linux Syscal  create file
.equ CLOSE,   0x6           @ Linux Syscal  close file

.equ HEAPSIZE,  100000
.equ CHARPOS, '@'           @ character insertion

'file source include '
/* file affichage.inc */
.data
/*************************************************/
szMessErr: .ascii "Error code hexa : "
sHexa:     .space 9,' '
           .ascii "  decimal :  "
sDeci:     .space 15,' '
           .asciz "\n"
ptzZoneHeap:   .int zZoneHeap
/*************************************************/
.bss
.align 4
zZoneHeap:              .skip HEAPSIZE
zEndZoneHeap:
.text
/******************************************************************/
/*     display text with size calculation                         */ 
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                          @ save  registres
    mov r2,#0                                      @ counter length 
1:                                                 @ loop length calculation 
    ldrb r1,[r0,r2]                                @ read octet start position + index 
    cmp r1,#0                                       @ if 0 its over 
    addne r2,r2,#1                                 @ else add 1 in the length 
    bne 1b                                         @ and loop 
                                                    @ so here r2 contains the length of the message 
    mov r1,r0                                       @ address message in r1 
    mov r0,#STDOUT                                 @ code to write to the standard output Linux 
    mov r7, #WRITE                                 @ code call system "write" 
    svc #0                                         @ call systeme 
    pop {r0,r1,r2,r7,lr}                            @ restaur des  2 registres */ 
    bx lr                                           @ return  
/******************************************************************/
/*     Converting a register to a decimal unsigned                */ 
/******************************************************************/
/* r0 contains value and r1 address area   */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes          */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                                 @ save registers 
    mov r3,r1
    mov r2,#LGZONECAL
1:                                                  @ start loop
    bl divisionpar10U                               @ unsigned  r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                                      @ digit
    strb r1,[r3,r2]                                 @ store digit on area
    cmp r0,#0                                       @ stop if quotient = 0 
    subne r2,#1                                     @ else previous position
    bne 1b                                          @ and loop
                                                    @ and move digit from left of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]
    add r2,#1
    add r4,#1
    cmp r2,#LGZONECAL
    ble 2b
                                                      @ and move spaces in end on area
    mov r0,r4                                         @ result length 
    mov r1,#' '                                       @ space
3:
    strb r1,[r3,r4]                                   @ store space in area
    add r4,#1                                         @ next position
    cmp r4,#LGZONECAL
    ble 3b                                            @ loop if r4 <= area size
 
100:
    pop {r1-r4,lr}                                    @ restaur registres 
    bx lr     
/***************************************************/
/*  Converting a register to a signed decimal      */
/***************************************************/
/* r0 contains value and r1 area address    */
conversion10S:
    push {r0-r4,lr}       @ save registers
    mov r2,r1             @ debut zone stockage
    mov r3,#'+'           @ par defaut le signe est +
    cmp r0,#0             @ negative number ? 
    movlt r3,#'-'         @ yes
    mvnlt r0,r0           @ number inversion
    addlt r0,#1
    mov r4,#10            @ length area
1:                        @ start loop
    bl divisionpar10U
    add r1,#48            @ digit
    strb r1,[r2,r4]       @ store digit on area
    sub r4,r4,#1          @ previous position
    cmp r0,#0             @ stop if quotient = 0
    bne 1b	

    strb r3,[r2,r4]       @ store signe 
    subs r4,r4,#1         @ previous position
    blt  100f             @ if r4 < 0 -> end

    mov r1,#' '           @ space
2:
    strb r1,[r2,r4]       @store byte space
    subs r4,r4,#1         @ previous position
    bge 2b                @ loop if r4 > 0
100: 
    pop {r0-r4,lr}        @ restaur registers
    bx lr  
 
/***************************************************/
/*   division par 10   unsigned                    */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */	
/* r1 remainder  */
divisionpar10U:
    push {r2,r3,r4, lr}
    mov r4,r0                                          @ save value
    //mov r3,#0xCCCD                                   @ r3 <- magic_number lower  raspberry 3
    //movt r3,#0xCCCC                                  @ r3 <- magic_number higter raspberry 3
    ldr r3,iMagicNumber                                @ r3 <- magic_number    raspberry 1 2
    umull r1, r2, r3, r0                               @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) 
    mov r0, r2, LSR #3                                 @ r2 <- r2 >> shift 3
    add r2,r0,r0, lsl #2                               @ r2 <- r0 * 5 
    sub r1,r4,r2, lsl #1                               @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2,r3,r4,lr}
    bx lr                                              @ leave function 
iMagicNumber:  	.int 0xCCCCCCCD
/***************************************************/
/*   display error message                        */
/***************************************************/
/* r0 contains error code  r1 : message address */
displayError:
    push {r0-r2,lr}                         @ save registers
    mov r2,r0                               @ save error code
    mov r0,r1
    bl affichageMess
    mov r0,r2                               @ error code
    ldr r1,iAdrsHexa
    bl conversion16                         @ conversion hexa
    mov r0,r2                               @ error code
    ldr r1,iAdrsDeci                        @ result address
    bl conversion10S                        @ conversion decimale
    ldr r0,iAdrszMessErr                    @ display error message
    bl affichageMess
100:
    pop {r0-r2,lr}                          @ restaur registers
    bx lr                                   @ return 
iAdrszMessErr:                 .int szMessErr
iAdrsHexa:                     .int sHexa
iAdrsDeci:                     .int sDeci
/******************************************************************/
/*     Convert a string to a number stored in a registry          */ 
/******************************************************************/
/* r0 contains the address of the area terminated by 0 or 0A */
/* r0 returns a number                           */
conversionAtoD:
    push {fp,lr}         @ save 2 registers 
    push {r1-r7}         @ save others registers 
    mov r1,#0
    mov r2,#10           @ factor 
    mov r3,#0            @ counter 
    mov r4,r0            @ save address string -> r4 
    mov r6,#0            @ positive sign by default 
    mov r0,#0            @ initialization to 0 
1:     /* early space elimination loop */
    ldrb r5,[r4,r3]     @ loading in r5 of the byte located at the beginning + the position 
    cmp r5,#0            @ end of string -> end routine
    beq 100f
    cmp r5,#0x0A        @ end of string -> end routine
    beq 100f
    cmp r5,#' '          @ space ? 
    addeq r3,r3,#1      @ yes we loop by moving one byte 
    beq 1b
    cmp r5,#'-'          @ first character is -    
    moveq r6,#1         @  1 -> r6
    beq 3f              @ then move on to the next position 
2:   /* beginning of digit processing loop */
    cmp r5,#'0'          @ character is not a number 
    blt 3f
    cmp r5,#'9'          @ character is not a number
    bgt 3f
    /* character is a number */
    sub r5,#48
    ldr r1,iMaxi       @ check the overflow of the register    
    cmp r0,r1
    bgt 99f            @ overflow error
    mul r0,r2,r0         @ multiply par factor 10 
    add r0,r5            @ add to  r0 
3:
    add r3,r3,#1         @ advance to the next position 
    ldrb r5,[r4,r3]     @ load byte 
    cmp r5,#0            @ end of string -> end routine
    beq 4f
    cmp r5,#0x0A            @ end of string -> end routine
    beq 4f
    b 2b                 @ loop 
4:
    cmp r6,#1            @ test r6 for sign 
    moveq r1,#-1
    muleq r0,r1,r0       @ if negatif, multiply par -1 
    b 100f
99:  /* overflow error */
    ldr r0,=szMessErrDep
    bl   affichageMess
    mov r0,#0      @ return  zero  if error
100:
    pop {r1-r7}          @ restaur other registers 
    pop {fp,lr}          @ restaur   2 registers 
    bx lr                 @return procedure 
/* constante program */
iMaxi: .int 1073741824
szMessErrDep:  .asciz  "Too large: overflow 32 bits.\n"
.align 4
/******************************************************************/
/*     Converting a register to hexadecimal                      */ 
/******************************************************************/
/* r0 contains value and r1 address area   */
conversion16:
    push {r1-r4,lr}                                    @ save registers
    mov r2,#28                                         @ start bit position
    mov r4,#0xF0000000                                 @ mask
    mov r3,r0                                          @ save entry value
1:                                                     @ start loop
    and r0,r3,r4                                       @value register and mask
    lsr r0,r2                                          @ move right 
    cmp r0,#10                                         @ compare value
    addlt r0,#48                                       @ <10  ->digit	
    addge r0,#55                                       @ >10  ->letter A-F
    strb r0,[r1],#1                                    @ store digit on area and + 1 in area address
    lsr r4,#4                                          @ shift mask 4 positions
    subs r2,#4                                         @  counter bits - 4 <= zero  ?
    bge 1b                                             @  no -> loop

100:
    pop {r1-r4,lr}                                     @ restaur registers 
    bx lr                                              @return
/***************************************************/
/* integer division unsigned                       */
/***************************************************/
division:
    /* r0 contains dividend */
    /* r1 contains divisor */
    /* r2 returns quotient */
    /* r3 returns remainder */
    push {r4, lr}
    mov r2, #0                                         @ init quotient
    mov r3, #0                                         @ init remainder
    mov r4, #32                                        @ init counter bits
    b 2f
1:                                                     @ loop 
    movs r0, r0, LSL #1                                @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
    adc r3, r3, r3                                     @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C 
    cmp r3, r1                                         @ compute r3 - r1 and update cpsr 
    subhs r3, r3, r1                                   @ if r3 >= r1 (C=1) then r3 <- r3 - r1 
    adc r2, r2, r2                                     @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C 
2:
    subs r4, r4, #1                                    @ r4 <- r4 - 1 
    bpl 1b                                             @ if r4 >= 0 (N=0) then loop
    pop {r4, lr}
    bx lr
/***************************************************/
/*   reserve heap area                             */
/***************************************************/
// r0 contains size in byte to reserve */
// r0 returne  begin address of area */
reserverPlace:              @ INFO: reserverPlace
    push {r1,r2,r3,lr}      @ save des registres
    mov r1,r0
    tst r1,#0b11            @ size multiple of 4 ?
    beq 1f                  @ yes
    and r1,#0xFFFFFFFC      @ else align to 4 superior
    add r1,#4
1:
    ldr r2,iAdrptzZoneHeap
    ldr r0,[r2]
    add r1,r1,r0            @  size too large ?
    ldr r3,iAdrzEndZoneHeap
    cmp r1,r3
    blt 2f                  @ no it is ok
    adr r0,szMessErrTas     @ yes -> error
    bl affichageMess
    mov r0,#-1
    b 100f
2:
    str r1,[r2]           @ store new pointer
100:                      @ fin standard de la fonction
    pop {r1,r2,r3,lr}     @ restaur des registres
    bx lr                 @ retour de la fonction en utilisant lr
iAdrptzZoneHeap:       .int ptzZoneHeap
iAdrzEndZoneHeap:      .int zEndZoneHeap
szMessErrTas:          .asciz "Error : heap not large !!!\n"
.align 4
/***************************************************/
/*   liberer place sur le tas                     */
/***************************************************/
// r0 contains begin address area 
libererPlace:               @ INFO: libererPlace
    push {r1,lr}            @ save des registres
    ldr r1,iAdrzZoneHeap
    cmp r0,r1
    blt 99f
    ldr r1,iAdrzEndZoneHeap
    cmp r0,r1
    bge 99f
    ldr r1,iAdrptzZoneHeap
    str r0,[r1]
    b 100f
99:
    adr r0,szMessErrTas1
    bl affichageMess
    mov r0,#-1
100:
    pop {r1,lr}                          @ restaur registers 
    bx lr
iAdrzZoneHeap:    .int zZoneHeap
szMessErrTas1:    .asciz "Error : address  < or > heap addresses !!!\n"
.align 4
/******************************************************************/
/*   insert string at character insertion                         */ 
/******************************************************************/
/* r0 contains the address of string 1 */
/* r1 contains the address of insertion string   */
/* r0 return the address of new string  on the heap */
/* or -1 if error   */
strInsertAtCharInc:
    push {r1-r7,lr}                         @ save  registres
    mov r3,#0                                // length counter 
1:                                           // compute length of string 1
    ldrb r4,[r0,r3]
    cmp r4,#0
    addne r3,r3,#1                           // increment to one if not equal
    bne 1b                                   // loop if not equal
    mov r5,#0                                // length counter insertion string
2:                                           // compute length to insertion string
    ldrb r4,[r1,r5]
    cmp r4,#0
    addne r5,r5,#1                           // increment to one if not equal
    bne 2b                                   // and loop
    cmp r5,#0
    beq 99f                                  // string empty -> error
    add r3,r3,r5                             // add 2 length
    add r3,r3,#1                             // +1 for final zero
    mov r6,r0                                // save address string 1
    mov r0,r3
    bl reserverPlace
    mov r5,r0                                // save address heap for output string
    cmp r0,#-1                               // allocation error
    beq 99f
 
    mov r2,#0
    mov r4,#0
3:                                           // loop copy string begin 
    ldrb r3,[r6,r2]
    cmp r3,#0
    beq 99f
    cmp r3,#CHARPOS                           // insertion character ?
    beq 5f                                   // yes
    strb r3,[r5,r4]                          // no store character in output string
    add r2,r2,#1
    add r4,r4,#1
    b 3b                                     // and loop
5:                                           // r4 contains position insertion
    add r7,r4,#1                              // init index character output string
                                             // at position insertion + one
    mov r3,#0                                // index load characters insertion string
6:
    ldrb r0,[r1,r3]                          // load characters insertion string
    cmp r0,#0                                // end string ?
    beq 7f                                   // yes 
    strb r0,[r5,r4]                          // store in output string
    add r3,r3,#1                             // increment index
    add r4,r4,#1                             // increment output index
    b 6b                                     // and loop
7:                                           // loop copy end string 
    ldrb r0,[r6,r7]                          // load other character string 1
    strb r0,[r5,r4]                          // store in output string
    cmp r0,#0                                // end string 1 ?
    beq 8f                                   // yes -> end
    add r4,r4,#1                             // increment output index
    add r7,r7,#1                             // increment index
    b 7b                                     // and loop
8:
    mov r0,r5                                // return output string address 
    b 100f
99:                                          // error
    mov r0,#-1
100:
    pop {r1-r7,lr}                          @ restaur registers 
    bx lr                                   @ return  

'File Main program'

/* ARM assembly Raspberry PI  */
/*  program include.s   */

/* Constantes               */
.include "./constantes.inc"
/* Initialized data */
.data
szMessageOK:        .asciz "Hello \n"

/*  code section */
.text
.global main 
main:                                   @ entry of program
    push {fp,lr}                        @ saves registers
    ldr r0,iAdrszMessageOK
    bl affichageMess


100:                                    @ standard end of the program
    mov r0, #0                          @ return code
    pop {fp,lr}                         @restaur  registers
    mov r7, #EXIT                       @ request to exit program
    swi 0                               @ perform the system call

iAdrszMessageOK:           .int szMessageOK

/*********************************/
/* include source display        */
/*********************************/
.include "./affichage.inc"

Arturo

; import a file
do.import {file.art}

; import another file
; from relative folder location
do.import relative "another_file.art"

AutoHotkey

#Include FileOrDirName
#IncludeAgain FileOrDirName

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:

awk -f one.awk -f two.awk

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

# one.awk
BEGIN {
  sayhello()
}

# two.awk
function sayhello() {
  print "Hello world"
}

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.

@include "filename.awk"

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.

prgmOTHER

BaCon

other.bac

other = 42

including.bac

' Include a file
INCLUDE "other.bac"
PRINT other
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.

REM $INCLUDE: 'file.bi'
'$INCLUDE: 'file.bi'

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

Batch File

call file2.bat

BBC BASIC

      CALL filepath$

The file is loaded into memory at run-time, executed, and then discarded. It must be in 'tokenised' (internal) .BBC format.

Bracmat

get$"<i>module</i>"

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.

/* Standard and other library header names are enclosed between chevrons */
#include <stdlib.h>

/* User/in-project header names are usually enclosed between double-quotes */
#include "myutil.h"
/* In C++20,you can use the import statement */
import <iostream>;

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#

/* 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.
 */

ChucK

Machine.add(me.dir() + "/MyOwnClassesDefinitions.ck");

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.

  #include "inkey.ch"

Clojure

Just as in Common Lisp:

(load "path/to/file")

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.

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

Common Lisp

(load "path/to/file")

Crystal

require "socket"   # includes a file from standard library or /lib relative to current directory
require "./myfile" # includes a file relative to current directory

D

D has a module system, so usually there is no need of a textual inclusion of a text file:

import std.stdio;

To perform a textual inclusion:

mixin(import("code.txt"));

At the expression level, e.g for large ubyte and char arrays:

static immutable array = import("data.txt");

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

Dragon

To include source code from another file, you simply need to use include keyword with file name.

Just this would be enough.

func my(){
  showln "hello"
  //this is program.dgn
}
include "program.dgn"
my() // output : hello

DWScript

In addition to straight inclusion, there is a filtered inclusion, in which the include file goes through a pre-processing filter.

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

Déjà Vu

#with the module system:
!import!foo

#passing a file name (only works with compiled bytecode files):
!run-file "/path/file.vu"

Emacs Lisp

Write this code in: file1.el

(defun sum (ls)
  (apply '+ ls) )

In the directory of file1.el, we write this new code in: file2.el

(add-to-list 'load-path "./")
(load "./file1.el")
(insert (format "%d" (sum (number-sequence 1 100) )))

Output:

5050

Erlang

-include("my_header.hrl"). % Includes the file at my_header.erl

Euphoria

include my_header.e

Factor

USING: vocaba vocabb... ;

Forth

include matrix.fs

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

Fortran

include ''char-literal-constant''

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

' 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

Main file :

' FB 1.05.0 Win 64

' main.bas file
#include "person.bi"

Dim person1 As Person
person1.name = "Methuselah"
person1.age = 969
Print person1
Print
Print "Press any key to quit"
Sleep
Output:
[Methuselah, 969]

Frink

The statement use filename includes a file. The Frink documentation section Including Other Files describes how paths are searched for the file.

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.

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

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

Public Sub Form_Open()
Dim sFile As String

sFile = File.Load("FileToLoad")

End

GAP

Read("file");

Gnuplot

load "filename.gnuplot"

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

load "-"         # read standard input

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

load "< myprogram"       # run myprogram, read its output
load "< echo print 123"

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

call "filename.gnuplot" 123 456 "arg3"

Go

Go has a 'package' system and doesn't therefore need to include source code from other files via an #include directive (as found in C/C++) or similar.

Instead one can simply give the other source code file(s) the same package name as the 'main' file, copy them to the same directory and build them all together. For example:

// main.go
package main

import "fmt"

func hello() {
    fmt.Println("Hello from main.go")
}

func main() {
    hello()
    hello2()
}
// main2.go
package main

import "fmt"

func hello2() {
    fmt.Println("Hello from main2.go")
}
Output:
$ go build main.go main2.go
$ ./main
Hello from main.go
Hello from main2.go

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.

#include "inkey.ch"

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:
#include "SomeModule.hs"

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:

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

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

<include>foobar.html</include>

Icon and Unicon

Include another file of source code using the preprocessor statement:

$include "filename.icn"

IWBASIC

$INCLUDE "ishelllink.inc"

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

$USE "libraries\\mylib.lib"

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:

Success=LOADRESOURCE(ID,Type,Variable)

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:

@RESCURSOR
@RESBITMAP
@RESICON
@RESMENU
@RESDIALOG
@RESSTRING
@RESACCEL
@RESDATA
@RESMESSAGETABLE
@RESGROUPCURSOR
@RESGROUPICON
@RESVERSION

J

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

require 'myheader.ijs'

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:

load 'myheader.ijs'

That said, the raw mechanism here would be

0!:0<'myheader.ijs'

and this form might be used in the unusual circumstance where the file myheader.ijs defined local variables and the scope of those local names was meant be larger than the context of the load verb.

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.

public class Class1 extends Class2
{
	//code here
}

You could also consider creating an instance of Class2 within Class1, and then using the instance methods.

public class Class1
{
	Class2 c2=new Class2();
	static void main(String[] args)
	{
		c2.func1();
		c2.func2();
	}
}

JavaScript

Pure JavaScript in browsers with the DOM

Following example, if loaded in an HTML file, loads the jQuery library from a remote site

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

Most be noted that it can also request HTTP source and eval() the source

With jQuery

Library: jQuery
$.getScript("http://example.com/script.js");

With AMD (require.js)

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

CommonJS style with node.js (or browserify)

Library: node.js
var $ = require('$');

ES6 Modules

import $ from "jquery";

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

include "gort";

hello

gort.jq

def hello: "Klaatu barada nikto";
Output:
$ jq -n -c -f Include_a_file.jq
Klaatu barada nikto.

Jsish

jsish can include other source via System.source('filename');. Versioned moduled can be included via System.require('module', version);. Methods in the System object are automatically exported as top level globals (and the module version argument defaults to 1), so those can be shortened to

source('file');
require('module');

Compiled code can also be included via System.load('shlib');, but that feature requires a known named init function, Jsi_Init[shlib] to be an exported symbol in the Dynamic Shared Object file.

Julia

Julia's include function executes code from an arbitrary file:

include("foo.jl")

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:

import MyModule

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

using MyModule

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:

fun f() = println("f called")

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

// version 1.1.2

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

fun main(args: Array<String>) {
    f()  // invoke f without qualification
}
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 ==

web_response -> include('my_file.inc')

Lang

# Execute and copy variables defined in code.lang only
ln.bindLibrary(code.lang)

# Execute and copy translations defined in code.lang only
ln.link(code.lang)

# Execute and copy variables and translations defined in code.lang
ln.include(code.lang)

Lasso

include('myfile.lasso')

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

Logtalk

:- object(foo).

    :- include(bar).

:- end_object.

Lua

To include a header file myheader.lua:

 require "myheader"

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.

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

Running code of a module, as code is inline and not in that module. Now X is a variable in CheckIt

\\ we can delete global
Module Global alfa {
      Print "this is alfa"
      X=10
}
Module Checkit {
      Inline Code alfa
      Print X=10
}
Checkit

m4

include(filename)

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.

$include <somefile>

Or

$include "somefile"

It is also possible to read a file, using the "read" statement. This has rather different semantics.

read "somefile":

Mathematica / Wolfram Language

 Get["myfile.m"]

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:

  % 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

Maxima

load("c:/.../source.mac")$

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

Modula-2

IMPORT  InOut, NumConv, Strings;

Modula-3

IMPORT IO, Text AS Str;
FROM Str IMPORT T

Nanoquery

import "filename.nq"

Nemerle

To include classes, static methods etc. from other namespaces, include those namespaces with the using keyword

using System.Console;

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.

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
}

NewLISP

;; local file
(load "file.lsp")

;; URLs (both http:// and file:// URLs are supported)
(load "http://www.newlisp.org/code/modules/ftp.lsp")

Nim

As other modular languages, accessing from a module to symbols of other modules is done by importation.
After import someModule an exported symbol x can be accessed as x and as someModule.x.

import someModule
import strutils except parseInt
import strutils as su, sequtils as qu # su.x works
import pure/os, "pure/times" # still strutils.x

But Nim provides also a way to include the content of a file, using the include statement:

include someFile

The import statement is only allowed at top level whereas the include statement can be used at any level as it simply includes the text (at the appropriate indentation level). Here is an example from the Nim manual:

# Module A
echo "Hello World!"


# Module B
proc main() =
  include A

main() # => Hello World!

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:

#use "some_file.ml"

In compile mode (compiled to bytecode or compiled to native code) we can use:

include Name_of_a_module

Oforth

In order to load a file with name filename :

"filename" load

In order to load a package with name pack :

import: pack

Ol

Ol has a module system, so usually there is no need of a textual inclusion of a text file.

(import (otus random!))

You can do a textual inclusion from the global scope using REPL command ",load" (not a part of core language itself, but a REPL extension).

,load "otus/random!.scm"

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.

   ::requires "regex.cls"

OpenEdge/Progress

Curly braces indicate that a file should be included. The file is searched across all PROPATH directory entries.

{file.i}

Arguments can be passed to the file being included:

{file.i super}

Openscad

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

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

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

PascalABC.NET

{$include a.inc}

begin
  Hello
end.

a.inc

procedure Hello := Print('Hello');


Perl

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

main.perl:

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

include.pl:

sub sayhello {
  print "Hello World!";
}

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.

Phix

Library: Phix/basics
include pGUI.e

Phix also supports relative directory includes, for instance if you include "..\demo\pGUI\demo.ew" then anything demo.ew includes is looked for in the same location.

The following remarks have been copied verbatim from the Compiler/Simple_file_inclusion_pre_processor#Phix entry:
Phix ships with a bunch of standard files in a builtins directory, most of which it knows how to "autoinclude", but some must be explicitly included (full docs). You can explicitly specify the builtins directory or not (obviously without it will look in the project directory first), and use the same mechanism for files you have written yourself. There is no limit to the number or depth of files than can be included. Relative directories are honoured, so if you specify a (partial) directory that is where it will look first for any sub-includes. You can also use single line "stub includes" to redirect include statements to different directories/versions. Note that namespaces are not supported by pwa/p2js. You can optionally use double quotes, but may then need to escape backslashes. Includes occur at compile time, as opposed to dynamically.

include builtins/complex.e
include complex.e             -- also valid
include "builtins\\complex.e" -- ditto

If the compiler detects that some file has already been included it does not do it again (from the same directory, two or more files of the same name can be included from different directories). I should perhaps also state that include handling is part of normal compilation/interpretation, as opposed to a separate "preprocessing" step, and that each file is granted a new private scope, and while of course there is only one "global" scope, it will use the implicit include hierarchy to automatically resolve any clashes that might arise to the most appropriate one, aka "if it works standalone it should work exactly the same when included in as part of a larger application".

PHP

There are different ways to do this in PHP. You can use a basic include:

include("file.php")

You can be safe about it and make sure it's not included more than once:

include_once("file.php")

You can crash the code at this point if the include fails for any reason by using require:

require("file.php")

And you can use the require statement, with the safe _once method:

require_once("file.php")

Picat

cl/1

cl/1 compiles a Picat program to a byte code file (.qi) and load that.

cl("include_file.pi")

The extension (.pi) can be omitted:

cl(include_file)

load/1

load/1 loads a byte code file. If the byte code files does not exist, the program is first compiled.

load(include_file)

import

A Picat module is loaded with import module, which must be placed before any other definitions in the program.

import cp, util.


PicoLisp

The function 'load' is used for recursively executing the contents of files.

(load "file1.l" "file2.l" "file3.l")

Pike

Including verbatim can be done with the "#include" preprocessor directive. This is usually only done for including constants or similar while code is handled via the module system.

Where code has to be included and compiled dynamically at run-time the compile() and compile_file() functions can be used.

#include "foo.txt"

PL/I

%include myfile;

PL/M

The original PL/M compiler did not have file inclusion, however PL/M 386 and possibly other versions, had a "$INCLUDE" compiler control statement. The "$" had to appear in the first column. Nesting of include files was possible, to a depth of 5 (in PL/M 386).

$INCLUDE (fileName.inc)

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.

#INCLUDE "Win32API.inc"
#INCLUDE ONCE "Win32API.inc"

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

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

Processing

Processing may include a file using a number of different methods.

1. Processing sketches automatically include any Processing .pde or Java .java files in the sketch directory. All .pde files are concatenated together and processed as if they were one big file. Each .java file is compiled to a Java class and the class is automatically imported.

So, for a sketch:

 MySketch/  
   MySketch.pde  
   one.pde
   two.pde
   MyClass.java

...the local files one.pde, two.pde, and MyClass.java are all automatically imported into MySketch by virtue of their extensions, without being explicitly referenced in MySketch.pde.

2. Java import statements may be used to import libraries from the path.

Processing also supports the `import` keyword for explicitly including Processing / Java 8 library files. This can be used to import standard part of Java 8, for example the Map class:

import java.util.Map;

It can also be used to import contributed libraries, which may be installed via PDE Contributions Manager or locally on the Processing Libraries path. For example, if the G4P library is installed, its files are then imported into a sketch with:

import g4p_controls.*;

3. Local Java JAR files may be added to the sketch /code subfolder, then imported with `import`. For example, if you have a file code/test.jar:

 MySketch/
   code/
     test.jar
   MySketch.pde

...and it contains a Java class file `foo/bar/Test.class`, then that can be imported from the file. The specific jar file name does _not_ need to be identified -- any resource in any jar file can be imported so long as you specify the in-jar path and class name in the import statement.

import foo.bar.Test;

Processing Python mode

Processing Python may include modules, .py files, using Python's `import` statements.

1. Sketches must contain a main .pyde file in the sketch directory, of same name. Tabs in the IDE are additional .py files that can be included.

So, for a sketch:

 MySketch/  
   MySketch.pyde  
   one.py

One can write:

import one # note there is no .py sufix
# then you may use
# one.one_function()
# object = one.OneClass()

otherwise use

from one import *

or, recommended style:

from one import OneClass, one_function
# then you may use
# one_function()
# object = OneClass()

Prolog

consult('filename').

PureBasic

IncludeFile will include the named source file at the current place in the code.

IncludeFile "Filename"

XIncludeFile is exactly the same except it avoids including the same file several times.

XIncludeFile "Filename"

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.

IncludeBinary "Filename"

Python

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

import mymodule

includes the content of mymodule.py

Names in this module can be accessed as attributes:

mymodule.variable

QB64

'$INCLUDE:'filename.bas'

Quackery

To load and compile a file called myfile.qky:

$ "myfile.qky" loadfile

To load and compile a file called myfile.qky whilst loading and compiling another file:

[ $ "myfile.qky" loadfile ] now!

To prevent a file called myfile.qky from being loaded and compiled more than once during a Quackery session (e.g. a library module that may be invoked during compilation of several other files) define a word called myfile.qky in the file myfile.qky. By convention, use this definition as the first line of the file:

[ this ] is myfile.qky

R

source("filename.R")

Racket

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

#lang racket
(include "other-file.rkt")

Raku

(formerly Perl 6)

Raku provides a module system that is based primarily on importation of symbols rather than on inclusion of textual code:

use MyModule;

However, one can evaluate code from a file:

require 'myfile.p6';

One can even do that at compile time:

BEGIN require 'myfile.p6'

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:

macro include(AST $file) { slurp $file.eval }
include('myfile.p6');

RapidQ

$INCLUDE "RAPIDQ.INC"

Retro

'filename include

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

/*%INCLUDE member */

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

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

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

Program2.rexx

/* This is program 2 */
say 'This is program 2 writing on standard output.'
say 'We now return to the caller.'
return

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.

This approach works, but is painfully slow since REXX reads the source on every call. No caching. External calls are hundreds of times slower as inline calls.

A low-profile preprocessor

Works with: ooRexx
Works with: Regina

See Compiler/Simple file inclusion pre processor

Ring

Load 'file.ring'

RPG

Works with: ILE 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"

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.

require 'file'

Run BASIC

You don't use the file extension. .bas is assumed.

run SomeProgram.bas",#include         ' this gives it a handle of #include
render #include                       ' render will RUN the program with handle #include

Rust

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

mod test;

fn main() {
    test::some_function();
}

Additionally, third-party libraries (called crates in rust) can be declared thusly:

extern crate foo;
fn main() {
    foo::some_function();
}

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.

Scheme

(load "filename")

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.

$ include "seed7_05.s7i";

All following include directives don't need a $ to introduce them. The float.s7i library can be included with:

  include "float.s7i";

Sidef

Include a file in the current namespace:

include 'file.sf';

Include a file as module (file must exists in SIDEF_INC as Some/Name.sm):

include Some::Name;
# variables are available here as: Some::Name::var_name

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:

aFilename asFilename readStream fileIn

or:

Smalltalk fileIn: aFilename

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
-INCLUDE "path/to/filename.inc"

SPL

$include.txt

Standard ML

Works with: SML/NJ
use "path/to/file";

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

source "foobar.tcl"

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

package require foobar 1.3

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
. myfile.sh    # Include the contents of myfile.sh

C Shell

source myfile.csh

Bash

. myfile.sh
source myfile.sh

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.

import "filename.u"

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:

var map = new Gee.HashMap<string, int> ();

or with a using statement:

using Gee;

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

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.

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

If you use the wsf form you can include a file by

<script id="Connections" language="VBScript" src="D:\include\ConnectionStrings.vbs"/>

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

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

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

V (Vlang)

V is a modular language and is quite easy to use. Create a directory with your module's name containing .v files:

cd ~/code/modules
mkdir mymodule

In that directory, create .v files. Example- myfile.v (file 1)

module mymodule

// To export a function we have to use 'pub'
pub fn say_hi() {
	println('hello from mymodule!')
}

In the same directory, create the 2nd file. Example- myfile2.v (file 2)

module mymodule

pub fn say_hi_and_bye() {
	say_hi() // from myfile.v
	println('goodbye from mymodule')
}

After creating files in the same directory, with the same module name (mymodule).

You can now import them into new files, as below:

import mymodule // name of module in those files

fn main() {
	mymodule.say_hi() // function from file 1 (myfile.v)
	mymodule.say_hi_and_bye() // function from file 2 (myfile2.v)
}

Wren

Library: Wren-fmt
Library: Wren-math

The import statement in Wren behaves in much the same way as the #include directive in C. However, there are some important differences:

1. You have to specify which top-level variable names you want to import using the for clause.

2. A module (Wren's term for a source code file) is only ever loaded once.

3. All core modules are imported automatically without the need for an import statement.

4. The code for an imported module is executed in a separate fiber from the main module.

Here's a simple example.

import "./fmt" for Fmt   // imports the Fmt module and makes the 'Fmt' class available
import "./math" for Math // imports the Math module and makes the 'Math' class available

Fmt.print("The value of 'e' to 6 d.p. is $,f.", Math.e)
Output:
The value of 'e' to 6 d.p. is 2.718282.

x86 Assembly

Works with: FASM on Windows
include 'MyFile.INC'
Works with: nasm
%include "MyFile.INC"

XPL0

include c:\cxpl\stdlib;
DateOut(0, GetDate)
Output:
09-28-12

Z80 Assembly

There are two different directives for including files: include and incbin.

  • include is for assembly code that will be converted to machine code that the computer can run.
  • incbin is for binary data such as graphics, which the assembler will convert as-is to binary and does not attempt to translate it into machine code.

It's important to note that, unlike in high-level languages, WHERE your include/incbin statements are located relative to your other code matters. Placing it incorrectly can cause execution to "fall into" your included files when you didn't intend it to happen.


What not to do:

org &1000
include "\source\mathLibrary.asm"
main:
ld a,&42
ret

In assembly, the order you arrange your code is typically the same as its layout in memory, unless you're using a linker. In the above example, execution will begin at the ORG directive and "fall through" into your math Library, rather than starting at main. Unless your program has a header that jumps to main (something that C generates for you automatically), you're going to have some undesired effects if you don't "trap" the program counter.

The right way:

org &1000
main:
ld a,&42
ret
include "\source\mathLibrary.asm"

You'll have to take this with a grain of salt, as it's hardware-dependent (the above was for Amstrad CPC or other similar home computers where your program is CALLed from BASIC.) If you're defining your own ROM header for something like Game Boy things will be a bit different.

zkl

include(vm.h.zkl, compiler.h.zkl, zkl.h.zkl, opcode.h.zkl);

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:

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