Erlang -- Compilation and Code Loading

User's Guide
PDF
Top

Erlang Reference Manual
User's Guide
Version 5.9.2

Expand All
Contract All

Chapters

- Introduction
  - Top of chapter
  - Purpose
  - Prerequisites
  - Document Conventions
  - Complete List of BIFs
  - Reserved Words
  - Character Set
- Data Types
  - Top of chapter
  - Terms
  - Number
  - Atom
  - Bit Strings and Binaries
  - Reference
  - Fun
  - Port Identifier
  - Pid
  - Tuple
  - List
  - String
  - Record
  - Boolean
  - Escape Sequences
  - Type Conversions
- Pattern Matching
  - Top of chapter
  - Pattern Matching
- Modules
  - Top of chapter
  - Module Syntax
  - Module Attributes
  - Comments
  - The module_info/0 and module_info/1 functions
- Functions
  - Top of chapter
  - Function Declaration Syntax
  - Function Evaluation
  - Tail recursion
  - Built-In Functions, BIFs
- Types and Function Specifications
  - Top of chapter
  - Introduction of Types
  - Types and their Syntax
  - Type declarations of user-defined types
  - Type information in record declarations
  - Specifications for functions
- Expressions
  - Top of chapter
  - Expression Evaluation
  - Terms
  - Variables
  - Patterns
  - Match
  - Function Calls
  - If
  - Case
  - Send
  - Receive
  - Term Comparisons
  - Arithmetic Expressions
  - Boolean Expressions
  - Short-Circuit Expressions
  - List Operations
  - Bit Syntax Expressions
  - Fun Expressions
  - Catch and Throw
  - Try
  - Parenthesized Expressions
  - Block Expressions
  - List Comprehensions
  - Bit String Comprehensions
  - Guard Sequences
  - Operator Precedence
- The Preprocessor
  - Top of chapter
  - File Inclusion
  - Defining and Using Macros
  - Predefined Macros
  - Macros Overloading
  - Flow Control in Macros
  - Stringifying Macro Arguments
- Records
  - Top of chapter
  - Defining Records
  - Creating Records
  - Accessing Record Fields
  - Updating Records
  - Records in Guards
  - Records in Patterns
  - Nested records
  - Internal Representation of Records
- Errors and Error Handling
  - Top of chapter
  - Terminology
  - Exceptions
  - Handling of Run-Time Errors in Erlang
  - Exit Reasons
- Processes
  - Top of chapter
  - Processes
  - Process Creation
  - Registered Processes
  - Process Termination
  - Message Sending
  - Links
  - Error Handling
  - Monitors
  - Process Dictionary
- Distributed Erlang
  - Top of chapter
  - Distributed Erlang System
  - Nodes
  - Node Connections
  - epmd
  - Hidden Nodes
  - C Nodes
  - Security
  - Distribution BIFs
  - Distribution Command Line Flags
  - Distribution Modules
- Compilation and Code Loading
  - Top of chapter
  - Compilation
  - Code Loading
  - Code Replacement
  - Running a function when a module is loaded
- Ports and Port Drivers
  - Top of chapter
  - Ports
  - Port Drivers
  - Port BIFs

# 13 Compilation and Code Loading

How code is compiled and loaded is not a language issue, but is system dependent. This chapter describes compilation and code loading in Erlang/OTP with pointers to relevant parts of the documentation.

### 13.1 Compilation

Erlang programs must be compiled to object code. The compiler can generate a new file which contains the object code. The current abstract machine which runs the object code is called BEAM, therefore the object files get the suffix .beam. The compiler can also generate a binary which can be loaded directly.

The compiler is located in the Kernel module compile, see compile(3).

    compile:file(Module)
    compile:file(Module, Options)

The Erlang shell understands the command c(Module) which both compiles and loads Module.

There is also a module make which provides a set of functions similar to the UNIX type Make functions, see make(3).

The compiler can also be accessed from the OS prompt, see erl(1).

    % erl -compile Module1...ModuleN
    % erl -make

The erlc program provides an even better way to compile modules from the shell, see erlc(1). It understands a number of flags that can be used to define macros, add search paths for include files, and more.

    % erlc <flags> File1.erl...FileN.erl

### 13.2 Code Loading

The object code must be loaded into the Erlang runtime system. This is handled by the code server, see code(3).

The code server loads code according to a code loading strategy which is either interactive (default) or embedded. In interactive mode, code are searched for in a code path and loaded when first referenced. In embedded mode, code is loaded at start-up according to a boot script. This is described in System Principles.

### 13.3 Code Replacement

Erlang supports change of code in a running system. Code replacement is done on module level.

The code of a module can exist in two variants in a system: current and old. When a module is loaded into the system for the first time, the code becomes 'current'. If then a new instance of the module is loaded, the code of the previous instance becomes 'old' and the new instance becomes 'current'.

Both old and current code is valid, and may be evaluated concurrently. Fully qualified function calls always refer to current code. Old code may still be evaluated because of processes lingering in the old code.

If a third instance of the module is loaded, the code server will remove (purge) the old code and any processes lingering in it will be terminated. Then the third instance becomes 'current' and the previously current code becomes 'old'.

To change from old code to current code, a process must make a fully qualified function call. Example:

    -module(m).
    -export([loop/0]).

    loop() ->
        receive
            code_switch ->
                m:loop();
            Msg ->
                ...
                loop()
        end.

To make the process change code, send the message code_switch to it. The process then will make a fully qualified call to m:loop() and change to current code. Note that m:loop/0 must be exported.

For code replacement of funs to work, the syntax fun Module:FunctionName/Arity should be used.

### 13.4 Running a function when a module is loaded

Warning

This section describes an experimental feature that was introduced in R13B03, and changed in a backwards-incompatible way in R13B04. There may be more backward-incompatible changes in future releases.

The -on_load() directive names a function that should be run automatically when a module a loaded. Its syntax is:

    -on_load(Name/0).

It is not necessary to export the function. It will be called in a freshly spawned process (which will be terminated as soon as the function returns). The function must return ok if the module is to be remained loaded and become callable, or any other value if the module is to be unloaded. Generating an exception will also cause the module to be unloaded. If the return value is not an atom, a warning error report will be sent to the error logger.

A process that calls any function in a module whose on_load function has not yet returned will be suspended until the on_load function has returned.

In embedded mode, all modules will be loaded first and then will all on_load functions be called. The system will be terminated unless all of the on_load functions return ok

.

Example:

    -module(m).
    -on_load(load_my_nifs/0).

    load_my_nifs() ->
        NifPath = ...,    %Set up the path to the NIF library.
        Info = ...,       %Initialize the Info term
        erlang:load_nif(NifPath, Info).

If the call to erlang:load_nif/2 fails, the module will be unloaded and there will be warning report sent to the error loader.