HEX
Server: Apache/2.4.46 (Win64) OpenSSL/1.1.1j PHP/8.4.25
System: Windows NT DESKTOP-4TAV2RJ 10.0 build 19045 (Windows 10) AMD64
User: fred (0)
PHP: 8.4.25
Disabled: NONE
Upload Files
File: C:/Program Files/R/R-4.4.0/doc/manual/R-exts.html
<!DOCTYPE html>
<html>
<!-- Created by GNU Texinfo 7.1, https://www.gnu.org/software/texinfo/ -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- This manual is for R, version 4.4.0 (2024-04-24).

Copyright © 1999-2024 R Core Team

Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation
approved by the R Core Team. -->
<title>Writing R Extensions</title>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Writing R Extensions">
<meta name="keywords" content="Writing R Extensions">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2any">
<meta name="viewport" content="width=device-width,initial-scale=1">

<link href="#Top" rel="start" title="Top">
<link href="#Function-and-variable-index" rel="index" title="Function and variable index">
<link href="#SEC_Contents" rel="contents" title="Table of Contents">
<link href="#Acknowledgements" rel="next" title="Acknowledgements">
<style type="text/css">
<!--
a.copiable-link {visibility: hidden; text-decoration: none; line-height: 0em}
a.summary-letter-printindex {text-decoration: none}
div.example {margin-left: 3.2em}
kbd.kbd {font-style: oblique}
kbd.key {font-style: normal}
span.r {font-family: initial; font-weight: normal; font-style: normal}
span:hover a.copiable-link {visibility: visible}
strong.def-name {font-family: monospace; font-weight: bold; font-size: larger}
td.printindex-index-entry {vertical-align: top}
td.printindex-index-section {vertical-align: top; padding-left: 1em}
th.entries-header-printindex {text-align:left}
th.sections-header-printindex {text-align:left; padding-left: 1em}
ul.mark-bullet {list-style-type: disc}
ul.mark-minus {list-style-type: "\2212"}
ul.toc-numbered-mark {list-style: none}
body {
    margin-left: 5%;
    margin-right: 5%;
}

h1 {             
    background: white;
    color: rgb(25%, 25%, 25%);
    font-family: monospace;
    font-size: xx-large;
    text-align: center;
}

h2 {
    background: white;
    color: rgb(40%, 40%, 40%);
    font-family: monospace;
    font-size: x-large;
    text-align: center;
}

h3 {
    background: white;
    color: rgb(40%, 40%, 40%);
    font-family: monospace;
    font-size: large;
}

h4 {
    background: white;
    color: rgb(40%, 40%, 40%);
    font-family: monospace;
}

span.samp {
    font-family: monospace;
}

span.command {
    font-family: monospace;
}

span.option {
    font-family: monospace;
}

span.file {
    font-family: monospace;
}

span.env {
    font-family: monospace;
}

ul {
    margin-top: 0.25ex;
    margin-bottom: 0.25ex;
}

li {
    margin-top: 0.25ex;
    margin-bottom: 0.25ex;
}

p {
    margin-top: 0.6ex;
    margin-bottom: 1.2ex;
}

/* hide top navigation bar in Texinfo >= 6.8 output */
#Top > .header, #Top > .nav-panel {
    display: none
}

-->
</style>


</head>

<body lang="en">
























<div class="top-level-extent" id="Top">
<div class="nav-panel">
<p>
Next: <a href="#Acknowledgements" accesskey="n" rel="next">Acknowledgements</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h1 class="top" id="Writing-R-Extensions"><span>Writing R Extensions<a class="copiable-link" href="#Writing-R-Extensions"> &para;</a></span></h1>

<p>This is a guide to extending R, describing the process of creating
R add-on packages, writing R documentation, R&rsquo;s system and
foreign language interfaces, and the R <abbr class="acronym">API</abbr>.
</p>
<p>This manual is for R, version 4.4.0 (2024-04-24).
</p>
<p>Copyright &copy; 1999&ndash;2024 R Core Team
</p>
<blockquote class="quotation">
<p>Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.
</p>
<p>Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.
</p>
<p>Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation
approved by the R Core Team.
</p></blockquote>



<div class="element-contents" id="SEC_Contents">
<h2 class="contents-heading">Table of Contents</h2>

<div class="contents">

<ul class="toc-numbered-mark">
  <li><a id="toc-Acknowledgements-1" href="#Acknowledgements">Acknowledgements</a></li>
  <li><a id="toc-Creating-R-packages-1" href="#Creating-R-packages">1 Creating R packages</a>
  <ul class="toc-numbered-mark">
    <li><a id="toc-Package-structure-1" href="#Package-structure">1.1 Package structure</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-The-DESCRIPTION-file-1" href="#The-DESCRIPTION-file">1.1.1 The <samp class="file">DESCRIPTION</samp> file</a></li>
      <li><a id="toc-Licensing-1" href="#Licensing">1.1.2 Licensing</a></li>
      <li><a id="toc-Package-Dependencies-1" href="#Package-Dependencies">1.1.3 Package Dependencies</a>
      <ul class="toc-numbered-mark">
        <li><a id="toc-Suggested-packages-1" href="#Suggested-packages">1.1.3.1 Suggested packages</a></li>
      </ul></li>
      <li><a id="toc-The-INDEX-file-1" href="#The-INDEX-file">1.1.4 The <samp class="file">INDEX</samp> file</a></li>
      <li><a id="toc-Package-subdirectories-1" href="#Package-subdirectories">1.1.5 Package subdirectories</a></li>
      <li><a id="toc-Data-in-packages-1" href="#Data-in-packages">1.1.6 Data in packages</a></li>
      <li><a id="toc-Non_002dR-scripts-in-packages-1" href="#Non_002dR-scripts-in-packages">1.1.7 Non-R scripts in packages</a></li>
      <li><a id="toc-Specifying-URLs-1" href="#Specifying-URLs">1.1.8 Specifying URLs</a></li>
    </ul></li>
    <li><a id="toc-Configure-and-cleanup-1" href="#Configure-and-cleanup">1.2 Configure and cleanup</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Using-Makevars-1" href="#Using-Makevars">1.2.1 Using <samp class="file">Makevars</samp></a>
      <ul class="toc-numbered-mark">
        <li><a id="toc-OpenMP-support-1" href="#OpenMP-support">1.2.1.1 <abbr class="abbr">OpenMP</abbr> support</a></li>
        <li><a id="toc-Using-pthreads-1" href="#Using-pthreads">1.2.1.2 Using pthreads</a></li>
        <li><a id="toc-Compiling-in-sub_002ddirectories-1" href="#Compiling-in-sub_002ddirectories">1.2.1.3 Compiling in sub-directories</a></li>
      </ul></li>
      <li><a id="toc-Configure-example-1" href="#Configure-example">1.2.2 Configure example</a></li>
      <li><a id="toc-Using-modern-Fortran-code-1" href="#Using-modern-Fortran-code">1.2.3 Using modern Fortran code</a></li>
      <li><a id="toc-Using-C_002b_002b-code-1" href="#Using-C_002b_002b-code">1.2.4 Using C++ code</a></li>
      <li><a id="toc-C-standards-1" href="#C-standards">1.2.5 C standards</a></li>
      <li><a id="toc-Using-cmake-1" href="#Using-cmake">1.2.6 Using <code class="command">cmake</code></a></li>
    </ul></li>
    <li><a id="toc-Checking-and-building-packages-1" href="#Checking-and-building-packages">1.3 Checking and building packages</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Checking-packages-1" href="#Checking-packages">1.3.1 Checking packages</a></li>
      <li><a id="toc-Building-package-tarballs-1" href="#Building-package-tarballs">1.3.2 Building package tarballs</a></li>
      <li><a id="toc-Building-binary-packages-1" href="#Building-binary-packages">1.3.3 Building binary packages</a></li>
    </ul></li>
    <li><a id="toc-Writing-package-vignettes-1" href="#Writing-package-vignettes">1.4 Writing package vignettes</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Encodings-and-vignettes-1" href="#Encodings-and-vignettes">1.4.1 Encodings and vignettes</a></li>
      <li><a id="toc-Non_002dSweave-vignettes-1" href="#Non_002dSweave-vignettes">1.4.2 Non-Sweave vignettes</a></li>
    </ul></li>
    <li><a id="toc-Package-namespaces-1" href="#Package-namespaces">1.5 Package namespaces</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Specifying-imports-and-exports-1" href="#Specifying-imports-and-exports">1.5.1 Specifying imports and exports</a></li>
      <li><a id="toc-Registering-S3-methods-1" href="#Registering-S3-methods">1.5.2 Registering S3 methods</a></li>
      <li><a id="toc-Load-hooks-1" href="#Load-hooks">1.5.3 Load hooks</a></li>
      <li><a id="toc-useDynLib-1" href="#useDynLib">1.5.4 <code class="code">useDynLib</code></a></li>
      <li><a id="toc-An-example-1" href="#An-example">1.5.5 An example</a></li>
      <li><a id="toc-Namespaces-with-S4-classes-and-methods-1" href="#Namespaces-with-S4-classes-and-methods">1.5.6 Namespaces with S4 classes and methods</a></li>
    </ul></li>
    <li><a id="toc-Writing-portable-packages-1" href="#Writing-portable-packages">1.6 Writing portable packages</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-PDF-size-1" href="#PDF-size">1.6.1 PDF size</a></li>
      <li><a id="toc-Check-timing-1" href="#Check-timing">1.6.2 Check timing</a></li>
      <li><a id="toc-Encoding-issues-1" href="#Encoding-issues">1.6.3 Encoding issues</a></li>
      <li><a id="toc-Portable-C-and-C_002b_002b-code-1" href="#Portable-C-and-C_002b_002b-code">1.6.4 Portable C and C++ code</a>
      <ul class="toc-numbered-mark">
        <li><a id="toc-Common-symbols-1" href="#Common-symbols">1.6.4.1 Common symbols</a></li>
        <li><a id="toc-C_002b_002b17-issues-1" href="#C_002b_002b17-issues">1.6.4.2 C++17 issues</a></li>
      </ul></li>
      <li><a id="toc-Portable-Fortran-code-1" href="#Portable-Fortran-code">1.6.5 Portable Fortran code</a></li>
      <li><a id="toc-Binary-distribution-1" href="#Binary-distribution">1.6.6 Binary distribution</a></li>
    </ul></li>
    <li><a id="toc-Diagnostic-messages-1" href="#Diagnostic-messages">1.7 Diagnostic messages</a></li>
    <li><a id="toc-Internationalization-1" href="#Internationalization">1.8 Internationalization</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-C_002dlevel-messages-1" href="#C_002dlevel-messages">1.8.1 C-level messages</a></li>
      <li><a id="toc-R-messages-1" href="#R-messages">1.8.2 R messages</a></li>
      <li><a id="toc-Preparing-translations-1" href="#Preparing-translations">1.8.3 Preparing translations</a></li>
    </ul></li>
    <li><a id="toc-CITATION-files-1" href="#CITATION-files">1.9 CITATION files</a></li>
    <li><a id="toc-Package-types-1" href="#Package-types">1.10 Package types</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Frontend-1" href="#Frontend">1.10.1 Frontend</a></li>
    </ul></li>
    <li><a id="toc-Services-1" href="#Services">1.11 Services</a></li>
  </ul></li>
  <li><a id="toc-Writing-R-documentation-files-1" href="#Writing-R-documentation-files">2 Writing R documentation files</a>
  <ul class="toc-numbered-mark">
    <li><a id="toc-Rd-format-1" href="#Rd-format">2.1 Rd format</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Documenting-functions-1" href="#Documenting-functions">2.1.1 Documenting functions</a></li>
      <li><a id="toc-Documenting-data-sets-1" href="#Documenting-data-sets">2.1.2 Documenting data sets</a></li>
      <li><a id="toc-Documenting-S4-classes-and-methods-1" href="#Documenting-S4-classes-and-methods">2.1.3 Documenting S4 classes and methods</a></li>
      <li><a id="toc-Documenting-packages-1" href="#Documenting-packages">2.1.4 Documenting packages</a></li>
    </ul></li>
    <li><a id="toc-Sectioning-1" href="#Sectioning">2.2 Sectioning</a></li>
    <li><a id="toc-Marking-text-1" href="#Marking-text">2.3 Marking text</a></li>
    <li><a id="toc-Lists-and-tables-1" href="#Lists-and-tables">2.4 Lists and tables</a></li>
    <li><a id="toc-Cross_002dreferences-1" href="#Cross_002dreferences">2.5 Cross-references</a></li>
    <li><a id="toc-Mathematics-1" href="#Mathematics">2.6 Mathematics</a></li>
    <li><a id="toc-Figures-1" href="#Figures">2.7 Figures</a></li>
    <li><a id="toc-Insertions-1" href="#Insertions">2.8 Insertions</a></li>
    <li><a id="toc-Indices-1" href="#Indices">2.9 Indices</a></li>
    <li><a id="toc-Platform_002dspecific-documentation" href="#Platform_002dspecific-sections">2.10 Platform-specific documentation</a></li>
    <li><a id="toc-Conditional-text-1" href="#Conditional-text">2.11 Conditional text</a></li>
    <li><a id="toc-Dynamic-pages-1" href="#Dynamic-pages">2.12 Dynamic pages</a></li>
    <li><a id="toc-User_002ddefined-macros-1" href="#User_002ddefined-macros">2.13 User-defined macros</a></li>
    <li><a id="toc-Encoding-1" href="#Encoding">2.14 Encoding</a></li>
    <li><a id="toc-Processing-documentation-files-1" href="#Processing-documentation-files">2.15 Processing documentation files</a></li>
    <li><a id="toc-Editing-Rd-files-1" href="#Editing-Rd-files">2.16 Editing Rd files</a></li>
  </ul></li>
  <li><a id="toc-Tidying-and-profiling-R-code-1" href="#Tidying-and-profiling-R-code">3 Tidying and profiling R code</a>
  <ul class="toc-numbered-mark">
    <li><a id="toc-Tidying-R-code-1" href="#Tidying-R-code">3.1 Tidying R code</a></li>
    <li><a id="toc-Profiling-R-code-for-speed-1" href="#Profiling-R-code-for-speed">3.2 Profiling R code for speed</a></li>
    <li><a id="toc-Profiling-R-code-for-memory-use-1" href="#Profiling-R-code-for-memory-use">3.3 Profiling R code for memory use</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Memory-statistics-from-Rprof-1" href="#Memory-statistics-from-Rprof">3.3.1 Memory statistics from <code class="code">Rprof</code></a></li>
      <li><a id="toc-Tracking-memory-allocations-1" href="#Tracking-memory-allocations">3.3.2 Tracking memory allocations</a></li>
      <li><a id="toc-Tracing-copies-of-an-object-1" href="#Tracing-copies-of-an-object">3.3.3 Tracing copies of an object</a></li>
    </ul></li>
    <li><a id="toc-Profiling-compiled-code-1" href="#Profiling-compiled-code">3.4 Profiling compiled code</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Profiling-on-Linux" href="#Profilong-on-Linux">3.4.1 Profiling on Linux</a>
      <ul class="toc-numbered-mark">
        <li><a id="toc-perf" href="#perf">3.4.1.1 <code class="command">perf</code></a></li>
        <li><a id="toc-oprofile-and-operf" href="#oprofile-and-operf">3.4.1.2 <code class="command">oprofile</code> and <code class="command">operf</code></a></li>
        <li><a id="toc-sprof" href="#sprof">3.4.1.3 <code class="command">sprof</code></a></li>
      </ul></li>
      <li><a id="toc-Profiling-on-macOS-1" href="#Profiling-on-macOS">3.4.2 Profiling on macOS</a></li>
      <li><a id="toc-Profiling-on-Windows-1" href="#Profiling-on-Windows">3.4.3 Profiling on Windows</a></li>
    </ul></li>
  </ul></li>
  <li><a id="toc-Debugging-1" href="#Debugging">4 Debugging</a>
  <ul class="toc-numbered-mark">
    <li><a id="toc-Browsing-1" href="#Browsing">4.1 Browsing</a></li>
    <li><a id="toc-Debugging-R-code-1" href="#Debugging-R-code">4.2 Debugging R code</a></li>
    <li><a id="toc-Checking-memory-access-1" href="#Checking-memory-access">4.3 Checking memory access</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Using-gctorture-1" href="#Using-gctorture">4.3.1 Using <code class="code">gctorture</code></a></li>
      <li><a id="toc-Using-Valgrind" href="#Using-valgrind">4.3.2 Using Valgrind</a></li>
      <li><a id="toc-Using-the-Address-Sanitizer" href="#Using-Address-Sanitizer">4.3.3 Using the Address Sanitizer</a>
      <ul class="toc-numbered-mark">
        <li><a id="toc-Using-the-Leak-Sanitizer" href="#Using-Leak-Sanitizer">4.3.3.1 Using the Leak Sanitizer</a></li>
      </ul></li>
      <li><a id="toc-Using-the-Undefined-Behaviour-Sanitizer" href="#Using-Undefined-Behaviour-Sanitizer">4.3.4 Using the Undefined Behaviour Sanitizer</a></li>
      <li><a id="toc-Other-analyses-with-_0060clang_0027-1" href="#Other-analyses-with-_0060clang_0027">4.3.5 Other analyses with &lsquo;clang&rsquo;</a></li>
      <li><a id="toc-Other-analyses-with-_0060gcc_0027-1" href="#Other-analyses-with-_0060gcc_0027">4.3.6 Other analyses with &lsquo;gcc&rsquo;</a></li>
      <li><a id="toc-Using-_0060Dr_002e-Memory_0027-1" href="#Using-_0060Dr_002e-Memory_0027">4.3.7 Using &lsquo;Dr. Memory&rsquo;</a></li>
      <li><a id="toc-Fortran-array-bounds-checking-1" href="#Fortran-array-bounds-checking">4.3.8 Fortran array bounds checking</a></li>
    </ul></li>
    <li><a id="toc-Debugging-compiled-code-1" href="#Debugging-compiled-code">4.4 Debugging compiled code</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Finding-entry-points-in-dynamically-loaded-code" href="#Finding-entry-points">4.4.1 Finding entry points in dynamically loaded code</a></li>
      <li><a id="toc-Inspecting-R-objects-when-debugging" href="#Inspecting-R-objects">4.4.2 Inspecting R objects when debugging</a></li>
      <li><a id="toc-Debugging-on-macOS-1" href="#Debugging-on-macOS">4.4.3 Debugging on macOS</a></li>
    </ul></li>
    <li><a id="toc-Using-Link_002dtime-Optimization-1" href="#Using-Link_002dtime-Optimization">4.5 Using Link-time Optimization</a></li>
  </ul></li>
  <li><a id="toc-System-and-foreign-language-interfaces-1" href="#System-and-foreign-language-interfaces">5 System and foreign language interfaces</a>
  <ul class="toc-numbered-mark">
    <li><a id="toc-Operating-system-access-1" href="#Operating-system-access">5.1 Operating system access</a></li>
    <li><a id="toc-Interface-functions-_002eC-and-_002eFortran-1" href="#Interface-functions-_002eC-and-_002eFortran">5.2 Interface functions <code class="code">.C</code> and <code class="code">.Fortran</code></a></li>
    <li><a id="toc-dyn_002eload-and-dyn_002eunload-1" href="#dyn_002eload-and-dyn_002eunload">5.3 <code class="code">dyn.load</code> and <code class="code">dyn.unload</code></a></li>
    <li><a id="toc-Registering-native-routines-1" href="#Registering-native-routines">5.4 Registering native routines</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Speed-considerations-1" href="#Speed-considerations">5.4.1 Speed considerations</a></li>
      <li><a id="toc-Example_003a-converting-a-package-to-use-registration" href="#Converting-a-package-to-use-registration">5.4.2 Example: converting a package to use registration</a></li>
      <li><a id="toc-Linking-to-native-routines-in-other-packages-1" href="#Linking-to-native-routines-in-other-packages">5.4.3 Linking to native routines in other packages</a></li>
    </ul></li>
    <li><a id="toc-Creating-shared-objects-1" href="#Creating-shared-objects">5.5 Creating shared objects</a></li>
    <li><a id="toc-Interfacing-C_002b_002b-code-1" href="#Interfacing-C_002b_002b-code">5.6 Interfacing C++ code</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-External-C_002b_002b-code" href="#External-C_002b_002b-code">5.6.1 External C++ code</a></li>
    </ul></li>
    <li><a id="toc-Fortran-I_002fO-1" href="#Fortran-I_002fO">5.7 Fortran I/O</a></li>
    <li><a id="toc-Linking-to-other-packages-1" href="#Linking-to-other-packages">5.8 Linking to other packages</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Unix_002dalikes-1" href="#Unix_002dalikes">5.8.1 Unix-alikes</a></li>
      <li><a id="toc-Windows-1" href="#Windows">5.8.2 Windows</a></li>
    </ul></li>
    <li><a id="toc-Handling-R-objects-in-C-1" href="#Handling-R-objects-in-C">5.9 Handling R objects in C</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Handling-the-effects-of-garbage-collection" href="#Garbage-Collection">5.9.1 Handling the effects of garbage collection</a></li>
      <li><a id="toc-Allocating-storage-1" href="#Allocating-storage">5.9.2 Allocating storage</a></li>
      <li><a id="toc-Details-of-R-types-1" href="#Details-of-R-types">5.9.3 Details of R types</a></li>
      <li><a id="toc-Attributes-1" href="#Attributes">5.9.4 Attributes</a></li>
      <li><a id="toc-Classes-1" href="#Classes">5.9.5 Classes</a></li>
      <li><a id="toc-Handling-lists-1" href="#Handling-lists">5.9.6 Handling lists</a></li>
      <li><a id="toc-Handling-character-data-1" href="#Handling-character-data">5.9.7 Handling character data</a></li>
      <li><a id="toc-Finding-and-setting-variables-1" href="#Finding-and-setting-variables">5.9.8 Finding and setting variables</a></li>
      <li><a id="toc-Some-convenience-functions-1" href="#Some-convenience-functions">5.9.9 Some convenience functions</a>
      <ul class="toc-numbered-mark">
        <li><a id="toc-Semi_002dinternal-convenience-functions-1" href="#Semi_002dinternal-convenience-functions">5.9.9.1 Semi-internal convenience functions</a></li>
      </ul></li>
      <li><a id="toc-Named-objects-and-copying-1" href="#Named-objects-and-copying">5.9.10 Named objects and copying</a></li>
    </ul></li>
    <li><a id="toc-Interface-functions-_002eCall-and-_002eExternal-1" href="#Interface-functions-_002eCall-and-_002eExternal">5.10 Interface functions <code class="code">.Call</code> and <code class="code">.External</code></a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Calling-_002eCall-1" href="#Calling-_002eCall">5.10.1 Calling <code class="code">.Call</code></a></li>
      <li><a id="toc-Calling-_002eExternal-1" href="#Calling-_002eExternal">5.10.2 Calling <code class="code">.External</code></a></li>
      <li><a id="toc-Missing-and-special-values-1" href="#Missing-and-special-values">5.10.3 Missing and special values</a></li>
    </ul></li>
    <li><a id="toc-Evaluating-R-expressions-from-C-1" href="#Evaluating-R-expressions-from-C">5.11 Evaluating R expressions from C</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Zero_002dfinding-1" href="#Zero_002dfinding">5.11.1 Zero-finding</a></li>
      <li><a id="toc-Calculating-numerical-derivatives-1" href="#Calculating-numerical-derivatives">5.11.2 Calculating numerical derivatives</a></li>
    </ul></li>
    <li><a id="toc-Parsing-R-code-from-C-1" href="#Parsing-R-code-from-C">5.12 Parsing R code from C</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Accessing-source-references-1" href="#Accessing-source-references">5.12.1 Accessing source references</a></li>
    </ul></li>
    <li><a id="toc-External-pointers-and-weak-references-1" href="#External-pointers-and-weak-references">5.13 External pointers and weak references</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-An-example-2" href="#An-external-pointer-example">5.13.1 An example</a></li>
    </ul></li>
    <li><a id="toc-Vector-accessor-functions-1" href="#Vector-accessor-functions">5.14 Vector accessor functions</a></li>
    <li><a id="toc-Character-encoding-issues-1" href="#Character-encoding-issues">5.15 Character encoding issues</a></li>
  </ul></li>
  <li><a id="toc-The-R-API_003a-entry-points-for-C-code" href="#The-R-API">6 The R <abbr class="acronym">API</abbr>: entry points for C code</a>
  <ul class="toc-numbered-mark">
    <li><a id="toc-Memory-allocation-1" href="#Memory-allocation">6.1 Memory allocation</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Transient-storage-allocation-1" href="#Transient-storage-allocation">6.1.1 Transient storage allocation</a></li>
      <li><a id="toc-User_002dcontrolled-memory-1" href="#User_002dcontrolled-memory">6.1.2 User-controlled memory</a></li>
    </ul></li>
    <li><a id="toc-Error-signaling-1" href="#Error-signaling">6.2 Error signaling</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Error-signaling-from-Fortran-1" href="#Error-signaling-from-Fortran">6.2.1 Error signaling from Fortran</a></li>
    </ul></li>
    <li><a id="toc-Random-number-generation" href="#Random-numbers">6.3 Random number generation</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Random_002dnumber-generation-from-Fortran-1" href="#Random_002dnumber-generation-from-Fortran">6.3.1 Random-number generation from Fortran</a></li>
    </ul></li>
    <li><a id="toc-Missing-and-IEEE-special-values" href="#Missing-and-IEEE-values">6.4 Missing and <abbr class="acronym">IEEE</abbr> special values</a></li>
    <li><a id="toc-Printing-1" href="#Printing">6.5 Printing</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Printing-from-Fortran-1" href="#Printing-from-Fortran">6.5.1 Printing from Fortran</a></li>
    </ul></li>
    <li><a id="toc-Calling-C-from-Fortran-and-vice-versa-1" href="#Calling-C-from-Fortran-and-vice-versa">6.6 Calling C from Fortran and vice versa</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Fortran-character-strings-1" href="#Fortran-character-strings">6.6.1 Fortran character strings</a></li>
      <li><a id="toc-Fortran-LOGICAL-1" href="#Fortran-LOGICAL">6.6.2 Fortran LOGICAL</a></li>
      <li><a id="toc-Passing-functions-1" href="#Passing-functions">6.6.3 Passing functions</a></li>
    </ul></li>
    <li><a id="toc-Numerical-analysis-subroutines-1" href="#Numerical-analysis-subroutines">6.7 Numerical analysis subroutines</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Distribution-functions-1" href="#Distribution-functions">6.7.1 Distribution functions</a></li>
      <li><a id="toc-Mathematical-functions-1" href="#Mathematical-functions">6.7.2 Mathematical functions</a></li>
      <li><a id="toc-Numerical-Utilities-1" href="#Numerical-Utilities">6.7.3 Numerical Utilities</a></li>
      <li><a id="toc-Mathematical-constants-1" href="#Mathematical-constants">6.7.4 Mathematical constants</a></li>
    </ul></li>
    <li><a id="toc-Optimization-1" href="#Optimization">6.8 Optimization</a></li>
    <li><a id="toc-Integration-1" href="#Integration">6.9 Integration</a></li>
    <li><a id="toc-Utility-functions-1" href="#Utility-functions">6.10 Utility functions</a></li>
    <li><a id="toc-Re_002dencoding-1" href="#Re_002dencoding">6.11 Re-encoding</a></li>
    <li><a id="toc-Condition-handling-and-cleanup-code-1" href="#Condition-handling-and-cleanup-code">6.12 Condition handling and cleanup code</a></li>
    <li><a id="toc-Allowing-interrupts-1" href="#Allowing-interrupts">6.13 Allowing interrupts</a></li>
    <li><a id="toc-Platform-and-version-information-1" href="#Platform-and-version-information">6.14 Platform and version information</a></li>
    <li><a id="toc-Inlining-C-functions-1" href="#Inlining-C-functions">6.15 Inlining C functions</a></li>
    <li><a id="toc-Controlling-visibility-1" href="#Controlling-visibility">6.16 Controlling visibility</a></li>
    <li><a id="toc-Using-these-functions-in-your-own-C-code" href="#Standalone-Mathlib">6.17 Using these functions in your own C code</a></li>
    <li><a id="toc-Organization-of-header-files-1" href="#Organization-of-header-files">6.18 Organization of header files</a></li>
  </ul></li>
  <li><a id="toc-Generic-functions-and-methods-1" href="#Generic-functions-and-methods">7 Generic functions and methods</a>
  <ul class="toc-numbered-mark">
    <li><a id="toc-Adding-new-generics-1" href="#Adding-new-generics">7.1 Adding new generics</a></li>
  </ul></li>
  <li><a id="toc-Linking-GUIs-and-other-front_002dends-to-R-1" href="#Linking-GUIs-and-other-front_002dends-to-R">8 Linking GUIs and other front-ends to R</a>
  <ul class="toc-numbered-mark">
    <li><a id="toc-Embedding-R-under-Unix_002dalikes-1" href="#Embedding-R-under-Unix_002dalikes">8.1 Embedding R under Unix-alikes</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Compiling-against-the-R-library-1" href="#Compiling-against-the-R-library">8.1.1 Compiling against the R library</a></li>
      <li><a id="toc-Setting-R-callbacks-1" href="#Setting-R-callbacks">8.1.2 Setting R callbacks</a></li>
      <li><a id="toc-Registering-symbols-1" href="#Registering-symbols">8.1.3 Registering symbols</a></li>
      <li><a id="toc-Meshing-event-loops-1" href="#Meshing-event-loops">8.1.4 Meshing event loops</a></li>
      <li><a id="toc-Threading-issues-1" href="#Threading-issues">8.1.5 Threading issues</a></li>
    </ul></li>
    <li><a id="toc-Embedding-R-under-Windows-1" href="#Embedding-R-under-Windows">8.2 Embedding R under Windows</a>
    <ul class="toc-numbered-mark">
      <li><a id="toc-Using-_0028D_0029COM-1" href="#Using-_0028D_0029COM">8.2.1 Using (D)COM</a></li>
      <li><a id="toc-Calling-R_002edll-directly-1" href="#Calling-R_002edll-directly">8.2.2 Calling <samp class="file">R.dll</samp> directly</a></li>
      <li><a id="toc-Finding-R_005fHOME-1" href="#Finding-R_005fHOME">8.2.3 Finding R_HOME</a></li>
    </ul></li>
  </ul></li>
  <li><a id="toc-Function-and-variable-index-1" href="#Function-and-variable-index" rel="index">Function and variable index</a></li>
  <li><a id="toc-Concept-index-1" href="#Concept-index" rel="index">Concept index</a></li>
</ul>
</div>
</div>
<hr>
<div class="unnumbered-level-extent" id="Acknowledgements">
<div class="nav-panel">
<p>
Next: <a href="#Creating-R-packages" accesskey="n" rel="next">Creating R packages</a>, Previous: <a href="#Top" accesskey="p" rel="prev">Writing R Extensions</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="unnumbered" id="Acknowledgements-1"><span>Acknowledgements<a class="copiable-link" href="#Acknowledgements-1"> &para;</a></span></h2>


<p>The contributions to early versions of this manual by Saikat DebRoy
(who wrote the first draft of a guide to using <code class="code">.Call</code> and
<code class="code">.External</code>) and Adrian Trapletti (who provided information on the
C++ interface) are gratefully acknowledged.
</p>
<hr>
</div>
<div class="chapter-level-extent" id="Creating-R-packages">
<div class="nav-panel">
<p>
Next: <a href="#Writing-R-documentation-files" accesskey="n" rel="next">Writing R documentation files</a>, Previous: <a href="#Acknowledgements" accesskey="p" rel="prev">Acknowledgements</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="chapter" id="Creating-R-packages-1"><span>1 Creating R packages<a class="copiable-link" href="#Creating-R-packages-1"> &para;</a></span></h2>
<a class="index-entry-id" id="index-Packages"></a>
<a class="index-entry-id" id="index-Creating-packages"></a>

<p>Packages provide a mechanism for loading optional code, data and
documentation as needed.  The R distribution itself includes about 30
packages.
</p>
<p>In the following, we assume that you know the <code class="code">library()</code> command,
including its <code class="code">lib.loc</code> argument, and we also assume basic
knowledge of the <code class="command">R CMD INSTALL</code> utility.  Otherwise, please
look at R&rsquo;s help pages on
</p>
<div class="example">
<pre class="example-preformatted">?library
?INSTALL
</pre></div>

<p>before reading on.
</p>
<p>For packages which contain code to be compiled, a computing environment
including a number of tools is assumed; the &ldquo;R Installation and
Administration&rdquo; manual describes what is needed for each OS.
</p>
<p>Once a source package is created, it must be installed by
the command <code class="code">R CMD INSTALL</code>.
See <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Add_002don-packages">Add-on-packages</a> in <cite class="cite">R Installation and Administration</cite>.
</p>

<p>Other types of extensions are supported (but rare): See <a class="xref" href="#Package-types">Package types</a>.
</p>
<p>Some notes on terminology complete this introduction.  These will help
with the reading of this manual, and also in describing concepts
accurately when asking for help.
</p>
<p>A <em class="emph">package</em> is a directory of files which extend R, a
<em class="emph">source package</em> (the master files of a package), or a tarball
containing the files of a source package, or an <em class="emph">installed</em>
package, the result of running <code class="command">R CMD INSTALL</code> on a source
package.  On some platforms (notably macOS and &lsquo;<samp class="samp">x86_64</samp>&rsquo; Windows)
there are also <em class="emph">binary packages</em>, a zip file or tarball containing
the files of an installed package which can be unpacked rather than
installing from sources.
</p>
<p>A package is <strong class="strong">not</strong><a class="footnote" id="DOCF1" href="#FOOT1"><sup>1</sup></a> a
<em class="emph">library</em>.  The latter is used in two senses in R documentation.
</p>
<ul class="itemize mark-bullet">
<li>A directory into which packages are installed, e.g.
<samp class="file">/usr/lib/R/library</samp>: in that sense it is sometimes referred to as
a <em class="emph">library directory</em> or <em class="emph">library tree</em> (since the library is
a directory which contains packages as directories, which themselves
contain directories).

</li><li>That used by the operating system, as a shared, dynamic or static
library or (especially on Windows) a DLL, where the second L stands for
&lsquo;library&rsquo;.  Installed packages may contain compiled code in what is
known on Unix-alikes as a <em class="emph">shared object</em> and on Windows as a DLL.
The concept of a <em class="emph">shared library</em> (<em class="emph">dynamic library</em> on macOS)
as a collection of compiled code to which a package might link is also
used, especially for R itself on some platforms. On most platforms
these concepts are interchangeable (shared objects and DLLs can both be
loaded into the R process and be linked against), but macOS
distinguishes between shared objects (extension <samp class="file">.so</samp>) and dynamic
libraries (extension <samp class="file">.dylib</samp>).

</li></ul>

<p>There are a number of well-defined operations on source packages.
</p>
<ul class="itemize mark-bullet">
<li>The most common is <em class="emph">installation</em> which takes a source package and
installs it in a library using <code class="command">R CMD INSTALL</code> or
<code class="code">install.packages</code>.

</li><li>Source packages can be <em class="emph">built</em>.  This involves taking a source
directory and creating a tarball ready for distribution, including
cleaning it up and creating PDF/<abbr class="acronym">HTML</abbr> documentation from any <em class="emph">vignettes</em>
it may contain.  Source packages (and most often tarballs) can be
<em class="emph">checked</em>, when a test installation is done and tested (including
running its examples); also, the contents of the package are tested in
various ways for consistency and portability.

</li><li><em class="emph">Compilation</em> is not a correct term for a package.  Installing a
source package which contains C, C++ or Fortran code will involve
compiling that code.  There is also the possibility of &lsquo;byte&rsquo; compiling
the R code in a package (using the facilities of package
<strong class="strong">compiler</strong>): nowadays this is enabled by default for all
packages. So <em class="emph">compiling</em> a package may come to mean byte-compiling
its R code.

</li><li>It used to be unambiguous to talk about <em class="emph">loading</em> an installed
package using <code class="code">library()</code>, but since the advent of package
namespaces this has been less clear: people now often talk about
<em class="emph">loading</em> the package&rsquo;s namespace and then <em class="emph">attaching</em> the
package so it becomes visible on the search path.  Function
<code class="code">library</code> performs both steps, but a package&rsquo;s namespace can be
loaded without the package being attached (for example by calls like
<code class="code">splines::ns</code>).

</li></ul>

<p>The concept of <em class="emph">lazy loading</em> of code or data is mentioned at
several points.  This is part of the installation, always selected for
R code but optional for data.  When used the R objects of the
package are created at installation time and stored in a database in the
<samp class="file">R</samp> directory of the installed package, being loaded into the
session at first use.  This makes the R session start up faster and
use less (virtual) memory.
(For technical details,
see <a data-manual="R-ints" href="https://cran.r-project.org/doc/manuals/R-ints.html#Lazy-loading">Lazy loading</a> in <cite class="cite">R Internals</cite>.)
</p>

<a class="index-entry-id" id="index-CRAN"></a>
<p><abbr class="acronym">CRAN</abbr> is a network of WWW sites holding the R distributions
and contributed code, especially R packages.  Users of R are
encouraged to join in the collaborative project and to submit their own
packages to <abbr class="acronym">CRAN</abbr>: current instructions are linked from
<a class="uref" href="https://CRAN.R-project.org/banner.shtml#submitting">https://CRAN.R-project.org/banner.shtml#submitting</a>.
</p>


<ul class="mini-toc">
<li><a href="#Package-structure" accesskey="1">Package structure</a></li>
<li><a href="#Configure-and-cleanup" accesskey="2">Configure and cleanup</a></li>
<li><a href="#Checking-and-building-packages" accesskey="3">Checking and building packages</a></li>
<li><a href="#Writing-package-vignettes" accesskey="4">Writing package vignettes</a></li>
<li><a href="#Package-namespaces" accesskey="5">Package namespaces</a></li>
<li><a href="#Writing-portable-packages" accesskey="6">Writing portable packages</a></li>
<li><a href="#Diagnostic-messages" accesskey="7">Diagnostic messages</a></li>
<li><a href="#Internationalization" accesskey="8">Internationalization</a></li>
<li><a href="#CITATION-files" accesskey="9">CITATION files</a></li>
<li><a href="#Package-types">Package types</a></li>
<li><a href="#Services">Services</a></li>
</ul>
<hr>
<div class="section-level-extent" id="Package-structure">
<div class="nav-panel">
<p>
Next: <a href="#Configure-and-cleanup" accesskey="n" rel="next">Configure and cleanup</a>, Previous: <a href="#Creating-R-packages" accesskey="p" rel="prev">Creating R packages</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Package-structure-1"><span>1.1 Package structure<a class="copiable-link" href="#Package-structure-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Package-structure"></a>

<p>The sources of an R package consist of a subdirectory containing the
files <samp class="file">DESCRIPTION</samp> and <samp class="file">NAMESPACE</samp>, and the subdirectories
<samp class="file">R</samp>, <samp class="file">data</samp>, <samp class="file">demo</samp>, <samp class="file">exec</samp>, <samp class="file">inst</samp>,
<samp class="file">man</samp>, <samp class="file">po</samp>, <samp class="file">src</samp>, <samp class="file">tests</samp>, <samp class="file">tools</samp> and
<samp class="file">vignettes</samp> (some of which can be missing, but which should not be
empty).  The package subdirectory may also contain files <samp class="file">INDEX</samp>,
<samp class="file">configure</samp>, <samp class="file">cleanup</samp>, <samp class="file">LICENSE</samp>, <samp class="file">LICENCE</samp> and
<samp class="file">NEWS</samp>.  Other files such as <samp class="file">INSTALL</samp> (for non-standard
installation instructions), <samp class="file">README</samp>/<samp class="file">README.md</samp><a class="footnote" id="DOCF2" href="#FOOT2"><sup>2</sup></a>, or <samp class="file">ChangeLog</samp> will be ignored by R, but may
be useful to end users.  The utility <code class="command">R CMD build</code> may add files
in a <samp class="file">build</samp> directory (but this should not be used for other
purposes).
</p>
<p>Except where specifically mentioned,<a class="footnote" id="DOCF3" href="#FOOT3"><sup>3</sup></a> packages should not contain
Unix-style &lsquo;hidden&rsquo; files/directories (that is, those whose name starts
with a dot).
</p>
<p>The <samp class="file">DESCRIPTION</samp> and <samp class="file">INDEX</samp> files are described in the
subsections below.  The <samp class="file">NAMESPACE</samp> file is described in the
section on <a class="ref" href="#Package-namespaces">Package namespaces</a>.
</p>
<a class="index-entry-id" id="index-configure-file"></a>
<a class="index-entry-id" id="index-cleanup-file"></a>

<p>The optional files <samp class="file">configure</samp> and <samp class="file">cleanup</samp> are (Bourne)
shell scripts which are, respectively, executed before and (if option
<samp class="option">--clean</samp> was given) after installation on Unix-alikes, see
<a class="ref" href="#Configure-and-cleanup">Configure and cleanup</a>.  The analogues on Windows are
<samp class="file">configure.win</samp> and <samp class="file">cleanup.win</samp>. Since R 4.2.0 on Windows,
<samp class="file">configure.ucrt</samp> and <samp class="file">cleanup.ucrt</samp> are supported and take
precedence over <samp class="file">configure.win</samp> and <samp class="file">cleanup.win</samp>. They can
hence be used to provide content specific to <abbr class="abbr">UCRT</abbr> or Rtools42 and newer, if needed,
but the support for <samp class="file">.ucrt</samp> files may be removed in future when
building packages from source on the older versions of R will no longer
be needed, and hence the files may be renamed back to <samp class="file">.win</samp>.
</p>
<p>For the conventions for files <samp class="file">NEWS</samp> and <samp class="file">ChangeLog</samp> in the
<abbr class="acronym">GNU</abbr> project see
<a class="uref" href="https://www.gnu.org/prep/standards/standards.html#Documentation">https://www.gnu.org/prep/standards/standards.html#Documentation</a>.
</p>
<p>The package subdirectory should be given the same name as the package.
Because some file systems (e.g., those on Windows and by default on
macOS) are not case-sensitive, to maintain portability it is strongly
recommended that case distinctions not be used to distinguish different
packages.  For example, if you have a package named <samp class="file">foo</samp>, do not
also create a package named <samp class="file">Foo</samp>.
</p>
<p>To ensure that file names are valid across file systems and supported
operating systems, the <abbr class="acronym">ASCII</abbr> control characters as well as the
characters &lsquo;<samp class="samp">&quot;</samp>&rsquo;, &lsquo;<samp class="samp">*</samp>&rsquo;, &lsquo;<samp class="samp">:</samp>&rsquo;, &lsquo;<samp class="samp">/</samp>&rsquo;, &lsquo;<samp class="samp">&lt;</samp>&rsquo;, &lsquo;<samp class="samp">&gt;</samp>&rsquo;,
&lsquo;<samp class="samp">?</samp>&rsquo;, &lsquo;<samp class="samp">\</samp>&rsquo;, and &lsquo;<samp class="samp">|</samp>&rsquo; are not allowed in file names.  In
addition, files with names &lsquo;<samp class="samp">con</samp>&rsquo;, &lsquo;<samp class="samp">prn</samp>&rsquo;, &lsquo;<samp class="samp">aux</samp>&rsquo;,
&lsquo;<samp class="samp">clock$</samp>&rsquo;, &lsquo;<samp class="samp">nul</samp>&rsquo;, &lsquo;<samp class="samp">com1</samp>&rsquo; to &lsquo;<samp class="samp">com9</samp>&rsquo;, and &lsquo;<samp class="samp">lpt1</samp>&rsquo;
to &lsquo;<samp class="samp">lpt9</samp>&rsquo; after conversion to lower case and stripping possible
&ldquo;extensions&rdquo; (e.g., &lsquo;<samp class="samp">lpt5.foo.bar</samp>&rsquo;), are disallowed.  Also, file
names in the same directory must not differ only by case (see the
previous paragraph).  In addition, the basenames of &lsquo;<samp class="samp">.Rd</samp>&rsquo; files may
be used in URLs and so must be <abbr class="acronym">ASCII</abbr> and not contain <code class="code">%</code>.
For maximal portability filenames should only contain only
<abbr class="acronym">ASCII</abbr> characters not excluded already (that is
<code class="code">A-Za-z0-9._!#$%&amp;+,;=@^(){}'[]</code> &mdash; we exclude space as many
utilities do not accept spaces in file paths): non-English alphabetic
characters cannot be guaranteed to be supported in all locales.  It
would be good practice to avoid the shell metacharacters
<code class="code">(){}'[]$~</code>: <code class="code">~</code> is also used as part of &lsquo;8.3&rsquo; filenames on
Windows.  In addition, packages are normally distributed as tarballs,
and these have a limit on path lengths: for maximal portability 100
bytes.
</p>
<p>A source package if possible should not contain binary executable files:
they are not portable, and a security risk if they are of the
appropriate architecture.  <code class="command">R CMD check</code> will warn about
them<a class="footnote" id="DOCF4" href="#FOOT4"><sup>4</sup></a> unless they are listed (one filepath per line) in a file
<samp class="file">BinaryFiles</samp> at the top level of the package.  Note that
<abbr class="acronym">CRAN</abbr> will not accept submissions containing binary files
even if they are listed.
</p>
<p>The R function <code class="code">package.skeleton</code> can help to create the
structure for a new package: see its help page for details.
</p>

<ul class="mini-toc">
<li><a href="#The-DESCRIPTION-file" accesskey="1">The <samp class="file">DESCRIPTION</samp> file</a></li>
<li><a href="#Licensing" accesskey="2">Licensing</a></li>
<li><a href="#Package-Dependencies" accesskey="3">Package Dependencies</a></li>
<li><a href="#The-INDEX-file" accesskey="4">The <samp class="file">INDEX</samp> file</a></li>
<li><a href="#Package-subdirectories" accesskey="5">Package subdirectories</a></li>
<li><a href="#Data-in-packages" accesskey="6">Data in packages</a></li>
<li><a href="#Non_002dR-scripts-in-packages" accesskey="7">Non-R scripts in packages</a></li>
<li><a href="#Specifying-URLs" accesskey="8">Specifying URLs</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="The-DESCRIPTION-file">
<div class="nav-panel">
<p>
Next: <a href="#Licensing" accesskey="n" rel="next">Licensing</a>, Previous: <a href="#Package-structure" accesskey="p" rel="prev">Package structure</a>, Up: <a href="#Package-structure" accesskey="u" rel="up">Package structure</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="The-DESCRIPTION-file-1"><span>1.1.1 The <samp class="file">DESCRIPTION</samp> file<a class="copiable-link" href="#The-DESCRIPTION-file-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-DESCRIPTION-file"></a>

<p>The <samp class="file">DESCRIPTION</samp> file contains basic information about the package
in the following format:
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example smallexample">
<pre class="example-preformatted">Package: pkgname
Version: 0.5-1
Date: 2015-01-01
Title: My First Collection of Functions
Authors@R: c(person(&quot;Joe&quot;, &quot;Developer&quot;, role = c(&quot;aut&quot;, &quot;cre&quot;),
                     email = &quot;[email protected]&quot;),
              person(&quot;Pat&quot;, &quot;Developer&quot;, role = &quot;aut&quot;),
              person(&quot;A.&quot;, &quot;User&quot;, role = &quot;ctb&quot;,
                     email = &quot;[email protected]&quot;))
Author: Joe Developer [aut, cre],
  Pat Developer [aut],
  A. User [ctb]
Maintainer: Joe Developer &lt;[email protected]&gt;
Depends: R (&gt;= 3.1.0), nlme
Suggests: MASS
Description: A (one paragraph) description of what
  the package does and why it may be useful.
License: GPL (&gt;= 2)
URL: https://www.r-project.org, http://www.another.url
BugReports: https://pkgname.bugtracker.url
</pre></div>
</td></tr></table>
</blockquote>

<p>The format is that of a version of a &lsquo;Debian Control File&rsquo; (see the help
for &lsquo;<samp class="samp">read.dcf</samp>&rsquo; and
<a class="uref" href="https://www.debian.org/doc/debian-policy/ch-controlfields.html">https://www.debian.org/doc/debian-policy/ch-controlfields.html</a>:
R does not require encoding in UTF-8 and does not support comments
starting with &lsquo;<samp class="samp">#</samp>&rsquo;).  Fields start with an <abbr class="acronym">ASCII</abbr> name
immediately followed by a colon: the value starts after the colon and a
space.  Continuation lines (for example, for descriptions longer than
one line) start with a space or tab.  Field names are case-sensitive:
all those used by R are capitalized.
</p>
<p>For maximal portability, the <samp class="file">DESCRIPTION</samp> file should be written
entirely in <abbr class="acronym">ASCII</abbr> &mdash; if this is not possible it must contain
an &lsquo;<samp class="samp">Encoding</samp>&rsquo; field (see below).
</p>
<p>Several optional fields take <em class="emph">logical values</em>: these can be
specified as &lsquo;<samp class="samp">yes</samp>&rsquo;, &lsquo;<samp class="samp">true</samp>&rsquo;, &lsquo;<samp class="samp">no</samp>&rsquo; or &lsquo;<samp class="samp">false</samp>&rsquo;:
capitalized values are also accepted.
</p>
<p>The &lsquo;<samp class="samp">Package</samp>&rsquo;, &lsquo;<samp class="samp">Version</samp>&rsquo;, &lsquo;<samp class="samp">License</samp>&rsquo;, &lsquo;<samp class="samp">Description</samp>&rsquo;,
&lsquo;<samp class="samp">Title</samp>&rsquo;, &lsquo;<samp class="samp">Author</samp>&rsquo;, and &lsquo;<samp class="samp">Maintainer</samp>&rsquo; fields are mandatory,
all other fields are optional.  Fields &lsquo;<samp class="samp">Author</samp>&rsquo; and
&lsquo;<samp class="samp">Maintainer</samp>&rsquo; can be auto-generated from &lsquo;<samp class="samp">Authors@R</samp>&rsquo;, and may
be omitted if the latter is provided: however if they are not
<abbr class="acronym">ASCII</abbr> we recommend that they are provided.
</p>
<p>The mandatory &lsquo;<samp class="samp">Package</samp>&rsquo; field gives the name of the package.  This
should contain only (<abbr class="acronym">ASCII</abbr>) letters, numbers and dot, have at
least two characters and start with a letter and not end in a dot.  If
it needs explaining, this should be done in the &lsquo;<samp class="samp">Description</samp>&rsquo; field
(and not the &lsquo;<samp class="samp">Title</samp>&rsquo; field).
</p>
<p>The mandatory &lsquo;<samp class="samp">Version</samp>&rsquo; field gives the version of the package.
This is a sequence of at least <em class="emph">two</em> (and usually three)
non-negative integers separated by single &lsquo;<samp class="samp">.</samp>&rsquo; or &lsquo;<samp class="samp">-</samp>&rsquo;
characters.  The canonical form is as shown in the example, and a
version such as &lsquo;<samp class="samp">0.01</samp>&rsquo; or &lsquo;<samp class="samp">0.01.0</samp>&rsquo; will be handled as if it
were &lsquo;<samp class="samp">0.1-0</samp>&rsquo;.  It is <strong class="strong">not</strong> a decimal number, so for example
<code class="code">0.9 &lt; 0.75</code> since <code class="code">9 &lt; 75</code>.
</p>
<p>The mandatory &lsquo;<samp class="samp">License</samp>&rsquo; field is discussed in the next subsection.
</p>
<p>The mandatory &lsquo;<samp class="samp">Title</samp>&rsquo; field should give a <em class="emph">short</em> description
of the package.  Some package listings may truncate the title to 65
characters.  It should use <em class="emph">title case</em> (that is, use capitals for
the principal words: <code class="code">tools::toTitleCase</code> can help you with this),
not use any markup, not have any continuation lines, and not end in a
period (unless part of &hellip;).  Do not repeat the package name: it is
often used prefixed by the name.  Refer to other packages and external
software in single quotes, and to book titles (and similar) in double
quotes.
</p>
<p>The mandatory &lsquo;<samp class="samp">Description</samp>&rsquo; field should give a
<em class="emph">comprehensive</em> description of what the package does.  One can use
several (complete) sentences, but only one paragraph. It should be
intelligible to all the intended readership (e.g. for a <abbr class="acronym">CRAN</abbr>
package to all <abbr class="acronym">CRAN</abbr> users).  It is good practice not to start
with the package name, &lsquo;This package&rsquo; or similar.  As with the
&lsquo;<samp class="samp">Title</samp>&rsquo; field, double quotes should be used for quotations
(including titles of books and articles), and single quotes for
non-English usage, including names of other packages and external
software.  This field should also be used for explaining the package
name if necessary.  URLs should be enclosed in angle brackets, e.g.
&lsquo;<samp class="samp">&lt;https://www.r-project.org&gt;</samp>&rsquo;: see also <a class="ref" href="#Specifying-URLs">Specifying URLs</a>.
</p>
<p>The mandatory &lsquo;<samp class="samp">Author</samp>&rsquo; field describes who wrote <em class="emph">the
package</em>.  It is a plain text field intended for human readers, but not
for automatic processing (such as extracting the email addresses of all
listed contributors: for that use &lsquo;<samp class="samp">Authors@R</samp>&rsquo;).  Note that all
significant contributors must be included: if you wrote an R wrapper
for the work of others included in the <samp class="file">src</samp> directory, you are not
the sole (and maybe not even the main) author.
</p>
<p>The mandatory &lsquo;<samp class="samp">Maintainer</samp>&rsquo; field should give a <em class="emph">single</em> name
followed by a <em class="emph">valid</em> (RFC 2822) email address in angle brackets.  It
should not end in a period or comma.  This field is what is reported by
the <code class="code">maintainer</code> function and used by <code class="code">bug.report</code>.  For a
<abbr class="acronym">CRAN</abbr> package it should be a <em class="emph">person</em>, not a mailing list
and not a corporate entity: do ensure that it is valid and will remain
valid for the lifetime of the package.
</p>
<p>Note that the <em class="emph">display name</em> (the part before the address in angle
brackets) should be enclosed in double quotes if it contains
non-alphanumeric characters such as comma or period.  (The current
standard, RFC 5322, allows periods but RFC 2822 did not.)
</p>
<p>Both &lsquo;<samp class="samp">Author</samp>&rsquo; and &lsquo;<samp class="samp">Maintainer</samp>&rsquo; fields can be omitted if a
suitable &lsquo;<samp class="samp">Authors@R</samp>&rsquo; field is given.  This field can be used to
provide a refined and machine-readable description of the package
&ldquo;authors&rdquo; (in particular specifying their precise <em class="emph">roles</em>),
<em class="emph">via</em> suitable R code. It should create an object of class
<code class="code">&quot;person&quot;</code>, by either a call to <code class="code">person</code> or a series of calls
(one per &ldquo;author&rdquo;) concatenated by <code class="code">c()</code>: see the example
<samp class="file">DESCRIPTION</samp> file above.  The roles can include &lsquo;<samp class="samp">&quot;aut&quot;</samp>&rsquo;
(author) for full authors, &lsquo;<samp class="samp">&quot;cre&quot;</samp>&rsquo; (creator) for the package
maintainer, and &lsquo;<samp class="samp">&quot;ctb&quot;</samp>&rsquo; (contributor) for other contributors,
&lsquo;<samp class="samp">&quot;cph&quot;</samp>&rsquo; (copyright holder, which should be the legal name for an
institution or corporate body), among others.  See <code class="code">?person</code> for
more information.  Note that no role is assumed by default.
Auto-generated package citation information takes advantage of this
specification. The &lsquo;<samp class="samp">Author</samp>&rsquo; and &lsquo;<samp class="samp">Maintainer</samp>&rsquo; fields are
auto-generated from it if needed when building<a class="footnote" id="DOCF5" href="#FOOT5"><sup>5</sup></a>  or installing.
</p>
<a class="index-entry-id" id="index-COPYRIGHTS"></a>
<p>An optional &lsquo;<samp class="samp">Copyright</samp>&rsquo; field can be used where the copyright
holder(s) are not the authors.  If necessary, this can refer to an
installed file: the convention is to use file <samp class="file">inst/COPYRIGHTS</samp>.
</p>
<p>The optional &lsquo;<samp class="samp">Date</samp>&rsquo; field gives the <em class="emph">release date</em> of the
current version of the package.  It is strongly recommended<a class="footnote" id="DOCF6" href="#FOOT6"><sup>6</sup></a> to use the &lsquo;<samp class="samp">yyyy-mm-dd</samp>&rsquo; format conforming to the ISO
8601 standard.
</p>
<p>The &lsquo;<samp class="samp">Depends</samp>&rsquo;, &lsquo;<samp class="samp">Imports</samp>&rsquo;, &lsquo;<samp class="samp">Suggests</samp>&rsquo;, &lsquo;<samp class="samp">Enhances</samp>&rsquo;,
&lsquo;<samp class="samp">LinkingTo</samp>&rsquo; and &lsquo;<samp class="samp">Additional_repositories</samp>&rsquo; fields are discussed
in a later subsection.
</p>
<p>Dependencies external to the R system should be listed in the
&lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field, possibly amplified in a separate
<samp class="file">README</samp> file.  This includes specifying a non-default C++ standard
and the need for GNU <code class="command">make</code>.
</p>
<p>The &lsquo;<samp class="samp">URL</samp>&rsquo; field may give a list of <abbr class="acronym">URL</abbr>s
separated by commas or whitespace, for example the homepage of the
author or a page where additional material describing the software can
be found.  These <abbr class="acronym">URL</abbr>s are converted to active hyperlinks in
<abbr class="acronym">CRAN</abbr> package listings.  See <a class="xref" href="#Specifying-URLs">Specifying URLs</a>.
</p>
<p>The &lsquo;<samp class="samp">BugReports</samp>&rsquo; field may contain a single <abbr class="acronym">URL</abbr> to which
bug reports about the package should be submitted.  This <abbr class="acronym">URL</abbr>
will be used by <code class="code">bug.report</code> instead of sending an email to the
maintainer.  A browser is opened for a &lsquo;<samp class="samp">http://</samp>&rsquo; or &lsquo;<samp class="samp">https://</samp>&rsquo;
<abbr class="acronym">URL</abbr>.  To specify another email address for bug reports, use
&lsquo;<samp class="samp">Contact</samp>&rsquo; instead: however <code class="code">bug.report</code> will try to extract an
email address (preferably from a &lsquo;<samp class="samp">mailto:</samp>&rsquo; URL or enclosed in angle
brackets) from &lsquo;<samp class="samp">BugReports</samp>&rsquo;.
</p>
<p>Base and recommended packages (i.e., packages contained in the R
source distribution or available from <abbr class="acronym">CRAN</abbr> and recommended to
be included in every binary distribution of R) have a &lsquo;<samp class="samp">Priority</samp>&rsquo;
field with value &lsquo;<samp class="samp">base</samp>&rsquo; or &lsquo;<samp class="samp">recommended</samp>&rsquo;, respectively.  These
priorities must not be used by other packages.
</p>
<p>A &lsquo;<samp class="samp">Collate</samp>&rsquo; field can be used for controlling the collation order
for the R code files in a package when these are processed for
package installation.  The default is to collate according to the
&lsquo;<samp class="samp">C</samp>&rsquo; locale.  If present, the collate specification must list
<em class="emph">all</em> R code files in the package (taking possible OS-specific
subdirectories into account, see <a class="ref" href="#Package-subdirectories">Package subdirectories</a>) as a
whitespace separated list of file paths relative to the <samp class="file">R</samp>
subdirectory.
Paths containing white space or quotes need to be quoted.  An
OS-specific collation field (&lsquo;<samp class="samp">Collate.unix</samp>&rsquo; or
&lsquo;<samp class="samp">Collate.windows</samp>&rsquo;) will be used in preference to &lsquo;<samp class="samp">Collate</samp>&rsquo;.
</p>
<p>The &lsquo;<samp class="samp">LazyData</samp>&rsquo; logical field controls whether the R datasets use
lazy-loading.  A &lsquo;<samp class="samp">LazyLoad</samp>&rsquo; field was used in versions prior to
2.14.0, but now is ignored.
</p>
<p>The &lsquo;<samp class="samp">KeepSource</samp>&rsquo; logical field controls if the package code is sourced
using <code class="code">keep.source = TRUE</code> or <code class="code">FALSE</code>: it might be needed
exceptionally for a package designed to always be used with
<code class="code">keep.source = TRUE</code>.
</p>
<p>The &lsquo;<samp class="samp">ByteCompile</samp>&rsquo; logical field controls if the package R code is to
be byte-compiled on installation: the default is to byte-compile.  This
can be overridden by installing with flag <samp class="option">--no-byte-compile</samp>.
</p>
<p>The &lsquo;<samp class="samp">UseLTO</samp>&rsquo; logical field is used to indicate if source code in
the package<a class="footnote" id="DOCF7" href="#FOOT7"><sup>7</sup></a>  is to be
compiled with Link-Time Optimization (see <a class="pxref" href="#Using-Link_002dtime-Optimization">Using Link-time Optimization</a>) if R was installed with <samp class="option">--enable-lto</samp> (default
true) or <samp class="option">--enable-lto=R</samp> (default false) (or on
Windows<a class="footnote" id="DOCF8" href="#FOOT8"><sup>8</sup></a> if
<code class="code">LTO_OPT</code> is set in <samp class="file">MkRules</samp>). This can be overridden by the
flags <samp class="option">--use-LTO</samp> and <samp class="option">--no-use-LTO</samp>.  <abbr class="abbr">LTO</abbr> is said to give
most size and performance improvements for large and complex (heavily
templated) C++ projects.
</p>
<p>The &lsquo;<samp class="samp">StagedInstall</samp>&rsquo; logical field controls if package installation
is &lsquo;staged&rsquo;, that is done to a temporary location and moved to the final
location when successfully completed.  This field was introduced in R
3.6.0 and it true by default: it is considered to be a temporary measure
which may be withdrawn in future.
</p>
<p>The &lsquo;<samp class="samp">ZipData</samp>&rsquo; logical field has been ignored since R 2.13.0.
</p>
<p>The &lsquo;<samp class="samp">Biarch</samp>&rsquo; logical field is used on Windows to select the
<code class="command">INSTALL</code> option <samp class="option">--force-biarch</samp> for this package.  Not
currently relevant.
</p>
<p>The &lsquo;<samp class="samp">BuildVignettes</samp>&rsquo; logical field can be set to a false value to
stop <code class="command">R CMD build</code> from attempting to build the vignettes, as
well as preventing<a class="footnote" id="DOCF9" href="#FOOT9"><sup>9</sup></a>  <code class="command">R CMD check</code> from testing
this.  This should only be used exceptionally, for example if the PDFs
include large figures which are not part of the package sources (and
hence only in packages which do not have an Open Source license).
</p>
<p>The &lsquo;<samp class="samp">VignetteBuilder</samp>&rsquo; field names (in a comma-separated list)
packages that provide an engine for building vignettes.  These may
include the current package, or ones listed in &lsquo;<samp class="samp">Depends</samp>&rsquo;,
&lsquo;<samp class="samp">Suggests</samp>&rsquo; or &lsquo;<samp class="samp">Imports</samp>&rsquo;. The <strong class="strong">utils</strong> package is always
implicitly appended.  See <a class="ref" href="#Non_002dSweave-vignettes">Non-Sweave vignettes</a> for details.  Note
that if, for example, a vignette has engine &lsquo;<samp class="samp">knitr::rmarkdown</samp>&rsquo;,
then <a class="url" href="https://CRAN.R-project.org/package=knitr"><strong class="strong">knitr</strong></a> provides the engine but both <strong class="strong">knitr</strong> and
<a class="url" href="https://CRAN.R-project.org/package=rmarkdown"><strong class="strong">rmarkdown</strong></a> are needed for using it, so <em class="emph">both</em> these
packages need to be in the &lsquo;<samp class="samp">VignetteBuilder</samp>&rsquo; field and at least
suggested (as <strong class="strong">rmarkdown</strong> is only suggested by <strong class="strong">knitr</strong>, and
hence not available automatically along with it).  Many packages using
<a class="url" href="https://CRAN.R-project.org/package=knitr"><strong class="strong">knitr</strong></a> also need the package <a class="url" href="https://CRAN.R-project.org/package=formatR"><strong class="strong">formatR</strong></a> which it
suggests and so the user package needs to do so too and include this in
&lsquo;<samp class="samp">VignetteBuilder</samp>&rsquo;.
</p>
<p>If the <samp class="file">DESCRIPTION</samp> file is not entirely in <abbr class="acronym">ASCII</abbr> it
should contain an &lsquo;<samp class="samp">Encoding</samp>&rsquo; field specifying an encoding.  This is
used as the encoding of the <samp class="file">DESCRIPTION</samp> file itself and of the
<samp class="file">R</samp> and <samp class="file">NAMESPACE</samp> files, and as the default encoding of
<samp class="file">.Rd</samp> files.  The examples are assumed to be in this encoding when
running <code class="command">R CMD check</code>, and it is used for the encoding of the
<code class="code">CITATION</code> file.  Only encoding names <code class="code">latin1</code> and
and <code class="code">UTF-8</code> are known to be portable.  (Do not specify an encoding
unless one is actually needed: doing so makes the package <em class="emph">less</em>
portable.  If a package has a specified encoding, you should run
<code class="command">R CMD build</code> etc in a locale using that encoding.)
</p>
<p>The &lsquo;<samp class="samp">NeedsCompilation</samp>&rsquo; field should be set to <code class="code">&quot;yes&quot;</code> if the
package contains native code which needs to be compiled, otherwise <code class="code">&quot;no&quot;</code> (when
the package could be installed from source on any platform without
additional tools).  This is used by <code class="code">install.packages(type =
&quot;both&quot;)</code> in R &gt;= 2.15.2 on platforms where binary packages are the
norm: it is normally set by <code class="command">R CMD build</code> or the repository
assuming compilation is required if and only if the package has a
<samp class="file">src</samp> directory.
</p>
<p>The &lsquo;<samp class="samp">OS_type</samp>&rsquo; field specifies the OS(es) for which the
package is intended.  If present, it should be one of <code class="code">unix</code> or
<code class="code">windows</code>, and indicates that the package can only be installed
on a platform with &lsquo;<samp class="samp">.Platform$OS.type</samp>&rsquo; having that value.
</p>
<p>The &lsquo;<samp class="samp">Type</samp>&rsquo; field specifies the type of the package:
see <a class="pxref" href="#Package-types">Package types</a>.
</p>
<p>One can add subject classifications for the content of the package using
the fields &lsquo;<samp class="samp">Classification/ACM</samp>&rsquo; or &lsquo;<samp class="samp">Classification/ACM-2012</samp>&rsquo;
(using the Computing Classification System of the Association for
Computing Machinery, <a class="uref" href="https://www.acm.org/publications/class-2012">https://www.acm.org/publications/class-2012</a>; the former refers
to the 1998 version), &lsquo;<samp class="samp">Classification/JEL</samp>&rsquo; (the Journal of Economic
Literature Classification System,
<a class="uref" href="https://www.aeaweb.org/econlit/jelCodes.php">https://www.aeaweb.org/econlit/jelCodes.php</a>, or
&lsquo;<samp class="samp">Classification/MSC</samp>&rsquo; or &lsquo;<samp class="samp">Classification/MSC-2010</samp>&rsquo; (the
Mathematics Subject Classification of the American Mathematical Society,
<a class="uref" href="https://mathscinet.ams.org/msc/msc2010.html">https://mathscinet.ams.org/msc/msc2010.html</a>; the former refers to the 2000 version).
The subject classifications should be comma-separated lists of the
respective classification codes, e.g., &lsquo;<samp class="samp">Classification/ACM: G.4,
H.2.8, I.5.1</samp>&rsquo;.
</p>
<p>A &lsquo;<samp class="samp">Language</samp>&rsquo; field can be used to indicate if the package
documentation is not in English: this should be a comma-separated list
of standard (not private use or grandfathered) <abbr class="abbr">IETF</abbr> language tags as
currently defined by RFC 5646
(<a class="uref" href="https://www.rfc-editor.org/rfc/rfc5646">https://www.rfc-editor.org/rfc/rfc5646</a>, see also
<a class="uref" href="https://en.wikipedia.org/wiki/IETF_language_tag">https://en.wikipedia.org/wiki/IETF_language_tag</a>), i.e., use
language subtags which in essence are 2-letter ISO 639-1
(<a class="uref" href="https://en.wikipedia.org/wiki/ISO_639-1">https://en.wikipedia.org/wiki/ISO_639-1</a>) or 3-letter ISO
639-3 (<a class="uref" href="https://en.wikipedia.org/wiki/ISO_639-3">https://en.wikipedia.org/wiki/ISO_639-3</a>) language
codes.
</p>
<p>An &lsquo;<samp class="samp">RdMacros</samp>&rsquo; field can be used to hold a comma-separated list of
packages from which the current package will import <samp class="file">Rd</samp> macro
definitions.  These package should also be listed in &lsquo;<samp class="samp">Imports</samp>&rsquo;
(or &lsquo;<samp class="samp">Depends</samp>&rsquo;).  The macros in these packages will be 
imported after the system macros, in the 
order listed in the &lsquo;<samp class="samp">RdMacros</samp>&rsquo; field, before any macro definitions
in the current package are loaded.  Macro definitions in individual
<samp class="file">.Rd</samp> files in the <samp class="file">man</samp> directory are loaded last, and are
local to later parts of that file.  In case of duplicates, the last
loaded definition will be used.<a class="footnote" id="DOCF10" href="#FOOT10"><sup>10</sup></a>  Both <code class="command">R CMD
Rd2pdf</code> and <code class="command">R CMD Rdconv</code> have an optional flag
<samp class="option">--RdMacros=pkglist</samp>.  The option is also a comma-separated list
of package names, and has priority over the value given in
<samp class="file">DESCRIPTION</samp>.  Packages using <samp class="file">Rd</samp> macros should depend on
R 3.2.0 or later.
</p>
<blockquote class="quotation">
<p><b class="b">Note:</b> There should be no &lsquo;<samp class="samp">Built</samp>&rsquo; or &lsquo;<samp class="samp">Packaged</samp>&rsquo; fields, as these are
added by the package management tools.
</p></blockquote>

<p>There is no restriction on the use of other fields not mentioned here
(but using other capitalizations of these field names would cause
confusion).  Fields <code class="code">Note</code>, <code class="code">Contact</code> (for contacting the
authors/developers<a class="footnote" id="DOCF11" href="#FOOT11"><sup>11</sup></a>) and <code class="code">MailingList</code> are in common
use. Some repositories (including <abbr class="acronym">CRAN</abbr> and R-forge) add their
own fields.
</p>


<hr>
</div>
<div class="subsection-level-extent" id="Licensing">
<div class="nav-panel">
<p>
Next: <a href="#Package-Dependencies" accesskey="n" rel="next">Package Dependencies</a>, Previous: <a href="#The-DESCRIPTION-file" accesskey="p" rel="prev">The <samp class="file">DESCRIPTION</samp> file</a>, Up: <a href="#Package-structure" accesskey="u" rel="up">Package structure</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Licensing-1"><span>1.1.2 Licensing<a class="copiable-link" href="#Licensing-1"> &para;</a></span></h4>

<p>Licensing for a package which might be distributed is an important but
potentially complex subject.
</p>
<p>It is very important that you include license information!  Otherwise,
it may not even be legally correct for others to distribute copies of
the package, let alone use it.
</p>
<p>The package management tools use the concept of
&lsquo;free or open source software&rsquo;
(<abbr class="abbr">FOSS</abbr>, e.g., <a class="uref" href="https://en.wikipedia.org/wiki/FOSS">https://en.wikipedia.org/wiki/FOSS</a>)
licenses: the idea being that some users of R and its packages want
to restrict themselves to such software.  Others need to ensure that
there are no restrictions stopping them using a package, e.g.
forbidding commercial or military use.  It is a central tenet of <abbr class="abbr">FOSS</abbr>
software that there are no restrictions on users nor usage.
</p>
<p>Do not use the &lsquo;<samp class="samp">License</samp>&rsquo; field for information on copyright
holders: if needed, use a &lsquo;<samp class="samp">Copyright</samp>&rsquo; field.
</p>
<p>The mandatory &lsquo;<samp class="samp">License</samp>&rsquo; field in the <samp class="file">DESCRIPTION</samp> file should
specify the license of the package in a standardized form.  Alternatives
are indicated <em class="emph">via</em> vertical bars.  Individual specifications must
be one of
</p><ul class="itemize mark-bullet">
<li>One of the &ldquo;standard&rdquo; short specifications
<div class="example">
<pre class="example-preformatted">GPL-2 GPL-3 LGPL-2 LGPL-2.1 LGPL-3 AGPL-3 Artistic-2.0
BSD_2_clause BSD_3_clause MIT
</pre></div>
<p>as made available <em class="emph">via</em> <a class="uref" href="https://www.R-project.org/Licenses/">https://www.R-project.org/Licenses/</a> and
contained in subdirectory <samp class="file">share/licenses</samp> of the R source or home
directory.
</p></li><li>The names or abbreviations of other licenses contained in the license
data base in file <samp class="file">share/licenses/license.db</samp> in the R source or
home directory, possibly (for versioned licenses) followed by a version
restriction of the form &lsquo;<samp class="samp">(<var class="var">op</var> <var class="var">v</var>)</samp>&rsquo; with &lsquo;<samp class="samp"><var class="var">op</var></samp>&rsquo; one of
the comparison operators &lsquo;<samp class="samp">&lt;</samp>&rsquo;, &lsquo;<samp class="samp">&lt;=</samp>&rsquo;, &lsquo;<samp class="samp">&gt;</samp>&rsquo;, &lsquo;<samp class="samp">&gt;=</samp>&rsquo;,
&lsquo;<samp class="samp">==</samp>&rsquo;, or &lsquo;<samp class="samp">!=</samp>&rsquo; and &lsquo;<samp class="samp"><var class="var">v</var></samp>&rsquo; a numeric version specification
(strings of non-negative integers separated by &lsquo;<samp class="samp">.</samp>&rsquo;), possibly
combined <em class="emph">via</em> &lsquo;<samp class="samp">,</samp>&rsquo; (see below for an example).  For versioned
licenses, one can also specify the name followed by the version, or
combine an existing abbreviation and the version with a &lsquo;<samp class="samp">-</samp>&rsquo;.

<p>Abbreviations <code class="code">GPL</code> and <code class="code">LGPL</code> are ambiguous and
usually<a class="footnote" id="DOCF12" href="#FOOT12"><sup>12</sup></a> taken to mean any version of the license: but it is better
not to use them.
</p></li><li>One of the strings &lsquo;<samp class="samp">file LICENSE</samp>&rsquo; or &lsquo;<samp class="samp">file LICENCE</samp>&rsquo; referring
to a file named <samp class="file">LICENSE</samp> or <samp class="file">LICENCE</samp> in the package (source
and installation) top-level directory.
</li><li>The string &lsquo;<samp class="samp">Unlimited</samp>&rsquo;, meaning that there are no restrictions on
distribution or use other than those imposed by relevant laws (including
copyright laws).
</li></ul>

<p>Multiple licences can be specified separated by &lsquo;<samp class="samp">|</samp>&rsquo; (surrounded by
spaces) in which case the user can choose any of the alternatives.
</p>
<p>If a package license <em class="emph">restricts</em> a base license (where permitted,
e.g., using GPL-3 or AGPL-3 with an attribution clause), the additional
terms should be placed in file <samp class="file">LICENSE</samp> (or <samp class="file">LICENCE</samp>), and
the string &lsquo;<samp class="samp">+ file LICENSE</samp>&rsquo; (or &lsquo;<samp class="samp">+ file LICENCE</samp>&rsquo;,
respectively) should be appended to the corresponding individual license
specification (preferably with the &lsquo;<samp class="samp">+</samp>&rsquo; surrounded by spaces).  Note
that several commonly used licenses do not permit restrictions: this
includes GPL-2 and hence any specification which includes it.
</p>
<p>Examples of standardized specifications include
</p><div class="example">
<pre class="example-preformatted">License: GPL-2
License: LGPL (&gt;= 2.0, &lt; 3) | Mozilla Public License
License: GPL-2 | file LICENCE
License: GPL (&gt;= 2) | BSD_3_clause + file LICENSE
License: Artistic-2.0 | AGPL-3 + file LICENSE
</pre></div>
<p>Please note in particular that &ldquo;Public domain&rdquo; is not a valid license,
since it is not recognized in some jurisdictions.
</p>
<p>Please ensure that the license you choose also covers any dependencies
(including system dependencies) of your package: it is particularly
important that any restrictions on the use of such dependencies are
evident to people reading your <samp class="file">DESCRIPTION</samp> file.
</p>
<p>Fields &lsquo;<samp class="samp">License_is_FOSS</samp>&rsquo; and &lsquo;<samp class="samp">License_restricts_use</samp>&rsquo; may be
added by repositories where information cannot be computed from the name
of the license.  &lsquo;<samp class="samp">License_is_FOSS: yes</samp>&rsquo; is used for licenses which
are known to be <abbr class="abbr">FOSS</abbr>, and &lsquo;<samp class="samp">License_restricts_use</samp>&rsquo; can have values
&lsquo;<samp class="samp">yes</samp>&rsquo; or &lsquo;<samp class="samp">no</samp>&rsquo; if the <samp class="file">LICENSE</samp> file is known to restrict
users or usage, or known not to.  These are used by, e.g., the
<code class="code">available.packages</code> filters.
</p>

<a class="index-entry-id" id="index-LICENSE-file"></a>
<a class="index-entry-id" id="index-LICENCE-file"></a>
<p>The optional file <samp class="file">LICENSE</samp>/<samp class="file">LICENCE</samp> contains a copy of the
license of the package.  To avoid any confusion only include such a file
if it is referred to in the &lsquo;<samp class="samp">License</samp>&rsquo; field of the
<samp class="file">DESCRIPTION</samp> file.
</p>
<p>Whereas you should feel free to include a license file in your
<em class="emph">source</em> distribution, please do not arrange to <em class="emph">install</em> yet
another copy of the <abbr class="acronym">GNU</abbr> <samp class="file">COPYING</samp> or <samp class="file">COPYING.LIB</samp>
files but refer to the copies on
<a class="uref" href="https://www.R-project.org/Licenses/">https://www.R-project.org/Licenses/</a> and included in the R
distribution (in directory <samp class="file">share/licenses</samp>).  Since files named
<samp class="file">LICENSE</samp> or <samp class="file">LICENCE</samp> <em class="emph">will</em> be installed, do not use
these names for standard license files.  To include comments about the
licensing rather than the body of a license, use a file named something
like <samp class="file">LICENSE.note</samp>.
</p>
<p>A few &ldquo;standard&rdquo; licenses are rather license templates which need
additional information to be completed <em class="emph">via</em> &lsquo;<samp class="samp">+ file LICENSE</samp>&rsquo;
(with the &lsquo;<samp class="samp">+</samp>&rsquo; surrounded by spaces).  Where the additional
information is &lsquo;<samp class="samp">COPYRIGHT HOLDER</samp>&rsquo;, this must give the actual legal
entities (not something vague like &lsquo;Name-of-package authors&rsquo;): if more
than one they should be listed in decreasing order of contribution.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Package-Dependencies">
<div class="nav-panel">
<p>
Next: <a href="#The-INDEX-file" accesskey="n" rel="next">The <samp class="file">INDEX</samp> file</a>, Previous: <a href="#Licensing" accesskey="p" rel="prev">Licensing</a>, Up: <a href="#Package-structure" accesskey="u" rel="up">Package structure</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Package-Dependencies-1"><span>1.1.3 Package Dependencies<a class="copiable-link" href="#Package-Dependencies-1"> &para;</a></span></h4>

<p>The &lsquo;<samp class="samp">Depends</samp>&rsquo; field gives a comma-separated list of package names
which this package depends on.  Those packages will be attached before
the current package when <code class="code">library</code> or <code class="code">require</code> is called.
Each package name may be optionally followed by a comment in parentheses
specifying a version requirement.  The comment should contain a
comparison operator, whitespace and a valid version number,
e.g. &lsquo;<samp class="samp">MASS (&gt;= 3.1-20)</samp>&rsquo;.
</p>
<p>The &lsquo;<samp class="samp">Depends</samp>&rsquo; field can also specify a dependence on a certain
version of R &mdash; e.g., if the package works only with R version
4.0.0 or later, include &lsquo;<samp class="samp">R (&gt;= 4.0)</samp>&rsquo; in the &lsquo;<samp class="samp">Depends</samp>&rsquo;
field. (As here, trailing zeroes can be dropped and it is recommended
that they are.)  You can also require a certain SVN revision for R-devel
or R-patched, e.g. &lsquo;<samp class="samp">R (&gt;= 2.14.0), R (&gt;= r56550)</samp>&rsquo; requires a
version later than R-devel of late July 2011 (including released
versions of 2.14.0).
</p>
<p>It makes no sense to declare a dependence on <code class="code">R</code> without a version
specification, nor on the package <strong class="strong">base</strong>: this is an R package
and package <strong class="strong">base</strong> is always available.
</p>
<p>A package or &lsquo;<samp class="samp">R</samp>&rsquo; can appear more than once in the &lsquo;<samp class="samp">Depends</samp>&rsquo;
field, for example to give upper and lower bounds on acceptable
versions.
</p>
<p>It is inadvisable to use a dependence on R with patch level (the third
digit) other than zero.  Doing so with packages which others depend on
will cause the other packages to become unusable under earlier versions
in the series, and e.g. versions 4.x.1 are widely used throughout the
Northern Hemisphere academic year.
</p>
<p>Both <code class="code">library</code> and the R package checking facilities use this
field: hence it is an error to use improper syntax or misuse the
&lsquo;<samp class="samp">Depends</samp>&rsquo; field for comments on other software that might be
needed.  The R <code class="command">INSTALL</code> facilities check if the version of
R used is recent enough for the package being installed, and the list
of packages which is specified will be attached (after checking version
requirements) before the current package.
</p>
<p>The &lsquo;<samp class="samp">Imports</samp>&rsquo; field lists packages whose namespaces are imported
from (as specified in the <samp class="file">NAMESPACE</samp> file) but which do not need
to be attached.  Namespaces accessed by the &lsquo;<samp class="samp">::</samp>&rsquo; and &lsquo;<samp class="samp">:::</samp>&rsquo;
operators must be listed here, or in &lsquo;<samp class="samp">Suggests</samp>&rsquo; or &lsquo;<samp class="samp">Enhances</samp>&rsquo;
(see below).  Ideally this field will include all the standard packages
that are used, and it is important to include S4-using packages (as
their class definitions can change and the <samp class="file">DESCRIPTION</samp> file is
used to decide which packages to re-install when this happens).
Packages declared in the &lsquo;<samp class="samp">Depends</samp>&rsquo; field should not also be in the
&lsquo;<samp class="samp">Imports</samp>&rsquo; field.  Version requirements can be specified and are
checked when the namespace is loaded.
</p>
<p>The &lsquo;<samp class="samp">Suggests</samp>&rsquo; field uses the same syntax as &lsquo;<samp class="samp">Depends</samp>&rsquo; and
lists packages that are not necessarily needed.  This includes packages
used only in examples, tests or vignettes (see <a class="pxref" href="#Writing-package-vignettes">Writing package vignettes</a>), and packages loaded in the body of functions.  E.g.,
suppose an example<a class="footnote" id="DOCF13" href="#FOOT13"><sup>13</sup></a> from
package <strong class="strong">foo</strong> uses a dataset from package <strong class="strong">bar</strong>. Then it is not
necessary to have <strong class="strong">bar</strong> use <strong class="strong">foo</strong> unless one wants to execute
all the examples/tests/vignettes: it is useful to have <strong class="strong">bar</strong>, but
not necessary.  Version requirements can be specified but should be
checked by the code which uses the package.
</p>
<p>Finally, the &lsquo;<samp class="samp">Enhances</samp>&rsquo; field lists packages &ldquo;enhanced&rdquo; by the
package at hand, e.g., by providing methods for classes from these
packages, or ways to handle objects from these packages (so several
packages have &lsquo;<samp class="samp">Enhances: chron</samp>&rsquo; because they can handle datetime
objects from <a class="url" href="https://CRAN.R-project.org/package=chron"><strong class="strong">chron</strong></a> even though they prefer R&rsquo;s native
datetime functions).  Version requirements can be specified, but are
currently not used.  Such packages cannot be required to check the
package: any tests which use them must be conditional on the presence
of the package.  (If your tests use e.g. a dataset from another
package it should be in &lsquo;<samp class="samp">Suggests</samp>&rsquo; and not &lsquo;<samp class="samp">Enhances</samp>&rsquo;.)
</p>
<p>The general rules are
</p>
<ul class="itemize mark-bullet">
<li>A package should be listed in only one of these fields.
</li><li>Packages whose namespace only is needed to load the package using
<code class="code">library(<var class="var">pkgname</var>)</code> should be listed in the &lsquo;<samp class="samp">Imports</samp>&rsquo; field
and not in the &lsquo;<samp class="samp">Depends</samp>&rsquo; field.  Packages listed in <code class="code">import</code>
or <code class="code">importFrom</code> directives in the <samp class="file">NAMESPACE</samp> file should
almost always be in &lsquo;<samp class="samp">Imports</samp>&rsquo; and not &lsquo;<samp class="samp">Depends</samp>&rsquo;.
</li><li>Packages that need to be attached to successfully load the package using
<code class="code">library(<var class="var">pkgname</var>)</code> must be listed in the &lsquo;<samp class="samp">Depends</samp>&rsquo;
field.
</li><li>All packages that are needed<a class="footnote" id="DOCF14" href="#FOOT14"><sup>14</sup></a> to successfully run <code class="code">R CMD check</code> on the
package must be listed in one of &lsquo;<samp class="samp">Depends</samp>&rsquo; or &lsquo;<samp class="samp">Suggests</samp>&rsquo; or
&lsquo;<samp class="samp">Imports</samp>&rsquo;.  Packages used to run examples or tests conditionally
(e.g. <em class="emph">via</em> <code class="code">if(require(<var class="var">pkgname</var>))</code>) should be listed
in &lsquo;<samp class="samp">Suggests</samp>&rsquo; or &lsquo;<samp class="samp">Enhances</samp>&rsquo;.  (This allows checkers to ensure
that all the packages needed for a complete check are installed.)

</li><li>Packages needed to use datasets from the package should be in
&lsquo;<samp class="samp">Imports</samp>&rsquo;: this includes those needed to define S4 classes used.
</li></ul>

<p>In particular, packages providing &ldquo;only&rdquo; data for examples or
vignettes should be listed in &lsquo;<samp class="samp">Suggests</samp>&rsquo; rather than &lsquo;<samp class="samp">Depends</samp>&rsquo;
in order to make lean installations possible.
</p>
<p>Version dependencies in the &lsquo;<samp class="samp">Depends</samp>&rsquo; and &lsquo;<samp class="samp">Imports</samp>&rsquo; fields are
used by <code class="code">library</code> when it loads the package, and
<code class="code">install.packages</code> checks versions for the &lsquo;<samp class="samp">Depends</samp>&rsquo;,
&lsquo;<samp class="samp">Imports</samp>&rsquo; and (for <code class="code">dependencies = TRUE</code>) &lsquo;<samp class="samp">Suggests</samp>&rsquo;
fields.
</p>
<p>It is important that the information in these fields is complete and
accurate: it is for example used to compute which packages depend on an
updated package and which packages can safely be installed in parallel.
</p>
<p>This scheme was developed before all packages had namespaces (R
2.14.0 in October 2011), and good practice changed once that was in
place.
</p>
<p>Field &lsquo;<samp class="samp">Depends</samp>&rsquo; should nowadays be used rarely, only for packages
which are intended to be put on the search path to make their facilities
available to the end user (and not to the package itself): for example
it makes sense that a user of package <a class="url" href="https://CRAN.R-project.org/package=latticeExtra"><strong class="strong">latticeExtra</strong></a> would want
the functions of package <a class="url" href="https://CRAN.R-project.org/package=lattice"><strong class="strong">lattice</strong></a> made available.
</p>
<p>Almost always packages mentioned in &lsquo;<samp class="samp">Depends</samp>&rsquo; should also be
imported from in the <samp class="file">NAMESPACE</samp> file: this ensures that any needed
parts of those packages are available when some other package imports
the current package.
</p>
<p>The &lsquo;<samp class="samp">Imports</samp>&rsquo; field should not contain packages which are not
imported from (<em class="emph">via</em> the <samp class="file">NAMESPACE</samp> file or <code class="code">::</code> or
<code class="code">:::</code> operators), as all the packages listed in that field need to
be installed for the current package to be installed.  (This is checked
by <code class="command">R CMD check</code>.)
</p>
<p>R code in the package should call <code class="code">library</code> or <code class="code">require</code>
only exceptionally.  Such calls are never needed for packages listed in
&lsquo;<samp class="samp">Depends</samp>&rsquo; as they will already be on the search path.  It used to
be common practice to use <code class="code">require</code> calls for packages listed in
&lsquo;<samp class="samp">Suggests</samp>&rsquo; in functions which used their functionality, but
nowadays it is better to access such functionality <em class="emph">via</em> <code class="code">::</code>
calls.
</p>
<p>A package that wishes to make use of header files in other packages to
compile its C/C++ code needs to declare them as a comma-separated list
in the field &lsquo;<samp class="samp">LinkingTo</samp>&rsquo; in the <samp class="file">DESCRIPTION</samp> file.  For
example
</p>
<div class="example">
<pre class="example-preformatted">LinkingTo: link1, link2
</pre></div>

<p>The &lsquo;<samp class="samp">LinkingTo</samp>&rsquo; field can have a version requirement which is
checked at installation.
</p>
<p>Specifying a package in &lsquo;<samp class="samp">LinkingTo</samp>&rsquo; suffices if these are C/C++
headers containing source code or static linking is done at
installation: the packages do not need to be (and usually should not be)
listed in the &lsquo;<samp class="samp">Depends</samp>&rsquo; or &lsquo;<samp class="samp">Imports</samp>&rsquo; fields.  This includes
<abbr class="acronym">CRAN</abbr> package <a class="url" href="https://CRAN.R-project.org/package=BH"><strong class="strong">BH</strong></a> and almost all users of
<a class="url" href="https://CRAN.R-project.org/package=RcppArmadillo"><strong class="strong">RcppArmadillo</strong></a> and <a class="url" href="https://CRAN.R-project.org/package=RcppEigen"><strong class="strong">RcppEigen</strong></a>.  Note that
&lsquo;<samp class="samp">LinkingTo</samp>&rsquo; applies only to installation: if a packages wishes to
use headers to compile code in tests or vignettes the package providing
them needs to be listed in &lsquo;<samp class="samp">Suggests</samp>&rsquo; or perhaps &lsquo;<samp class="samp">Depends</samp>&rsquo;.
</p>
<p>For another use of &lsquo;<samp class="samp">LinkingTo</samp>&rsquo; see <a class="ref" href="#Linking-to-native-routines-in-other-packages">Linking to native routines in other packages</a>.
</p>
<p>The &lsquo;<samp class="samp">Additional_repositories</samp>&rsquo; field is a comma-separated list of
repository URLs where the packages named in the other fields may be
found.  It is currently used by <code class="command">R CMD check</code> to check that the
packages can be found, at least as source packages (which can be
installed on any platform).
</p>

<ul class="mini-toc">
<li><a href="#Suggested-packages" accesskey="1">Suggested packages</a></li>
</ul>
<hr>
<div class="subsubsection-level-extent" id="Suggested-packages">
<div class="nav-panel">
<p>
Previous: <a href="#Package-Dependencies" accesskey="p" rel="prev">Package Dependencies</a>, Up: <a href="#Package-Dependencies" accesskey="u" rel="up">Package Dependencies</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsubsection" id="Suggested-packages-1"><span>1.1.3.1 Suggested packages<a class="copiable-link" href="#Suggested-packages-1"> &para;</a></span></h4>

<p>Note that someone wanting to run the examples/tests/vignettes may not
have a suggested package available (and it may not even be possible to
install it for that platform).  The recommendation used to be to make
their use conditional <em class="emph">via</em> <code class="code">if(require(&quot;<var class="var">pkgname</var>&quot;))</code>:
this is OK if that conditioning is done in examples/tests/vignettes,
although using <code class="code">if(requireNamespace(&quot;<var class="var">pkgname</var>&quot;))</code> is
preferred, if possible.
</p>
<p>However, using <code class="code">require</code> for conditioning <em class="emph">in package code</em> is
not good practice as it alters the search path for the rest of the
session and relies on functions in that package not being masked by
other <code class="code">require</code> or <code class="code">library</code> calls.  It is better practice to
use code like
</p><div class="example">
<pre class="example-preformatted">   if (requireNamespace(&quot;rgl&quot;, quietly = TRUE)) {
      rgl::plot3d(...)
   } else {
      ## do something else not involving rgl.
   }
</pre></div>
<p>Note the use of <code class="code">rgl::</code> as that object would not necessarily be
visible (and if it is, it need not be the one from that namespace:
<code class="code">plot3d</code> occurs in several other packages).  If the intention is to
give an error if the suggested package is not available, simply use
e.g. <code class="code">rgl::plot3d</code>.
</p>
<p>If the conditional code produces <code class="code">print</code> output, function
<code class="code">withAutoprint</code> can be useful.
</p>
<p>Note that the recommendation to use suggested packages conditionally in
tests does also apply to packages used to manage test suites: a
notorious example was <a class="url" href="https://CRAN.R-project.org/package=testthat"><strong class="strong">testthat</strong></a> which in version 1.0.0 contained
illegal C++ code and hence could not be installed on standards-compliant
platforms.
</p>
<p>Some people have assumed that a &lsquo;recommended&rsquo; package in &lsquo;<samp class="samp">Suggests</samp>&rsquo;
can safely be used unconditionally, but this is not so.  (R can be
installed without recommended packages, and which packages are
&lsquo;recommended&rsquo; may change.)
</p>
<p>As noted above, packages in &lsquo;<samp class="samp">Enhances</samp>&rsquo; <em class="emph">must</em> be used
conditionally and hence objects within them should always be accessed
<em class="emph">via</em> <code class="code">::</code>.
</p>
<p>On most systems, <code class="command">R CMD check</code> can be run with only those
packages declared in &lsquo;<samp class="samp">Depends</samp>&rsquo; and &lsquo;<samp class="samp">Imports</samp>&rsquo; by setting
environment variable <code class="env">_R_CHECK_DEPENDS_ONLY_=true</code>, whereas setting
<code class="env">_R_CHECK_SUGGESTS_ONLY_=true</code> also allows suggested packages, but
not those in &lsquo;<samp class="samp">Enhances</samp>&rsquo; nor those not mentioned in the
<samp class="file">DESCRIPTION</samp> file.  It is recommended that a package is checked
with each of these set, as well as with neither.
</p>
<p><strong class="strong">WARNING:</strong> Be extremely careful if you do things which would be
run at installation time depending on whether suggested packages are
available or not&mdash;this includes top-level code in R code files,
<code class="code">.onLoad</code> functions and the definitions of S4 classes and methods.
The problem is that once a namespace of a suggested package is loaded,
references to it may be captured in the installed package (most commonly
in S4 methods), but the suggested package may not be available when the
installed package is used (which especially for binary packages might be
on a different machine).  Even worse, the problems might not be confined
to your package, for the namespaces of your suggested packages will also
be loaded whenever any package which imports yours is installed and so
may be captured there.
</p>
<hr>
</div>
</div>
<div class="subsection-level-extent" id="The-INDEX-file">
<div class="nav-panel">
<p>
Next: <a href="#Package-subdirectories" accesskey="n" rel="next">Package subdirectories</a>, Previous: <a href="#Package-Dependencies" accesskey="p" rel="prev">Package Dependencies</a>, Up: <a href="#Package-structure" accesskey="u" rel="up">Package structure</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="The-INDEX-file-1"><span>1.1.4 The <samp class="file">INDEX</samp> file<a class="copiable-link" href="#The-INDEX-file-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-INDEX-file"></a>

<p>The optional file <samp class="file">INDEX</samp> contains a line for each sufficiently
interesting object in the package, giving its name and a description
(functions such as print methods not usually called explicitly might not
be included).  Normally this file is missing and the corresponding
information is automatically generated from the documentation sources
(using <code class="code">tools::Rdindex()</code>) when installing from source.
</p>
<p>The file is part of the information given by <code class="code">library(help =
<var class="var">pkgname</var>)</code>.
</p>
<p>Rather than editing this file, it is preferable to put customized
information about the package into an overview help page
(see <a class="pxref" href="#Documenting-packages">Documenting packages</a>) and/or a vignette (see <a class="pxref" href="#Writing-package-vignettes">Writing package vignettes</a>).
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Package-subdirectories">
<div class="nav-panel">
<p>
Next: <a href="#Data-in-packages" accesskey="n" rel="next">Data in packages</a>, Previous: <a href="#The-INDEX-file" accesskey="p" rel="prev">The <samp class="file">INDEX</samp> file</a>, Up: <a href="#Package-structure" accesskey="u" rel="up">Package structure</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Package-subdirectories-1"><span>1.1.5 Package subdirectories<a class="copiable-link" href="#Package-subdirectories-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Package-subdirectories"></a>

<p>The <samp class="file">R</samp> subdirectory contains R code files, only.  The code
files to be installed must start with an <abbr class="acronym">ASCII</abbr> (lower or upper
case) letter or digit and have one of the extensions<a class="footnote" id="DOCF15" href="#FOOT15"><sup>15</sup></a> <samp class="file">.R</samp>,
<samp class="file">.S</samp>, <samp class="file">.q</samp>, <samp class="file">.r</samp>, or <samp class="file">.s</samp>.  We recommend using
<samp class="file">.R</samp>, as this extension seems to be not used by any other software.
It should be possible to read in the files using <code class="code">source()</code>, so
R objects must be created by assignments.  Note that there need be no
connection between the name of the file and the R objects created by
it.  Ideally, the R code files should only directly assign R
objects and definitely should not call functions with side effects such
as <code class="code">require</code> and <code class="code">options</code>.  If computations are required to
create objects these can use code &lsquo;earlier&rsquo; in the package (see the
&lsquo;<samp class="samp">Collate</samp>&rsquo; field) plus functions in the &lsquo;<samp class="samp">Depends</samp>&rsquo; packages
provided that the objects created do not depend on those packages except
<em class="emph">via</em> namespace imports.
</p>
<p>Extreme care is needed if top-level computations are made to depend on
availability or not of other packages.  In particular this applies to
<code class="code">setMethods</code> and <code class="code">setClass</code> calls.  Nor should they depend on
the availability of external resources such as downloads.
</p>
<p>Two exceptions are allowed: if the <samp class="file">R</samp> subdirectory contains a file
<samp class="file">sysdata.rda</samp> (a saved image of one or more R objects: please
use suitable compression as suggested by <code class="code">tools::resaveRdaFiles</code>,
and see also the &lsquo;<samp class="samp">SysDataCompression</samp>&rsquo; <samp class="file">DESCRIPTION</samp> field.)
this will be lazy-loaded into the namespace environment &ndash; this is
intended for system datasets that are not intended to be user-accessible
<em class="emph">via</em> <code class="code">data</code>.  Also, files ending in &lsquo;<samp class="samp">.in</samp>&rsquo; will be
allowed in the <samp class="file">R</samp> directory to allow a <samp class="file">configure</samp> script to
generate suitable files.
</p>
<p>Only <abbr class="acronym">ASCII</abbr> characters (and the control characters tab,
form feed, <abbr class="abbr">LF</abbr> and <abbr class="abbr">CR</abbr>) should be used in code files.  Other characters are
accepted in comments<a class="footnote" id="DOCF16" href="#FOOT16"><sup>16</sup></a>, but then the comments may not
be readable in e.g. a UTF-8 locale.  Non-<abbr class="acronym">ASCII</abbr> characters in
object names will normally<a class="footnote" id="DOCF17" href="#FOOT17"><sup>17</sup></a> fail when the package is installed.  Any byte will
be allowed in a quoted character string but &lsquo;<samp class="samp">\uxxxx</samp>&rsquo; escapes should
be used for non-<abbr class="acronym">ASCII</abbr> characters.  However,
non-<abbr class="acronym">ASCII</abbr> character strings may not be usable in some locales
and may display incorrectly in others.
</p>

<a class="index-entry-id" id="index-library_002edynam"></a>
<p>Various R functions in a package can be used to initialize and
clean up.  See <a class="xref" href="#Load-hooks">Load hooks</a>.
</p>
<p>The <samp class="file">man</samp> subdirectory should contain (only) documentation files
for the objects in the package in <em class="dfn">R documentation</em> (Rd) format.
The documentation filenames must start with an <abbr class="acronym">ASCII</abbr> (lower or
upper case) letter or digit and have the extension <samp class="file">.Rd</samp> (the
default) or <samp class="file">.rd</samp>.  Further, the names must be valid in
&lsquo;<samp class="samp">file://</samp>&rsquo; URLs, which means<a class="footnote" id="DOCF18" href="#FOOT18"><sup>18</sup></a>
they must be entirely <abbr class="acronym">ASCII</abbr> and not contain &lsquo;<samp class="samp">%</samp>&rsquo;.
See <a class="xref" href="#Writing-R-documentation-files">Writing R documentation files</a>, for more information.  Note that
all user-level objects in a package should be documented; if a package
<var class="var">pkg</var> contains user-level objects which are for &ldquo;internal&rdquo; use
only, it should provide a file <samp class="file"><var class="var">pkg</var>-internal.Rd</samp> which
documents all such objects, and clearly states that these are not meant
to be called by the user.  See e.g. the sources for package <strong class="strong">grid</strong>
in the R distribution.  Note that packages which use internal objects
extensively should not export those objects from their namespace, when
they do not need to be documented (see <a class="pxref" href="#Package-namespaces">Package namespaces</a>).
</p>
<p>Having a <samp class="file">man</samp> directory containing no documentation files may give
an installation error.
</p>
<p>The <samp class="file">man</samp> subdirectory may contain a subdirectory named <samp class="file">macros</samp>;
this will contain source for user-defined Rd macros.
(See <a class="ref" href="#User_002ddefined-macros">User-defined macros</a>.)  These use the Rd format, but may
not contain anything but macro definitions, comments and whitespace.
</p>
<p>The <samp class="file">R</samp> and <samp class="file">man</samp> subdirectories may contain OS-specific
subdirectories named <samp class="file">unix</samp> or <samp class="file">windows</samp>.
</p>
<p>The sources and headers for the compiled code are in <samp class="file">src</samp>, plus
optionally a file <samp class="file">Makevars</samp> or <samp class="file">Makefile</samp> (or for use on
Windows, with extension <samp class="file">.win</samp> or <samp class="file">.ucrt</samp>).  When a package is
installed using <code class="code">R CMD INSTALL</code>, <code class="command">make</code> is used to control
compilation and linking into a shared object for loading into R.
There are default <code class="command">make</code> variables and rules for this
(determined when R is configured and recorded in
<samp class="file"><var class="var">R_HOME</var>/etc<var class="var">R_ARCH</var>/Makeconf</samp>), providing support for C,
C++, fixed- or free-form Fortran, Objective C and Objective
C++<a class="footnote" id="DOCF19" href="#FOOT19"><sup>19</sup></a> with associated extensions <samp class="file">.c</samp>,
<samp class="file">.cc</samp> or <samp class="file">.cpp</samp>, <samp class="file">.f</samp>, <samp class="file">.f90</samp> or
<samp class="file">.f95</samp>,<a class="footnote" id="DOCF20" href="#FOOT20"><sup>20</sup></a>
<samp class="file">.m</samp>, and <samp class="file">.mm</samp>, respectively.  We recommend using <samp class="file">.h</samp>
for headers, also for C++<a class="footnote" id="DOCF21" href="#FOOT21"><sup>21</sup></a> or Fortran include files.  (Use of extension
<samp class="file">.C</samp> for C++ is no longer supported.)  Files in the <samp class="file">src</samp>
directory should not be hidden (start with a dot), and hidden files will
under some versions of R be ignored.
</p>
<p>It is not portable (and may not be possible at all) to mix all these
languages in a single package.  Because R itself uses it, we know that
C and fixed-form Fortran can be used together, and mixing C, C++ and
Fortran usually work for the platform&rsquo;s native compilers.
</p>
<p>If your code needs to depend on the platform there are certain defines
which can used in C or C++.  On all Windows builds (even 64-bit ones)
&lsquo;<samp class="samp">_WIN32</samp>&rsquo; will be defined: on 64-bit Windows builds also
&lsquo;<samp class="samp">_WIN64</samp>&rsquo;. For Windows on ARM, test for &lsquo;<samp class="samp">_M_ARM64</samp>&rsquo; or both
&lsquo;<samp class="samp">_WIN32</samp>&rsquo; and &lsquo;<samp class="samp">__aarch64__</samp>&rsquo;.  On macOS &lsquo;<samp class="samp">__APPLE__</samp>&rsquo; is
defined<a class="footnote" id="DOCF22" href="#FOOT22"><sup>22</sup></a>; for an &lsquo;Apple Silicon&rsquo; platform, test
for both &lsquo;<samp class="samp">__APPLE__</samp>&rsquo; and &lsquo;<samp class="samp">__arm64__</samp>&rsquo;.
</p>
<p>The default rules can be tweaked by setting macros<a class="footnote" id="DOCF23" href="#FOOT23"><sup>23</sup></a> in a file
<samp class="file">src/Makevars</samp> (see <a class="pxref" href="#Using-Makevars">Using <samp class="file">Makevars</samp></a>).  Note that this mechanism
should be general enough to eliminate the need for a package-specific
<samp class="file">src/Makefile</samp>.  If such a file is to be distributed, considerable
care is needed to make it general enough to work on all R platforms.
If it has any targets at all, it should have an appropriate first target
named &lsquo;<samp class="samp">all</samp>&rsquo; and a (possibly empty) target &lsquo;<samp class="samp">clean</samp>&rsquo; which
removes all files generated by running <code class="command">make</code> (to be used by
&lsquo;<samp class="samp">R CMD INSTALL --clean</samp>&rsquo; and &lsquo;<samp class="samp">R CMD INSTALL --preclean</samp>&rsquo;).
There are platform-specific file names on Windows:
<samp class="file">src/Makevars.win</samp> takes precedence over <samp class="file">src/Makevars</samp> and
<samp class="file">src/Makefile.win</samp> must be used. Since R 4.2.0,
<samp class="file">src/Makevars.ucrt</samp> takes precedence over
<samp class="file">src/Makevars.win</samp> and <samp class="file">src/Makefile.ucrt</samp> takes precedence
over <samp class="file">src/Makefile.win</samp>. <samp class="file">src/Makevars.ucrt</samp> and
<samp class="file">src/Makefile.ucrt</samp> will be ignored by earlier versions of R, and
hence can be used to provide content specific to <abbr class="abbr">UCRT</abbr> or Rtools42 and newer,
but the support for <samp class="file">.ucrt</samp> files may be removed in the future when
building packages from source on the older versions of R will no longer
be needed, and hence the files may be renamed back to <samp class="file">.win</samp>.
Some <code class="command">make</code> programs
require makefiles to have a complete final line, including a newline.
</p>
<p>A few packages use the <samp class="file">src</samp> directory for purposes other than
making a shared object (e.g. to create executables).  Such packages
should have files <samp class="file">src/Makefile</samp> and <samp class="file">src/Makefile.win</samp> or
<samp class="file">src/Makefile.ucrt</samp> (unless intended for only Unix-alikes or only
Windows).  Note that on Unix such makefiles are included after
<samp class="file"><var class="var">R_HOME</var>/etc/<var class="var">R_ARCH</var>/Makeconf</samp> so all the usual R
macros and make rules are available &ndash; for example C compilation will by
default use the C compiler and flags with which R was
configured.  This also applies on Windows as from R 4.3.0: packages
intended to be used with earlier versions should include that file
themselves.
</p>
<p>The order of inclusion of makefiles for a package which does
<strong class="strong">not</strong> have a <samp class="file">src/Makefile</samp> file is
</p><table summary="" class="multitable">
<thead><tr><th width="50%">Unix-alike</th><th width="50%">Windows</th></tr></thead>
<tbody><tr><td width="50%"><samp class="file">src/Makevars</samp></td><td width="50%"><samp class="file">src/Makevars.ucrt</samp>,
<samp class="file">src/Makevars.win</samp></td></tr>
<tr><td width="50%"><samp class="file"><var class="var">R_HOME</var>/etc/<var class="var">R_ARCH</var>/Makeconf</samp></td><td width="50%"><samp class="file"><var class="var">R_HOME</var>/etc/<var class="var">R_ARCH</var>/Makeconf</samp></td></tr>
<tr><td width="50%"><code class="env">R_MAKEVARS_SITE</code>, <samp class="file"><var class="var">R_HOME</var>/etc/<var class="var">R_ARCH</var>/Makevars.site</samp></td><td width="50%"><code class="env">R_MAKEVARS_SITE</code>, <samp class="file"><var class="var">R_HOME</var>/etc/<var class="var">R_ARCH</var>/Makevars.site</samp></td></tr>
<tr><td width="50%"><samp class="file"><var class="var">R_HOME</var>/share/make/shlib.mk</samp></td><td width="50%"><samp class="file"><var class="var">R_HOME</var>/share/make/winshlib.mk</samp></td></tr>
<tr><td width="50%"><code class="env">R_MAKEVARS_USER</code>, <samp class="file"> ~/.R/Makevars-<var class="var">platform</var></samp>,
<samp class="file"> ~/.R/Makevars</samp></td><td width="50%"><code class="env">R_MAKEVARS_USER</code>, <samp class="file"> ~/.R/Makevars.ucrt</samp>,
<samp class="file"> ~/.R/Makevars.win64</samp>, <samp class="file"> ~/.R/Makevars.win</samp></td></tr>
</tbody>
</table>
<p>For those which do, it is
</p><table summary="" class="multitable">
<tbody><tr><td width="50%"><samp class="file"><var class="var">R_HOME</var>/etc/<var class="var">R_ARCH</var>/Makeconf</samp></td><td width="50%"><samp class="file"><var class="var">R_HOME</var>/etc/<var class="var">R_ARCH</var>/Makeconf</samp></td></tr>
<tr><td width="50%"><code class="env">R_MAKEVARS_SITE</code>, <samp class="file"><var class="var">R_HOME</var>/etc/<var class="var">R_ARCH</var>/Makevars.site</samp></td><td width="50%"><code class="env">R_MAKEVARS_SITE</code>, <samp class="file"><var class="var">R_HOME</var>/etc/<var class="var">R_ARCH</var>/Makevars.site</samp></td></tr>
<tr><td width="50%"><samp class="file">src/Makefile</samp></td><td width="50%"><samp class="file">src/Makefile.ucrt</samp>,
<samp class="file">src/Makefile.win</samp></td></tr>
<tr><td width="50%"><code class="env">R_MAKEVARS_USER</code>, <samp class="file"> ~/.R/Makevars-<var class="var">platform</var></samp>,
<samp class="file"> ~/.R/Makevars</samp></td><td width="50%"><code class="env">R_MAKEVARS_USER</code>, <samp class="file"> ~/.R/Makevars.ucrt</samp>,
<samp class="file"> ~/.R/Makevars.win64</samp>, <samp class="file"> ~/.R/Makevars.win</samp></td></tr>
</tbody>
</table>
<p>Items in capitals are environment variables: those separated by commas
are alternatives looked for in the order shown.
</p>
<p>In very special cases packages may create binary files other than the
shared objects/DLLs in the <samp class="file">src</samp> directory.  Such files will not be
installed in a multi-architecture setting since <code class="code">R CMD INSTALL
--libs-only</code> is used to merge multiple sub-architectures and it only
copies shared objects/DLLs.  If a package wants to install other
binaries (for example executable programs), it should provide an R
script <samp class="file">src/install.libs.R</samp> which will be run as part of the
installation in the <code class="code">src</code> build directory <em class="emph">instead of</em> copying
the shared objects/DLLs. The script is run in a separate R
environment containing the following variables: <code class="code">R_PACKAGE_NAME</code>
(the name of the package), <code class="code">R_PACKAGE_SOURCE</code> (the path to the
source directory of the package), <code class="code">R_PACKAGE_DIR</code> (the path of the
target installation directory of the package), <code class="code">R_ARCH</code> (the
arch-dependent part of the path, often empty), <code class="code">SHLIB_EXT</code> (the
extension of shared objects) and <code class="code">WINDOWS</code> (<code class="code">TRUE</code> on Windows,
<code class="code">FALSE</code> elsewhere).  Something close to the default behavior could
be replicated with the following <samp class="file">src/install.libs.R</samp> file:
</p>
<div class="example">
<pre class="example-preformatted">files &lt;- Sys.glob(paste0(&quot;*&quot;, SHLIB_EXT))
dest &lt;- file.path(R_PACKAGE_DIR, paste0('libs', R_ARCH))
dir.create(dest, recursive = TRUE, showWarnings = FALSE)
file.copy(files, dest, overwrite = TRUE)
if(file.exists(&quot;symbols.rds&quot;))
    file.copy(&quot;symbols.rds&quot;, dest, overwrite = TRUE)
</pre></div>
<p>On the other hand, executable programs could be installed along the
lines of
</p><div class="example">
<pre class="example-preformatted">execs &lt;- c(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;)
if(WINDOWS) execs &lt;- paste0(execs, &quot;.exe&quot;)
if ( any(file.exists(execs)) ) {
  dest &lt;- file.path(R_PACKAGE_DIR,  paste0('bin', R_ARCH))
  dir.create(dest, recursive = TRUE, showWarnings = FALSE)
  file.copy(execs, dest, overwrite = TRUE)
}
</pre></div>

<p>Note the use of architecture-specific subdirectories of <samp class="file">bin</samp> where
needed.  (Executables should installed under a <samp class="file">bin</samp> directory and
not under <samp class="file">libs</samp>.  It is good practice to check that they can be
executed as part of the installation script, so a broken package is not
installed.)
</p>
<p>The <samp class="file">data</samp> subdirectory is for data files: See <a class="xref" href="#Data-in-packages">Data in packages</a>.
</p>
<p>The <samp class="file">demo</samp> subdirectory is for R scripts (for running <em class="emph">via</em>
<code class="code">demo()</code>) that demonstrate some of the functionality of the
package.  Demos may be interactive and are not checked automatically, so
if testing is desired use code in the <samp class="file">tests</samp> directory to achieve
this.  The script files must start with a (lower or upper case) letter
and have one of the extensions <samp class="file">.R</samp> or <samp class="file">.r</samp>.  If present, the
<samp class="file">demo</samp> subdirectory should also have a <samp class="file">00Index</samp> file with one
line for each demo, giving its name and a description separated by a tab
or at least three spaces. (This index file is not generated
automatically.)  Note that a demo does not have a specified encoding and
so should be an <abbr class="acronym">ASCII</abbr> file (see <a class="pxref" href="#Encoding-issues">Encoding issues</a>). Function
<code class="code">demo()</code> will use the package encoding if there is one, but this is
mainly useful for non-<abbr class="acronym">ASCII</abbr> comments.
</p>
<a class="index-entry-id" id="index-_002eRinstignore-file"></a>
<p>The contents of the <samp class="file">inst</samp> subdirectory will be copied recursively
to the installation directory.  Subdirectories of <samp class="file">inst</samp> should not
interfere with those used by R (currently, <samp class="file">R</samp>, <samp class="file">data</samp>,
<samp class="file">demo</samp>, <samp class="file">exec</samp>, <samp class="file">libs</samp>, <samp class="file">man</samp>, <samp class="file">help</samp>,
<samp class="file">html</samp> and <samp class="file">Meta</samp>, and earlier versions used <samp class="file">latex</samp>,
<samp class="file">R-ex</samp>).  The copying of the <samp class="file">inst</samp> happens after <samp class="file">src</samp>
is built so its <samp class="file">Makefile</samp> can create files to be installed.  To
exclude files from being installed, one can specify a list of exclude
patterns in file <samp class="file">.Rinstignore</samp> in the top-level source directory.
These patterns should be Perl-like regular expressions (see the help for
<code class="code">regexp</code> in R for the precise details), one per line, to be
matched case-insensitively against the file and directory paths, e.g.
<samp class="file">doc/.*[.]png$</samp> will exclude all PNG files in <samp class="file">inst/doc</samp> based
on the extension.
</p>
<p>Note that with the exceptions of <samp class="file">INDEX</samp>,
<samp class="file">LICENSE</samp>/<samp class="file">LICENCE</samp> and <samp class="file">NEWS</samp>, information files at the
top level of the package will <em class="emph">not</em> be installed and so not be
known to users of Windows and macOS compiled packages (and not seen
by those who use <code class="command">R CMD INSTALL</code> or <code class="code">install.packages()</code>
on the tarball).  So any information files you wish an end user to see
should be included in <samp class="file">inst</samp>.  Note that if the named exceptions
also occur in <samp class="file">inst</samp>, the version in <samp class="file">inst</samp> will be that seen
in the installed package.
</p>
<a class="index-entry-id" id="index-CITATION"></a>
<a class="index-entry-id" id="index-citation"></a>
<a class="index-entry-id" id="index-NEWS_002eRd"></a>
<a class="index-entry-id" id="index-news"></a>
<p>Things you might like to add to <samp class="file">inst</samp> are a <samp class="file">CITATION</samp> file
for use by the <code class="code">citation</code> function, and a <samp class="file">NEWS.Rd</samp> file for
use by the <code class="code">news</code> function.  See its help page for the specific
format restrictions of the <samp class="file">NEWS.Rd</samp> file.
</p>
<a class="index-entry-id" id="index-AUTHORS"></a>
<a class="index-entry-id" id="index-COPYRIGHTS-1"></a>
<p>Another file sometimes needed in <samp class="file">inst</samp> is <samp class="file">AUTHORS</samp> or
<samp class="file">COPYRIGHTS</samp> to specify the authors or copyright holders when this
is too complex to put in the <samp class="file">DESCRIPTION</samp> file.
</p>
<p>Subdirectory <samp class="file">tests</samp> is for additional package-specific test code,
similar to the specific tests that come with the R distribution.
Test code can either be provided directly in a <samp class="file">.R</samp> (or <samp class="file">.r</samp>
as from R 3.4.0) file, or <em class="emph">via</em> a <samp class="file">.Rin</samp> file containing
code which in turn creates the corresponding <samp class="file">.R</samp> file (e.g., by
collecting all function objects in the package and then calling them
with the strangest arguments).  The results of running a <samp class="file">.R</samp> file
are written to a <samp class="file">.Rout</samp> file.  If there is a
corresponding<a class="footnote" id="DOCF24" href="#FOOT24"><sup>24</sup></a> <samp class="file">.Rout.save</samp> file, these two are
compared, with differences being reported but not causing an error.  The
directory <samp class="file">tests</samp> is copied to the check area, and the tests are
run with the copy as the working directory and with <code class="code">R_LIBS</code> set to
ensure that the copy of the package installed during testing will be
found by <code class="code">library(<var class="var">pkg_name</var>)</code>.  Note that the package-specific
tests are run in a vanilla R session without setting the
random-number seed, so tests which use random numbers will need to set
the seed to obtain reproducible results (and it can be helpful to do so
in all cases, to avoid occasional failures when tests are run).
</p>
<p>If directory <samp class="file">tests</samp> has a subdirectory <samp class="file">Examples</samp> containing
a file <code class="code"><var class="var">pkg</var>-Ex.Rout.save</code>, this is compared to the output
file for running the examples when the latter are checked.  Reference
output should be produced without having the <samp class="option">--timings</samp> option
set (and note that <samp class="option">--as-cran</samp> sets it).
</p>
<p>If reference output is included for examples, tests or vignettes do make
sure that it is fully reproducible, as it will be compared verbatim to
that produced in a check run, unless the &lsquo;<samp class="samp">IGNORE_RDIFF</samp>&rsquo; markup is
used.  Things which trip up maintainers include displayed version
numbers from loading other packages, printing numerical results to an
unreproducibly high precision and printing timings.  Another trap is
small values which are in fact rounding error from zero: consider using
<code class="code">zapsmall</code>.
</p>
<p>Subdirectory <samp class="file">exec</samp> could contain additional executable scripts the
package needs, typically scripts for interpreters such as the shell,
Perl, or Tcl.  NB: only files (and not directories) under <samp class="file">exec</samp>
are installed (and those with names starting with a dot are ignored),
and they are all marked as executable (mode <code class="code">755</code>, moderated by
&lsquo;<samp class="samp">umask</samp>&rsquo;) on POSIX platforms.  Note too that this is not suitable
for executable <em class="emph">programs</em> since some platforms support multiple
architectures using the same installed package directory.
</p>
<p>Subdirectory <samp class="file">po</samp> is used for files related to <em class="emph">localization</em>:
see <a class="pxref" href="#Internationalization">Internationalization</a>.
</p>
<p>Subdirectory <samp class="file">tools</samp> is the preferred place for auxiliary files
needed during configuration, and also for sources need to re-create
scripts (e.g. M4 files for <code class="command">autoconf</code>: some prefer to put
those in a subdirectory <samp class="file">m4</samp> of <samp class="file">tools</samp>).
</p>

<hr>
</div>
<div class="subsection-level-extent" id="Data-in-packages">
<div class="nav-panel">
<p>
Next: <a href="#Non_002dR-scripts-in-packages" accesskey="n" rel="next">Non-R scripts in packages</a>, Previous: <a href="#Package-subdirectories" accesskey="p" rel="prev">Package subdirectories</a>, Up: <a href="#Package-structure" accesskey="u" rel="up">Package structure</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Data-in-packages-1"><span>1.1.6 Data in packages<a class="copiable-link" href="#Data-in-packages-1"> &para;</a></span></h4>

<p>The <samp class="file">data</samp> subdirectory is for data files, either to be made
available <em class="emph">via</em> lazy-loading or for loading using <code class="code">data()</code>.
(The choice is made by the &lsquo;<samp class="samp">LazyData</samp>&rsquo; field in the
<samp class="file">DESCRIPTION</samp> file: the default is not to do so.)  It should not be
used for other data files needed by the package, and the convention has
grown up to use directory <samp class="file">inst/extdata</samp> for such files.
</p>
<p>Data files can have one of three types as indicated by their extension:
plain R code (<samp class="file">.R</samp> or <samp class="file">.r</samp>), tables (<samp class="file">.tab</samp>,
<samp class="file">.txt</samp>, or <samp class="file">.csv</samp>, see <code class="code">?data</code> for the file formats, and
note that <samp class="file">.csv</samp> is <strong class="strong">not</strong> the standard<a class="footnote" id="DOCF25" href="#FOOT25"><sup>25</sup></a> CSV format), or
<code class="code">save()</code> images (<samp class="file">.RData</samp> or <samp class="file">.rda</samp>).  The files should
not be hidden (have names starting with a dot).  Note that R code
should be if possible &ldquo;self-sufficient&rdquo; and not make use of extra
functionality provided by the package, so that the data file can also be
used without having to load the package or its namespace: it should run
as silently as possible and not change the <code class="code">search()</code> path by
attaching packages or other environments.
</p>
<p>Images (extensions <samp class="file">.RData</samp><a class="footnote" id="DOCF26" href="#FOOT26"><sup>26</sup></a> or <samp class="file">.rda</samp>) can contain
references to the namespaces of packages that were used to create them.
Preferably there should be no such references in data files, and in any
case they should only be to packages listed in the <code class="code">Depends</code> and
<code class="code">Imports</code> fields, as otherwise it may be impossible to install the
package.  To check for such references, load all the images into a
vanilla R session, run <code class="code">str()</code> on all the datasets, and look at
the output of <code class="code">loadedNamespaces()</code>.
</p>
<p>Particular care is needed where a dataset or one of its components is of
an S4 class, especially if the class is defined in a different package.
First, the package containing the class definition has to be available
to do useful things with the dataset, so that package must be listed in
<code class="code">Imports</code> or <code class="code">Depends</code> (even if this gives a check warning
about unused imports).  Second, the definition of an S4 class can
change, and often is unnoticed when in a package with a different
author.  So it may be wiser to use the <samp class="file">.R</samp> form and use that to
create the dataset object when needed (loading package namespaces but
not attaching them by using <code class="code">requireNamespace(<var class="var">pkg</var>, quietly =
TRUE)</code> and using <code class="code"><var class="var">pkg</var>::</code> to refer to objects in the
namespace).
</p>
<p>If you are not using &lsquo;<samp class="samp">LazyData</samp>&rsquo; and either your data files are large
or e.g., you use <samp class="file">data/foo.R</samp> scripts to produce your data, loading
your namespace, you 
can speed up installation by providing a file <samp class="file">datalist</samp> in the
<samp class="file">data</samp> subdirectory.  This should have one line per topic that
<code class="code">data()</code> will find, in the format &lsquo;<samp class="samp">foo</samp>&rsquo; if <code class="code">data(foo)</code>
provides &lsquo;<samp class="samp">foo</samp>&rsquo;, or &lsquo;<samp class="samp">foo: bar bah</samp>&rsquo; if <code class="code">data(foo)</code> provides
&lsquo;<samp class="samp">bar</samp>&rsquo; and &lsquo;<samp class="samp">bah</samp>&rsquo;.  <code class="command">R CMD build</code> will automatically add
a <samp class="file">datalist</samp> file to <samp class="file">data</samp> directories of over 1Mb, using the
function <code class="code">tools::add_datalist</code>.
</p>
<p>Tables (<samp class="file">.tab</samp>, <samp class="file">.txt</samp>, or <samp class="file">.csv</samp> files) can be
compressed by <code class="command">gzip</code>, <code class="command">bzip2</code> or <code class="command">xz</code>,
optionally with additional extension <samp class="file">.gz</samp>, <samp class="file">.bz2</samp> or
<samp class="file">.xz</samp>.
</p>
<p>If your package is to be distributed, do consider the resource
implications of large datasets for your users: they can make packages
very slow to download and use up unwelcome amounts of storage space, as
well as taking many seconds to load.  It is normally best to distribute
large datasets as <samp class="file">.rda</samp> images prepared by <code class="code">save(, compress =
TRUE)</code> (the default).  Using <code class="command">bzip2</code> or <code class="command">xz</code> compression
will usually reduce the size of both the package tarball and the
installed package, in some cases by a factor of two or more.
</p>
<p>Package <strong class="strong">tools</strong> has a couple of functions to help with data images:
<code class="code">checkRdaFiles</code> reports on the way the image was saved, and
<code class="code">resaveRdaFiles</code> will re-save with a different type of compression,
including choosing the best type for that particular image.
</p>
<p>Many packages using &lsquo;<samp class="samp">LazyData</samp>&rsquo; will benefit from using a form of
compression other than <code class="command">gzip</code> in the installed lazy-loading
database.  This can be selected by the <samp class="option">--data-compress</samp> option
to <code class="command">R CMD INSTALL</code> or by using the &lsquo;<samp class="samp">LazyDataCompression</samp>&rsquo;
field in the <samp class="file">DESCRIPTION</samp> file.  Useful values are <code class="code">bzip2</code>,
<code class="code">xz</code> and the default, <code class="code">gzip</code>: value <code class="code">none</code> is also
accepted.  The only way to discover which is best is to try them all and
look at the size of the <samp class="file"><var class="var">pkgname</var>/data/Rdata.rdb</samp> file.  A
function to do that (quoting sizes in KB) is
</p><div class="example">
<pre class="example-preformatted">CheckLazyDataCompression &lt;- function(pkg)
{
    pkg_name &lt;- sub(&quot;_.*&quot;, &quot;&quot;, pkg)
    lib &lt;- tempfile(); dir.create(lib)
    zs &lt;- c(&quot;gzip&quot;, &quot;bzip2&quot;, &quot;xz&quot;)
    res &lt;- integer(3); names(res) &lt;- zs
    for (z in zs) {
        opts &lt;- c(paste0(&quot;--data-compress=&quot;, z),
                  &quot;--no-libs&quot;, &quot;--no-help&quot;, &quot;--no-demo&quot;, &quot;--no-exec&quot;, &quot;--no-test-load&quot;)
        install.packages(pkg, lib, INSTALL_opts = opts, repos = NULL, quiet = TRUE)
        res[z] &lt;- file.size(file.path(lib, pkg_name, &quot;data&quot;, &quot;Rdata.rdb&quot;))
    }
    ceiling(res/1024)
}
</pre></div>

<p>(applied to a source package without any &lsquo;<samp class="samp">LazyDataCompression</samp>&rsquo;
field).  <code class="command">R CMD check</code> will warn if it finds a
<samp class="file"><var class="var">pkgname</var>/data/Rdata.rdb</samp> file of more than 5MB without
&lsquo;<samp class="samp">LazyDataCompression</samp>&rsquo; being set.  If you see that, run
<code class="code">CheckLazyDataCompression()</code> and set the field &ndash; to <code class="code">gzip</code> in
the unlikely event<a class="footnote" id="DOCF27" href="#FOOT27"><sup>27</sup></a> that is the best choice.
</p>
<p>The analogue for <samp class="file">sysdata.rda</samp> is field &lsquo;<samp class="samp">SysDataCompression</samp>&rsquo;:
the default is <code class="code">xz</code> for files bigger than 1MB otherwise
<code class="code">gzip</code>.
</p>
<p>Lazy-loading is not supported for very large datasets (those which when
serialized exceed 2GB, the limit for the format on 32-bit platforms).
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Non_002dR-scripts-in-packages">
<div class="nav-panel">
<p>
Next: <a href="#Specifying-URLs" accesskey="n" rel="next">Specifying URLs</a>, Previous: <a href="#Data-in-packages" accesskey="p" rel="prev">Data in packages</a>, Up: <a href="#Package-structure" accesskey="u" rel="up">Package structure</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Non_002dR-scripts-in-packages-1"><span>1.1.7 Non-R scripts in packages<a class="copiable-link" href="#Non_002dR-scripts-in-packages-1"> &para;</a></span></h4>

<p>Code which needs to be compiled (C, C++, Fortran &hellip;)
is included in the <samp class="file">src</samp> subdirectory and discussed elsewhere in
this document.
</p>
<p>Subdirectory <samp class="file">exec</samp> could be used for scripts for interpreters such
as the shell, BUGS, JavaScript, Matlab, Perl, PHP (<a class="url" href="https://CRAN.R-project.org/package=amap"><strong class="strong">amap</strong></a>),
Python or Tcl (<a class="url" href="https://CRAN.R-project.org/package=Simile"><strong class="strong">Simile</strong></a>), or even R.  However, it seems more
common to use the <samp class="file">inst</samp> directory, for example
<samp class="file">WriteXLS/inst/Perl</samp>, <samp class="file">NMF/inst/m-files</samp>,
<samp class="file">RnavGraph/inst/tcl</samp>, <samp class="file">RProtoBuf/inst/python</samp> and
<samp class="file">emdbook/inst/BUGS</samp> and <samp class="file">gridSVG/inst/js</samp>.
</p>
<p>Java code is a special case: except for very small programs,
<samp class="file">.java</samp> files should be byte-compiled (to a <samp class="file">.class</samp> file) and
distributed as part of a <samp class="file">.jar</samp> file: the conventional location for
the <samp class="file">.jar</samp> file(s) is <samp class="file">inst/java</samp>.  It is desirable (and
required under an Open Source license) to make the Java source files
available: this is best done in a top-level <samp class="file">java</samp> directory in the
package&mdash;the source files should not be installed.
</p>
<p>If your package requires one of these interpreters or an extension then
this should be declared in the &lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field of its
<samp class="file">DESCRIPTION</samp> file.  (Users of Java most often do so <em class="emph">via</em>
<a class="url" href="https://CRAN.R-project.org/package=rJava"><strong class="strong">rJava</strong></a>, when depending on/importing that suffices unless there
is a version requirement on Java code in the package.)
</p>
<p>Windows and Mac users should be aware that the Tcl extensions
&lsquo;<samp class="samp">BWidget</samp>&rsquo; and &lsquo;<samp class="samp">Tktable</samp>&rsquo; (which have sometimes been included in
the Windows<a class="footnote" id="DOCF28" href="#FOOT28"><sup>28</sup></a> and macOS R installers)
<em class="emph">are</em> extensions and do need to be declared (and that
&lsquo;<samp class="samp">Tktable</samp>&rsquo; is less widely available than it used to be, including
not in the main repositories for major Linux distributions).
&lsquo;<samp class="samp">BWidget</samp>&rsquo; needs to be installed by the user on other OSes.  This is
fairly easy to do: first find the Tcl search path:
</p>
<div class="example">
<pre class="example-preformatted">library(tcltk)
strsplit(tclvalue('auto_path'), &quot; &quot;)[[1]]
</pre></div>

<p>then download the sources from
<a class="uref" href="https://sourceforge.net/projects/tcllib/files/BWidget/">https://sourceforge.net/projects/tcllib/files/BWidget/</a>
and in a terminal run something like
</p>
<div class="example">
<pre class="example-preformatted">tar xf bwidget-1.9.14.tar.gz
sudo mv bwidget-1.9.14 /usr/local/lib
</pre></div>

<p>substituting a location on the Tcl search path for <samp class="file">/usr/local/lib</samp> if
needed.  (If no location on that search path is writeable, you will need
to add one each time &lsquo;<samp class="samp">BWidget</samp>&rsquo; is to be used with <code class="code">tcltk::addTclPath()</code>.)
</p>
<p>To (silently) test for the presence of &lsquo;<samp class="samp">Tktable</samp>&rsquo; one can use
</p>
<div class="example">
<pre class="example-preformatted">library(tcltk)
have_tktable &lt;- !isFALSE(suppressWarnings(tclRequire('Tktable')))
</pre></div>

<p>Installing &lsquo;<samp class="samp">Tktable</samp>&rsquo; needs a C compiler and the Tk headers (not
necessarily installed with Tcl/Tk).  At the time of writing the latest
sources (from 2008) were available from
<a class="uref" href="https://sourceforge.net/projects/tktable/files/tktable/2.10/Tktable2.10.tar.gz/download">https://sourceforge.net/projects/tktable/files/tktable/2.10/Tktable2.10.tar.gz/download</a>,
but needed patching for current Tk (8.6.11, but not 8.6.10) &ndash; a patch
can be found at <a class="uref" href="https://www.stats.ox.ac.uk/pub/bdr/Tktable/">https://www.stats.ox.ac.uk/pub/bdr/Tktable/</a>. For
a system installation of Tk you may need to install &lsquo;<samp class="samp">Tktable</samp>&rsquo; as
&lsquo;<samp class="samp">root</samp>&rsquo; as on e.g. Fedora all the locations on <code class="code">auto_path</code>
are owned by &lsquo;<samp class="samp">root</samp>&rsquo;.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Specifying-URLs">
<div class="nav-panel">
<p>
Previous: <a href="#Non_002dR-scripts-in-packages" accesskey="p" rel="prev">Non-R scripts in packages</a>, Up: <a href="#Package-structure" accesskey="u" rel="up">Package structure</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Specifying-URLs-1"><span>1.1.8 Specifying URLs<a class="copiable-link" href="#Specifying-URLs-1"> &para;</a></span></h4>

<p>URLs in many places in the package documentation will be converted to
clickable hyperlinks in at least some of their renderings.  So care is
needed that their forms are correct and portable.
</p>
<p>The full URL should be given, including the scheme (often &lsquo;<samp class="samp">http://</samp>&rsquo;
or &lsquo;<samp class="samp">https://</samp>&rsquo;) and a final &lsquo;<samp class="samp">/</samp>&rsquo; for references to directories.
</p>
<p>Spaces in URLs are not portable and how they are handled does vary by
HTTP server and by client.  There should be no space in the host part of
an &lsquo;<samp class="samp">http://</samp>&rsquo; URL, and spaces in the remainder should be encoded,
with each space replaced by &lsquo;<samp class="samp">%20</samp>&rsquo;.
</p>
<p>Other characters may benefit from being encoded: see the help on
<code class="code">URLencode()</code>.
</p>
<p>The canonical URL for a <abbr class="acronym">CRAN</abbr> package is
</p><div class="example">
<pre class="example-preformatted">https://cran.r-project.org/package=<var class="var">pkgname</var>
</pre></div>

<p>and not a version starting
&lsquo;<samp class="samp">https://cran.r-project.org/web/packages/<var class="var">pkgname</var></samp>&rsquo;.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Configure-and-cleanup">
<div class="nav-panel">
<p>
Next: <a href="#Checking-and-building-packages" accesskey="n" rel="next">Checking and building packages</a>, Previous: <a href="#Package-structure" accesskey="p" rel="prev">Package structure</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Configure-and-cleanup-1"><span>1.2 Configure and cleanup<a class="copiable-link" href="#Configure-and-cleanup-1"> &para;</a></span></h3>

<p>Note that most of this section is specific to Unix-alikes: see the
comments later on about the Windows port of R.
</p>
<p>If your package needs some system-dependent configuration before
installation you can include an executable (Bourne<a class="footnote" id="DOCF29" href="#FOOT29"><sup>29</sup></a>  shell script <samp class="file">configure</samp>
in your package which (if present) is executed by <code class="code">R CMD INSTALL</code>
before any other action is performed.  This can be a script created by
the Autoconf mechanism, but may also be a script written by yourself.
Use this to detect if any nonstandard libraries are present such that
corresponding code in the package can be disabled at install time rather
than giving error messages when the package is compiled or used.  To
summarize, the full power of Autoconf is available for your extension
package (including variable substitution, searching for libraries,
etc.).  Background and useful tips on Autoconf and related tools
(including <code class="command">pkg-config</code> described below) can be found at
<a class="uref" href="https://autotools.info/">https://autotools.info/</a>.
</p>
<a class="index-entry-id" id="index-R_005fPACKAGE_005fDIR"></a>
<a class="index-entry-id" id="index-R_005fPACKAGE_005fNAME"></a>
<p>A <code class="command">configure</code> script is run in an environment which has all the
environment variables set for an R session (see
<samp class="file"><var class="var">R_HOME</var>/etc/Renviron</samp>) plus <code class="code">R_PACKAGE_NAME</code> (the name of
the package), <code class="code">R_PACKAGE_DIR</code> (the path of the target installation
directory of the package, a temporary location for staged installs) and
<code class="code">R_ARCH</code> (the arch-dependent part of the path, often empty).
</p>
<p>Under a Unix-alike only, an executable (Bourne shell) script
<code class="command">cleanup</code> is executed as the last thing by <code class="code">R CMD INSTALL</code> if
option <samp class="option">--clean</samp> was given, and by <code class="code">R CMD build</code> when
preparing the package for building from its source.
</p>
<p>As an example consider we want to use functionality provided by a (C or
Fortran) library <code class="code">foo</code>.  Using Autoconf, we can create a configure
script which checks for the library, sets variable <code class="code">HAVE_FOO</code> to
<code class="code">TRUE</code> if it was found and to <code class="code">FALSE</code> otherwise, and then
substitutes this value into output files (by replacing instances of
&lsquo;<samp class="samp">@HAVE_FOO@</samp>&rsquo; in input files with the value of <code class="code">HAVE_FOO</code>).
For example, if a function named <code class="code">bar</code> is to be made available by
linking against library <code class="code">foo</code> (i.e., using <samp class="option">-lfoo</samp>), one
could use
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">AC_CHECK_LIB(foo, <var class="var">fun</var>, [HAVE_FOO=TRUE], [HAVE_FOO=FALSE])
AC_SUBST(HAVE_FOO)
......
AC_CONFIG_FILES([foo.R])
AC_OUTPUT
</pre></div></div>

<p>in <samp class="file">configure.ac</samp> (assuming Autoconf 2.50 or later).
</p>
<p>The definition of the respective R function in <samp class="file">foo.R.in</samp> could be
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">foo &lt;- function(x) {
    if(!@HAVE_FOO@)
      stop(&quot;Sorry, library ‘foo’ is not available&quot;)
    ...
</pre></div></div>

<p>From this file <code class="command">configure</code> creates the actual R source file
<samp class="file">foo.R</samp> looking like
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">foo &lt;- function(x) {
    if(!FALSE)
      stop(&quot;Sorry, library ‘foo’ is not available&quot;)
    ...
</pre></div></div>

<p>if library <code class="code">foo</code> was not found (with the desired functionality).
In this case, the above R code effectively disables the function.
</p>
<p>One could also use different file fragments for available and missing
functionality, respectively.
</p>
<p>You will very likely need to ensure that the same C compiler and
compiler flags are used in the <samp class="file">configure</samp> tests as when compiling
R or your package.  Under a Unix-alike, you can achieve this by
including the following fragment early in <samp class="file">configure.ac</samp>
(<em class="emph">before</em> calling <code class="code">AC_PROG_CC</code> or anything which calls it)
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">: ${R_HOME=`R RHOME`}
if test -z &quot;${R_HOME}&quot;; then
  echo &quot;could not determine R_HOME&quot;
  exit 1
fi
CC=`&quot;${R_HOME}/bin/R&quot; CMD config CC`
CFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CFLAGS`
CPPFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CPPFLAGS`
</pre></div></div>

<p>(Using &lsquo;<samp class="samp">${R_HOME}/bin/R</samp>&rsquo; rather than just &lsquo;<samp class="samp">R</samp>&rsquo; is necessary
in order to use the correct version of R when running the script as
part of <code class="code">R CMD INSTALL</code>, and the quotes since &lsquo;<samp class="samp">${R_HOME}</samp>&rsquo;
might contain spaces.)
</p>
<p>If your code does load checks (for example, to check for an entry point in
a library or to run code) then you will also need
</p><div class="example">
<pre class="example-preformatted">LDFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config LDFLAGS`
</pre></div>

<p>Packages written with C++ need to pick up the details for the C++
compiler and switch the current language to C++ by something like
</p><div class="example">
<pre class="example-preformatted">CXX=`&quot;${R_HOME}/bin/R&quot; CMD config CXX`
if test -z &quot;$CXX&quot;; then
  AC_MSG_ERROR([No C++ compiler is available])
fi
CXXFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CXXFLAGS`
CPPFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CPPFLAGS`
AC_LANG(C++)
</pre></div>

<p>The latter is important, as for example C headers may not be available
to C++ programs or may not be written to avoid C++ name-mangling.  Note
that an R installation is not required to have a C++ compiler so
&lsquo;<samp class="samp">CXX</samp>&rsquo; may be empty.  If the package specifies a non-default C++
standard, use the <code class="command">config</code> variable names (such as <code class="code">CXX17</code>)
appropriate to the standard, but still set <code class="code">CXX</code> and
<code class="code">CXXFLAGS</code>.
</p>
<a class="index-entry-id" id="index-R-CMD-config"></a>
<p>You can use <code class="code">R CMD config</code> to get the value of the basic
configuration variables, and also the header and library flags necessary
for linking a front-end executable program against R, see <kbd class="kbd">R CMD
config --help</kbd> for details.  If you do, it is essential that you use
both the command and the appropriate flags, so that for example
&lsquo;<samp class="samp">CC</samp>&rsquo; must always be used with &lsquo;<samp class="samp">CFLAGS</samp>&rsquo; and (for code to be
linked into a shared library) &lsquo;<samp class="samp">CPICFLAGS</samp>&rsquo;.  For Fortran, be careful
to use &lsquo;<samp class="samp">FC FFLAGS FPICFLAGS</samp>&rsquo; for fixed-form Fortran and 
&lsquo;<samp class="samp">FC FCFLAGS FPICFLAGS</samp>&rsquo; for free-form Fortran.
</p>
<p>As from R 4.3.0, variables
</p><div class="example">
<pre class="example-preformatted">CC CFLAGS CXX CXXFLAGS CPPFLAGS LDFLAGS FC FCFLAGS
</pre></div>
<p>are set in the environment (if not already set) when <code class="command">configure</code>
is called from <code class="command">R CMD INSTALL</code>, in case the script forgets to
set them as described above.  This includes making use of the selected C
standard (but not the C++ standard as that is selected at a later stage
by  <code class="command">R CMD SHLIB</code>).
</p>
<p>To check for an external BLAS library using the <code class="code">AX_BLAS</code> macro
from the official Autoconf Macro
Archive<a class="footnote" id="DOCF30" href="#FOOT30"><sup>30</sup></a>, one
can use
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">FC=`&quot;${R_HOME}/bin/R&quot; CMD config FC`
FCLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config FFLAGS`
AC_PROG_FC
FLIBS=`&quot;${R_HOME}/bin/R&quot; CMD config FLIBS`
AX_BLAS([], AC_MSG_ERROR([could not find your BLAS library], 1))
</pre></div></div>
<p>Note that <code class="code">FLIBS</code> as determined by R must be used to ensure that
Fortran code works on all R platforms.  
</p>

<p><strong class="strong">N.B.</strong>: If the <code class="command">configure</code> script creates files, e.g.
<samp class="file">src/Makevars</samp>, you do need a <code class="command">cleanup</code> script to remove
them.  Otherwise <code class="command">R CMD build</code> may ship the files that are
created.  For example, package <a class="url" href="https://CRAN.R-project.org/package=RODBC"><strong class="strong">RODBC</strong></a> has
</p>
<div class="example">
<pre class="example-preformatted">#!/bin/sh

rm -f config.* src/Makevars src/config.h
</pre></div>

<p>As this example shows, <code class="command">configure</code> often creates working files
such as <samp class="file">config.log</samp>.  If you use a hand-crafted script
rather than one created by <code class="command">autoconf</code>, it is highly recommended
that you log its actions to file <samp class="file">config.log</samp>.
</p>
<p>If your configure script needs auxiliary files, it is recommended that
you ship them in a <samp class="file">tools</samp> directory (as R itself does).
</p>
<p>You should bear in mind that the configure script will not be used on
Windows systems.  If your package is to be made publicly available,
please give enough information for a user on a non-Unix-alike platform
to configure it manually, or provide a <samp class="file">configure.win</samp> script (or
<samp class="file">configure.ucrt</samp>) to be used on that platform.  (Optionally, there
can be a <samp class="file">cleanup.win</samp> script (or <samp class="file">cleanup.ucrt</samp>).  Both
should be shell scripts to be executed by <code class="command">ash</code>, which is a
minimal version of Bourne-style <code class="command">sh</code>. As from R 4.2.0,
<code class="command">bash</code> is used.  When <samp class="file">configure.win</samp> (or
<samp class="file">configure.ucrt</samp>) is run the environment variables <code class="env">R_HOME</code>
(which uses &lsquo;<samp class="samp">/</samp>&rsquo; as the file separator), <code class="env">R_ARCH</code> and
<code class="env">R_ARCH_BIN</code> will be set.  Use <code class="env">R_ARCH</code> to decide if this is a
64-bit build for Intel (its value there is &lsquo;<samp class="samp">/x64</samp>&rsquo;) and to install DLLs to the
correct place (<samp class="file">${R_HOME}/libs${R_ARCH}</samp>).  Use
<code class="env">R_ARCH_BIN</code> to find the correct place under the <samp class="file">bin</samp>
directory, e.g. <samp class="file">${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe</samp>.  If
a <samp class="file">configure.win</samp> script does compilation (including calling
<code class="command">R CMD SHLIB</code>), most of the considerations above apply.
</p>
<p>As the scripts on Windows are executed as <code class="command">sh ./configure.win</code>
and similar, any &rsquo;shebang&rsquo; first line  (such as <code class="code">#! /bin/bash</code>) is
treated as a comment.
</p>
<p>In some rare circumstances, the configuration and cleanup scripts need
to know the location into which the package is being installed.  An
example of this is a package that uses C code and creates two shared
object/DLLs.  Usually, the object that is dynamically loaded by R
is linked against the second, dependent, object.  On some systems, we
can add the location of this dependent object to the object that is
dynamically loaded by R.  This means that each user does not have to
set the value of the <code class="env">LD_LIBRARY_PATH</code> (or equivalent) environment
variable, but that the secondary object is automatically resolved.
Another example is when a package installs support files that are
required at run time, and their location is substituted into an R
data structure at installation time.
<a class="index-entry-id" id="index-R_005fLIBRARY_005fDIR"></a>
<a class="index-entry-id" id="index-R_005fPACKAGE_005fDIR-1"></a>
<a class="index-entry-id" id="index-R_005fPACKAGE_005fNAME-1"></a>
The names of the top-level library directory (i.e., specifiable
<em class="emph">via</em> the &lsquo;<samp class="samp">-l</samp>&rsquo; argument) and the directory of the package
itself are made available to the installation scripts <em class="emph">via</em> the two
shell/environment variables <code class="env">R_LIBRARY_DIR</code> and <code class="env">R_PACKAGE_DIR</code>.
Additionally, the name of the package (e.g. &lsquo;<samp class="samp">survival</samp>&rsquo; or
&lsquo;<samp class="samp">MASS</samp>&rsquo;) being installed is available from the environment variable
<code class="env">R_PACKAGE_NAME</code>.  (Currently the value of <code class="env">R_PACKAGE_DIR</code> is
always <code class="code">${R_LIBRARY_DIR}/${R_PACKAGE_NAME}</code>, but this used not to
be the case when versioned installs were allowed.  Its main use is in
<samp class="file">configure.win</samp> (or <samp class="file">configure.ucrt</samp>) scripts for the installation path of external
software&rsquo;s DLLs.)  Note that the value of <code class="env">R_PACKAGE_DIR</code> may
contain spaces and other shell-unfriendly characters, and so should be
quoted in makefiles and configure scripts.
</p>
<p>One of the more tricky tasks can be to find the headers and libraries of
external software.  One tool which is increasingly available on
Unix-alikes (but not by default<a class="footnote" id="DOCF31" href="#FOOT31"><sup>31</sup></a>  on macOS) to
do this is <code class="command">pkg-config</code>.  The <samp class="file">configure</samp> script will need
to test for the presence of the command itself<a class="footnote" id="DOCF32" href="#FOOT32"><sup>32</sup></a>
(see for example package <a class="url" href="https://CRAN.R-project.org/package=tiff"><strong class="strong">tiff</strong></a>), and if present it can be
asked if the software is installed, of a suitable version and for
compilation/linking flags by e.g.
</p>
<div class="example">
<pre class="example-preformatted">$ pkg-config --exists ‘libtiff-4 &gt;= 4.1.0’ --print-errors # check the status
$ pkg-config --modversion libtiff-4
4.3.0
$ pkg-config --cflags libtiff-4
-I/usr/local/include
$ pkg-config --libs libtiff-4
-L/usr/local/lib -ltiff
$ pkg-config --static --libs libtiff-4
-L/usr/local/lib -ltiff -lwebp -llzma -ljpeg -lz
</pre></div>

<p>Note that <code class="command">pkg-config --libs</code> gives the information required to
link against the default version<a class="footnote" id="DOCF33" href="#FOOT33"><sup>33</sup></a> of that library (usually the dynamic one), and
<code class="command">pkg-config --static --libs</code> may be needed if the static library is
to be used.
</p>
<p>Static libraries are commonly used on macOS and Windows to facilitate
bundling external software with binary distributions of packages.  This
means that portable (source) packages need to allow for this.  It is
<em class="emph">not</em> safe to just use <code class="command">pkg-config --static --libs</code>, as
that will often include further libraries that are not necessarily
installed on the user&rsquo;s system (or maybe only the versioned library such
as <samp class="file">libjbig.so.2.1</samp> is installed and not <samp class="file">libjbig.so</samp> which
would be needed to use <code class="code">-ljbig</code> sometimes included in
<code class="command">pkg-config --static --libs libtiff-4</code>).
</p>
<p>Another issue is that <code class="command">pkg-config --exists</code> may not be reliable.
It checks not only that the &lsquo;module&rsquo; is available but <em class="emph">all</em> of the
dependencies, including those in principle needed for static linking.
(XQuartz 2.8.x only distributed dynamic libraries and not some of the
<samp class="file">.pc</samp> files needed for <code class="code">--exists</code>.)
</p>
<p>Sometimes the name by which the software is known to
<code class="command">pkg-config</code> is not what one might expect (e.g.
&lsquo;<samp class="samp">libxml-2.0</samp>&rsquo; even for 2.9.x).  To get a complete list use
</p>
<div class="example">
<pre class="example-preformatted">pkg-config --list-all | sort
</pre></div>

<p>Some external software provides a <samp class="file">-config</samp> command to do a similar
job to <code class="command">pkg-config</code>, including
</p><div class="example">
<pre class="example-preformatted">curl-config   freetype-config  gdal-config    geos-config
gsl-config    iodbc-config     libpng-config  nc-config
pcre-config   pcre2-config     xml2-config    xslt-config
</pre></div>
<p>(<code class="command">curl-config</code> is for <code class="code">libcurl</code> not <code class="command">curl</code>.
<code class="command">nc-config</code> is for <code class="code">netcdf</code>.)  Most have an option to use
static libraries.
</p>
<p><strong class="strong">N.B.</strong>  These commands indicate what header paths and
libraries are needed, but they do not obviate the need to check that the
recipes they give actually work.  (This is especially necessary for
platforms which use static linking.)
</p>
<p>If using Autoconf it is good practice to include all the Autoconf
sources in the package (and required for an Open Source package and
tested by <code class="command">R CMD check --as-cran</code>).  This will include the file
<samp class="file">configure.ac</samp><a class="footnote" id="DOCF34" href="#FOOT34"><sup>34</sup></a> in the top-level directory of the package.  If
extensions written in <code class="command">m4</code> are needed, these should be included
under the directory <samp class="file">tools</samp> and included from <samp class="file">configure.ac</samp>
<em class="emph">via</em> e.g.,
</p><div class="example">
<pre class="example-preformatted">m4_include([tools/ax_pthread.m4])
</pre></div>
<p>Alternatively, Autoconf can be asked to search all <samp class="file">.m4</samp> files in a
directory by including something like<a class="footnote" id="DOCF35" href="#FOOT35"><sup>35</sup></a>
</p><div class="example">
<pre class="example-preformatted">AC_CONFIG_MACRO_DIR([tools/m4])
</pre></div>
<p>One source of such extensions is the &lsquo;Autoconf Archive&rsquo;
(<a class="uref" href="https://www.gnu.org/software/autoconf-archive/">https://www.gnu.org/software/autoconf-archive/</a>.  It is not
safe to assume this is installed on users&rsquo; machines, so the extension
should be shipped with the package (taking care to comply with its
licence).
</p>

<ul class="mini-toc">
<li><a href="#Using-Makevars" accesskey="1">Using <samp class="file">Makevars</samp></a></li>
<li><a href="#Configure-example" accesskey="2">Configure example</a></li>
<li><a href="#Using-modern-Fortran-code" accesskey="3">Using modern Fortran code</a></li>
<li><a href="#Using-C_002b_002b-code" accesskey="4">Using C++ code</a></li>
<li><a href="#C-standards" accesskey="5">C standards</a></li>
<li><a href="#Using-cmake" accesskey="6">Using <code class="command">cmake</code></a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Using-Makevars">
<div class="nav-panel">
<p>
Next: <a href="#Configure-example" accesskey="n" rel="next">Configure example</a>, Previous: <a href="#Configure-and-cleanup" accesskey="p" rel="prev">Configure and cleanup</a>, Up: <a href="#Configure-and-cleanup" accesskey="u" rel="up">Configure and cleanup</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-Makevars-1"><span>1.2.1 Using <samp class="file">Makevars</samp><a class="copiable-link" href="#Using-Makevars-1"> &para;</a></span></h4>


<p>Sometimes writing your own <samp class="file">configure</samp> script can be avoided by
supplying a file <samp class="file">Makevars</samp>: also one of the most common uses of a
<samp class="file">configure</samp> script is to make <samp class="file">Makevars</samp> from
<samp class="file">Makevars.in</samp>.
</p>
<p>A <samp class="file">Makevars</samp> file is a makefile and is used as one of several
makefiles by <code class="command">R CMD SHLIB</code> (which is called by <code class="command">R CMD
INSTALL</code> to compile code in the <samp class="file">src</samp> directory).  It should be
written if at all possible in a portable style, in particular (except
for <samp class="file">Makevars.win</samp> and <samp class="file">Makevars.ucrt</samp>) without the use of GNU
extensions.
</p>
<p>The most common use of a <samp class="file">Makevars</samp> file is to set additional
preprocessor options (for example include paths and definitions) for
C/C++ files <em class="emph">via</em> <code class="code">PKG_CPPFLAGS</code>, and additional compiler
flags by setting <code class="code">PKG_CFLAGS</code>, <code class="code">PKG_CXXFLAGS</code> or
<code class="code">PKG_FFLAGS</code>, for C, C++ or Fortran respectively (see <a class="pxref" href="#Creating-shared-objects">Creating shared objects</a>).
</p>
<p><strong class="strong">N.B.</strong>: Include paths are preprocessor options, not compiler
options, and <strong class="strong">must</strong> be set in <code class="code">PKG_CPPFLAGS</code> as otherwise
platform-specific paths (e.g. &lsquo;<samp class="samp">-I/usr/local/include</samp>&rsquo;) will take
precedence.  <code class="code">PKG_CPPFLAGS</code> should contain &lsquo;<samp class="samp">-I</samp>&rsquo;, &lsquo;<samp class="samp">-D</samp>&rsquo;,
&lsquo;<samp class="samp">-U</samp>&rsquo; and (where supported) &lsquo;<samp class="samp">-include</samp>&rsquo; and &lsquo;<samp class="samp">-pthread</samp>&rsquo;
options: everything else should be a compiler flag.  The order of flags
matters, and using &lsquo;<samp class="samp">-I</samp>&rsquo; in <code class="code">PKG_CFLAGS</code> or <code class="code">PKG_CXXFLAGS</code>
has led to hard-to-debug platform-specific errors.
</p>
<p><samp class="file">Makevars</samp> can also be used to set flags for the linker, for
example &lsquo;<samp class="samp">-L</samp>&rsquo; and &lsquo;<samp class="samp">-l</samp>&rsquo; options, <em class="emph">via</em> <code class="code">PKG_LIBS</code>.
</p>
<p>When writing a <samp class="file">Makevars</samp> file for a package you intend to
distribute, take care to ensure that it is not specific to your
compiler: flags such as <samp class="option">-O2 -Wall -pedantic</samp> (and all other
<samp class="option">-W</samp> flags: for the Oracle compilers these were used to pass
arguments to compiler phases) are all specific to GCC (and compilers such
as <code class="command">clang</code> which aim to be options-compatible with it).
</p>
<p>Also, do not set variables such as <code class="code">CPPFLAGS</code>, <code class="code">CFLAGS</code> etc.:
these should be settable by users (sites) through appropriate personal
(site-wide) <samp class="file">Makevars</samp> files.
See <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Customizing-package-compilation">Customizing package compilation</a> in <cite class="cite">R Installation and Administration</cite>,
</p>
<p>There are some macros<a class="footnote" id="DOCF36" href="#FOOT36"><sup>36</sup></a>  which are set whilst configuring the
building of R itself and are stored in
<samp class="file"><var class="var">R_HOME</var>/etc<var class="var">R_ARCH</var>/Makeconf</samp>.  That makefile is included
as a <samp class="file">Makefile</samp> <em class="emph">after</em> <samp class="file">Makevars[.win]</samp>, and the macros
it defines can be used in macro assignments and make command lines in
the latter.  These include
</p>
<dl class="table">
<dt><a id="index-FLIBS"></a><span><code class="code">FLIBS</code><a class="copiable-link" href="#index-FLIBS"> &para;</a></span></dt>
<dd><p>A macro containing the set of libraries need to link Fortran code.  This
may need to be included in <code class="code">PKG_LIBS</code>: it will normally be included
automatically if the package contains Fortran source files in the
<samp class="file">src</samp> directory.
</p>
</dd>
<dt><a id="index-BLAS_005fLIBS"></a><span><code class="code">BLAS_LIBS</code><a class="copiable-link" href="#index-BLAS_005fLIBS"> &para;</a></span></dt>
<dd><p>A macro containing the BLAS libraries used when building R.  This may
need to be included in <code class="code">PKG_LIBS</code>.  Beware that if it is empty then
the R executable will contain all the double-precision and
double-complex BLAS routines, but no single-precision nor complex
routines.  If <code class="code">BLAS_LIBS</code> is included, then <code class="code">FLIBS</code> also needs
to be<a class="footnote" id="DOCF37" href="#FOOT37"><sup>37</sup></a>  included following it, as most BLAS
libraries are written at least partially in Fortran.  However, it can
be omitted if the package contains Fortran source code as that will add
<code class="code">FLIBS</code> to the link line.
</p>
</dd>
<dt><a id="index-LAPACK_005fLIBS"></a><span><code class="code">LAPACK_LIBS</code><a class="copiable-link" href="#index-LAPACK_005fLIBS"> &para;</a></span></dt>
<dd><p>A macro containing the LAPACK libraries (and paths where appropriate)
used when building R.  This may need to be included in
<code class="code">PKG_LIBS</code>.  It may point to a dynamic library <code class="code">libRlapack</code>
which contains the main double-precision LAPACK routines as well as
those double-complex LAPACK routines needed to build R, or it may
point to an external LAPACK library, or may be empty if an external BLAS
library also contains LAPACK.
</p>
<p>[<code class="code">libRlapack</code> includes all the double-precision LAPACK routines
which were current in 2003 and a few more recent ones: a list of which
routines are included is in file <samp class="file">src/modules/lapack/README</samp>. Note
that an external LAPACK/BLAS library need not do so, as some were
&lsquo;deprecated&rsquo; (and not compiled by default) in LAPACK 3.6.0 in late
2015.]
</p>
<p>For portability, the macros <code class="code">BLAS_LIBS</code> and <code class="code">FLIBS</code> should
always be included <em class="emph">after</em> <code class="code">LAPACK_LIBS</code> (and in that order).
</p>
</dd>
<dt><a id="index-SAFE_005fFFLAGS"></a><span><code class="code">SAFE_FFLAGS</code><a class="copiable-link" href="#index-SAFE_005fFFLAGS"> &para;</a></span></dt>
<dd><p>A macro containing flags which are needed to circumvent
over-optimization of FORTRAN code: it is might be &lsquo;<samp class="samp">-g -O2
-ffloat-store</samp>&rsquo; or &lsquo;<samp class="samp">-g -O2 -msse2 -mfpmath=sse</samp>&rsquo; on &lsquo;<samp class="samp">ix86</samp>&rsquo;
platforms using <code class="command">gfortran</code>.  Note that this is <strong class="strong">not</strong> an
additional flag to be used as part of <code class="code">PKG_FFLAGS</code>, but a
replacement for <code class="code">FFLAGS</code>.  See the example later in this section.
</p></dd>
</dl>

<a class="index-entry-id" id="index-OBJECTS"></a>
<p>Setting certain macros in <samp class="file">Makevars</samp> will prevent <code class="command">R CMD
SHLIB</code> setting them: in particular if <samp class="file">Makevars</samp> sets
&lsquo;<samp class="samp">OBJECTS</samp>&rsquo; it will not be set on the <code class="command">make</code> command line.
This can be useful in conjunction with implicit rules to allow other
types of source code to be compiled and included in the shared object.
It can also be used to control the set of files which are compiled,
either by excluding some files in <samp class="file">src</samp> or including some files in
subdirectories.  For example
</p>
<div class="example">
<pre class="example-preformatted">OBJECTS = 4dfp/endianio.o 4dfp/Getifh.o R4dfp-object.o
</pre></div>


<p>Note that <samp class="file">Makevars</samp> should not normally contain targets, as it is
included before the default makefile and <code class="command">make</code> will call the
first target, intended to be <code class="code">all</code> in the default makefile.  If you
really need to circumvent that, use a suitable (phony) target <code class="code">all</code>
before any actual targets in <samp class="file">Makevars.[win]</samp>: for example package
<a class="url" href="https://CRAN.R-project.org/package=fastICA"><strong class="strong">fastICA</strong></a> used to have
</p>
<div class="example">
<pre class="example-preformatted">PKG_LIBS = @BLAS_LIBS@

SLAMC_FFLAGS=$(R_XTRA_FFLAGS) $(FPICFLAGS) $(SHLIB_FFLAGS) $(SAFE_FFLAGS)

all: $(SHLIB)

slamc.o: slamc.f
        $(FC) $(SLAMC_FFLAGS) -c -o slamc.o slamc.f
</pre></div>

<p>needed to ensure that the LAPACK routines find some constants without
infinite looping.  The Windows equivalent was
</p>
<div class="example">
<pre class="example-preformatted">all: $(SHLIB)

slamc.o: slamc.f
        $(FC) $(SAFE_FFLAGS) -c -o slamc.o slamc.f
</pre></div>

<p>(since the other macros are all empty on that platform, and R&rsquo;s
internal BLAS was not used).  Note that the first target in
<samp class="file">Makevars</samp> will be called, but for back-compatibility it is best
named <code class="code">all</code>.
</p>
<p>If you want to create and then link to a library, say using code in a
subdirectory, use something like
</p>
<div class="example">
<pre class="example-preformatted">.PHONY: all mylibs

all: $(SHLIB)
$(SHLIB): mylibs

mylibs:
        (cd subdir; $(MAKE))
</pre></div>

<p>Be careful to create all the necessary dependencies, as there is no
guarantee that the dependencies of <code class="code">all</code> will be run in a
particular order (and some of the <abbr class="acronym">CRAN</abbr> build machines use
multiple CPUs and parallel makes).  In particular,
</p>
<div class="example">
<pre class="example-preformatted">all: mylibs
</pre></div>

<p>does <strong class="strong">not</strong> suffice.  GNU make does allow the construct
</p><div class="example">
<pre class="example-preformatted">.NOTPARALLEL: all
all: mylibs $(SHLIB)
</pre></div>

<p>but that is not portable.  <code class="command">dmake</code> and <code class="command">pmake</code> allow the
similar <code class="code">.NO_PARALLEL</code>, also not portable: some variants of
<code class="command">pmake</code> accept <code class="code">.NOTPARALLEL</code> as an alias for
<code class="code">.NO_PARALLEL</code>.
</p>
<p>Note that on Windows it is required that <samp class="file">Makevars[.win, .ucrt]</samp> does
create a DLL: this is needed as it is the only reliable way to ensure
that building a DLL succeeded.  If you want to use the <samp class="file">src</samp>
directory for some purpose other than building a DLL, use a
<samp class="file">Makefile.win</samp> or <samp class="file">Makefile.ucrt</samp> file.
</p>
<p>It is sometimes useful to have a target &lsquo;<samp class="samp">clean</samp>&rsquo; in <samp class="file">Makevars</samp>,
<samp class="file">Makevars.win</samp> or <samp class="file">Makevars.ucrt</samp>:
this will be used by <code class="command">R CMD build</code> to
clean up (a copy of) the package sources.  When it is run by
<code class="command">build</code> it will have fewer macros set, in particular not
<code class="code">$(SHLIB)</code>, nor <code class="code">$(OBJECTS)</code> unless set in the file itself.
It would also be possible to add tasks to the target &lsquo;<samp class="samp">shlib-clean</samp>&rsquo;
which is run by <code class="command">R CMD INSTALL</code> and <code class="command">R CMD SHLIB</code> with
options <samp class="option">--clean</samp> and <samp class="option">--preclean</samp>.
</p>
<p>Avoid the use of default (also known as &lsquo;implicit&rsquo; rules) in makefiles,
as these are <code class="command">make</code>-specific.  Even when mandated by POSIX &ndash;
GNU <code class="command">make</code> does not comply and this has broken package
installation.
</p>
<p>An unfortunately common error is to have
</p>
<div class="example">
<pre class="example-preformatted">all: $(SHLIB) clean
</pre></div>

<p>which asks <code class="command">make</code> to clean in parallel with compiling the code.
Not only does this lead to hard-to-debug installation errors, it wipes
out all the evidence of any error (from a parallel make or not).  It is
much better to leave cleaning to the end user using the facilities in
the previous paragraph.
</p>
<p>If you want to run R code in <samp class="file">Makevars</samp>, e.g. to find
configuration information, please do ensure that you use the correct
copy of <code class="code">R</code> or <code class="code">Rscript</code>: there might not be one in the path
at all, or it might be the wrong version or architecture.  The correct
way to do this is <em class="emph">via</em>
</p>
<div class="example">
<pre class="example-preformatted">&quot;$(R_HOME)/bin$(R_ARCH_BIN)/Rscript&quot; <var class="var">filename</var>
&quot;$(R_HOME)/bin$(R_ARCH_BIN)/Rscript&quot; -e ‘<var class="var">R expression</var>’
</pre></div>

<p>where <code class="code">$(R_ARCH_BIN)</code> is only needed currently on Windows.
</p>
<p>Environment or make variables can be used to select different macros for
Intel 64-bit code or code for other architectures, for example
(GNU <code class="command">make</code> syntax, allowed on Windows)
</p>
<div class="example">
<pre class="example-preformatted">ifeq &quot;$(WIN)&quot; &quot;64&quot;
PKG_LIBS = <var class="var">value for 64-bit Intel Windows</var>
else
PKG_LIBS = <var class="var">value for unknown Windows architectures</var>
endif
</pre></div>

<p>On Windows there is normally a choice between linking to an import
library or directly to a DLL.  Where possible, the latter is much more
reliable: import libraries are tied to a specific toolchain, and in
particular on 64-bit Windows two different conventions have been
commonly used.  So for example instead of
</p>
<div class="example">
<pre class="example-preformatted">PKG_LIBS = -L$(XML_DIR)/lib -lxml2
</pre></div>

<p>one can use
</p>
<div class="example">
<pre class="example-preformatted">PKG_LIBS = -L$(XML_DIR)/bin -lxml2
</pre></div>

<p>since on Windows <code class="code">-lxxx</code> will look in turn for
</p>
<div class="example">
<pre class="example-preformatted">libxxx.dll.a
xxx.dll.a
libxxx.a
xxx.lib
libxxx.dll
xxx.dll
</pre></div>

<p>where the first and second are conventionally import libraries, the
third and fourth often static libraries (with <code class="code">.lib</code> intended for
Visual C++), but might be import libraries.  See for example
<a class="uref" href="https://sourceware.org/binutils/docs-2.20/ld/WIN32.html#WIN32">https://sourceware.org/binutils/docs-2.20/ld/WIN32.html#WIN32</a>.
</p>
<p>The fly in the ointment is that the DLL might not be named
<samp class="file">libxxx.dll</samp>, and in fact on 32-bit Windows there was a
<samp class="file">libxml2.dll</samp> whereas on one build for 64-bit Windows the DLL is
called <samp class="file">libxml2-2.dll</samp>.  Using import libraries can cover over
these differences but can cause equal difficulties.
</p>
<p>If static libraries are available they can save a lot of problems with
run-time finding of DLLs, especially when binary packages are to be
distributed and even more when these support both architectures.  Where
using DLLs is unavoidable we normally arrange (<em class="emph">via</em>
<samp class="file">configure.win</samp> or <samp class="file">configure.ucrt</samp>) to ship them in the same directory as the package
DLL.
</p>
<ul class="mini-toc">
<li><a href="#OpenMP-support" accesskey="1"><abbr class="abbr">OpenMP</abbr> support</a></li>
<li><a href="#Using-pthreads" accesskey="2">Using pthreads</a></li>
<li><a href="#Compiling-in-sub_002ddirectories" accesskey="3">Compiling in sub-directories</a></li>
</ul>
<hr>
<div class="subsubsection-level-extent" id="OpenMP-support">
<div class="nav-panel">
<p>
Next: <a href="#Using-pthreads" accesskey="n" rel="next">Using pthreads</a>, Previous: <a href="#Using-Makevars" accesskey="p" rel="prev">Using <samp class="file">Makevars</samp></a>, Up: <a href="#Using-Makevars" accesskey="u" rel="up">Using <samp class="file">Makevars</samp></a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsubsection" id="OpenMP-support-1"><span>1.2.1.1 <abbr class="abbr">OpenMP</abbr> support<a class="copiable-link" href="#OpenMP-support-1"> &para;</a></span></h4>

<a class="index-entry-id" id="index-OpenMP"></a>

<p>There is some support for packages which wish to use
<abbr class="abbr">OpenMP</abbr><a class="footnote" id="DOCF38" href="#FOOT38"><sup>38</sup></a>.  The
<code class="command">make</code> macros
</p>
<div class="example">
<pre class="example-preformatted">SHLIB_OPENMP_CFLAGS
SHLIB_OPENMP_CXXFLAGS
SHLIB_OPENMP_FFLAGS
</pre></div>

<p>are available for use in <samp class="file">src/Makevars</samp>, <samp class="file">src/Makevars.win</samp> or
<samp class="file">Makevars.ucrt</samp>.  Include the appropriate macro in
<code class="code">PKG_CFLAGS</code>, <code class="code">PKG_CXXFLAGS</code> and so on, and also in
<code class="code">PKG_LIBS</code> (but see below for Fortran).  C/C++ code that needs to
be conditioned on the use of <abbr class="abbr">OpenMP</abbr> can be used inside <code class="code">#ifdef
_OPENMP</code>: note that some toolchains used for R (including Apple&rsquo;s for
macOS<a class="footnote" id="DOCF39" href="#FOOT39"><sup>39</sup></a> and some others using
<code class="command">clang</code><a class="footnote" id="DOCF40" href="#FOOT40"><sup>40</sup></a>) have no <abbr class="abbr">OpenMP</abbr> support at all, not even
<samp class="file">omp.h</samp>.
</p>
<p>For example, a package with C code written for <abbr class="abbr">OpenMP</abbr> should have in
<samp class="file">src/Makevars</samp> the lines
</p>
<div class="example">
<pre class="example-preformatted">PKG_CFLAGS = $(SHLIB_OPENMP_CFLAGS)
PKG_LIBS = $(SHLIB_OPENMP_CFLAGS)
</pre></div>

<p>Note that the macro <code class="code">SHLIB_OPENMP_CXXFLAGS</code> applies to the default
C++ compiler and not necessarily to the C++17/20/23 compiler: users of the
latter should do their own <code class="command">configure</code> checks.  If you do use
your own checks, make sure that <abbr class="abbr">OpenMP</abbr> support is complete by compiling
and linking an <abbr class="abbr">OpenMP</abbr>-using program: on some platforms the runtime
library is optional and on others that library depends on other optional
libraries.
</p>
<p>Some care is needed when compilers are from different families which may
use different <abbr class="abbr">OpenMP</abbr> runtimes (e.g. <code class="command">clang</code> <em class="emph">vs</em> GCC
including <code class="command">gfortran</code>, although it is often possible to use the
<code class="command">clang</code> runtime with GCC but not <em class="emph">vice versa</em>: however
<code class="command">gfortran</code> &gt;= 9 may generate calls not in the <code class="command">clang</code>
runtime).  For a package with Fortran code using <abbr class="abbr">OpenMP</abbr> the appropriate
lines are
</p>
<div class="example">
<pre class="example-preformatted">PKG_FFLAGS = $(SHLIB_OPENMP_FFLAGS)
PKG_LIBS = $(SHLIB_OPENMP_CFLAGS)
</pre></div>

<p>as the C compiler will be used to link the package code. There are
platforms on which this does not work <em class="emph">for some <abbr class="abbr">OpenMP</abbr>-using code</em>
and installation will fail.  Since R &gt;= 3.6.2 the best alternative
for a package with only Fortran sources using <abbr class="abbr">OpenMP</abbr> is to use
</p><div class="example">
<pre class="example-preformatted">USE_FC_TO_LINK =
PKG_FFLAGS = $(SHLIB_OPENMP_FFLAGS)
PKG_LIBS = $(SHLIB_OPENMP_FFLAGS)
</pre></div>
<p>in <samp class="file">src/Makevars</samp>, <samp class="file">src/Makevars.win</samp> or <samp class="file">Makevars.ucrt</samp>.
Note however, that
when this is used <code class="code">$(FLIBS)</code> should not be included in
<code class="code">PKG_LIBS</code> since it is for linking Fortran-compiled code by the C
compiler.
</p>
<p>Common platforms may inline all <abbr class="abbr">OpenMP</abbr> calls and so tolerate the
omission of the <abbr class="abbr">OpenMP</abbr> flag from <code class="code">PKG_LIBS</code>, but this usually
results in an installation failure with a different compiler or
compilation flags.  So cross-check that e.g. <code class="code">-fopenmp</code> appears
in the linking line in the installation logs.
</p>
<p>It is not portable to use <abbr class="abbr">OpenMP</abbr> with more than one of C, C++ and
Fortran in a single package since it is not uncommon that the compilers
are of different families.
</p>
<p>For portability, any C/C++ code using the <code class="code">omp_*</code> functions should
include the <samp class="file">omp.h</samp> header: some compilers (but not all) include it
when <abbr class="abbr">OpenMP</abbr> mode is switched on (e.g. <em class="emph">via</em> flag
<samp class="option">-fopenmp</samp>).
</p>
<p>There is nothing<a class="footnote" id="DOCF41" href="#FOOT41"><sup>41</sup></a> to say what
version of <abbr class="abbr">OpenMP</abbr> is supported: version 4.0 (and much of 4.5 or 5.0) is
supported by recent versions of the Linux and Windows platforms, but
portable packages cannot assume that end users have recent versions.
Apple <code class="command">clang</code> on macOS has no <abbr class="abbr">OpenMP</abbr> support.
<a class="uref" href="https://www.openmp.org/resources/openmp-compilers-tools/">https://www.openmp.org/resources/openmp-compilers-tools/</a> gives
some idea of what compilers support what versions.  Note that support
for Fortran compilers is often less up-to-date and that page suggests it
is unwise to rely on a version later than 3.1.  Which introduced a
Fortran <abbr class="abbr">OpenMP</abbr> module, so Fortran users of <abbr class="abbr">OpenMP</abbr> should include
</p><div class="example">
<pre class="example-preformatted">use omp_lib
</pre></div>

<p>Rarely, using <abbr class="abbr">OpenMP</abbr> with <code class="command">clang</code> on Linux generates calls in
<code class="code">libatomic</code>, resulting in loading messages like
</p><div class="example">
<pre class="example-preformatted">  undefined symbol: __atomic_compare_exchange
  undefined symbol: __atomic_load
</pre></div>
<p>The workaround is to link with <code class="code">-latomic</code> (having checked it exists).
</p>
<p>The performance of <abbr class="abbr">OpenMP</abbr> varies substantially between platforms.  The
Windows implementation has substantial overheads, so is only beneficial
if quite substantial tasks are run in parallel.  Also, on Windows new
threads are started with the default<a class="footnote" id="DOCF42" href="#FOOT42"><sup>42</sup></a> <abbr class="abbr">FPU</abbr> control word, so computations done on <abbr class="abbr">OpenMP</abbr>
threads will not make use of extended-precision arithmetic which is the
default for the main process.
</p>
<p>Do not include these macros unless your code does make use of <abbr class="abbr">OpenMP</abbr>
(possibly for C++ via included external headers): this can result in the
<abbr class="abbr">OpenMP</abbr> runtime being linked in, threads being started, &hellip;.
</p>
<p>Calling any of the R API from threaded code is &lsquo;for experts only&rsquo; and
strongly discouraged.  Many functions in the R API modify internal
R data structures and might corrupt these data structures if called
simultaneously from multiple threads.  Most R API functions can
signal errors, which must only happen on the R main thread.  Also,
external libraries (e.g. LAPACK) may not be thread-safe.
</p>
<p>Packages are not standard-alone programs, and an R process could
contain more than one <abbr class="abbr">OpenMP</abbr>-enabled package as well as other components
(for example, an optimized BLAS) making use of <abbr class="abbr">OpenMP</abbr>.  So careful
consideration needs to be given to resource usage.  <abbr class="abbr">OpenMP</abbr> works with
parallel regions, and for most implementations the default is to use as
many threads as &lsquo;CPUs&rsquo; for such regions.  Parallel regions can be
nested, although it is common to use only a single thread below the
first level.  The correctness of the detected number of &lsquo;CPUs&rsquo; and the
assumption that the R process is entitled to use them all are both
dubious assumptions.  One way to limit resources is to limit the overall
number of threads available to <abbr class="abbr">OpenMP</abbr> in the R process: this can be
done <em class="emph">via</em> environment variable <code class="env">OMP_THREAD_LIMIT</code>, where
implemented.<a class="footnote" id="DOCF43" href="#FOOT43"><sup>43</sup></a>  Alternatively, the number of threads per
region can be limited by the environment variable <code class="env">OMP_NUM_THREADS</code>
or API call <code class="code">omp_set_num_threads</code>, or, better, for the regions in
your code as part of their specification. E.g. R uses<a class="footnote" id="DOCF44" href="#FOOT44"><sup>44</sup></a>
</p><div class="example">
<pre class="example-preformatted">#pragma omp parallel for num_threads(nthreads) ...
</pre></div>
<p>That way you only control your own code and not that of other <abbr class="abbr">OpenMP</abbr> users.
</p>
<p>Note that setting environment variables to control <abbr class="abbr">OpenMP</abbr> is
implementation-dependent and may need to be done outside the R
process or before any use of <abbr class="abbr">OpenMP</abbr> (which might be by another process
or R itself).   Also, implementation-specific variables such as
<code class="env">KMP_THREAD_LIMIT</code> might take precedence.
</p>
<hr>
</div>
<div class="subsubsection-level-extent" id="Using-pthreads">
<div class="nav-panel">
<p>
Next: <a href="#Compiling-in-sub_002ddirectories" accesskey="n" rel="next">Compiling in sub-directories</a>, Previous: <a href="#OpenMP-support" accesskey="p" rel="prev"><abbr class="abbr">OpenMP</abbr> support</a>, Up: <a href="#Using-Makevars" accesskey="u" rel="up">Using <samp class="file">Makevars</samp></a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsubsection" id="Using-pthreads-1"><span>1.2.1.2 Using pthreads<a class="copiable-link" href="#Using-pthreads-1"> &para;</a></span></h4>

<p>There is no direct support for the POSIX threads (more commonly known as
<code class="code">pthreads</code>): by the time we considered adding it several packages
were using it unconditionally so it seems that nowadays it is
universally available on POSIX operating systems.
</p>
<p>For reasonably recent versions of <code class="command">gcc</code> and <code class="command">clang</code> the
correct specification is
</p>
<div class="example">
<pre class="example-preformatted">PKG_CPPFLAGS = -pthread
PKG_LIBS = -pthread
</pre></div>

<p>(and the plural version is also accepted on some systems/versions).  For
other platforms the specification is
</p>
<div class="example">
<pre class="example-preformatted">PKG_CPPFLAGS = -D_REENTRANT
PKG_LIBS = -lpthread
</pre></div>
<p>(and note that the library name is singular).  This is what
<samp class="option">-pthread</samp> does on all known current platforms (although earlier
versions of OpenBSD used a different library name).
</p>
<p>For a tutorial see
<a class="uref" href="https://hpc-tutorials.llnl.gov/posix/">https://hpc-tutorials.llnl.gov/posix/</a>.
</p>
<p>POSIX threads are not normally used on Windows which has its own native
concepts of threads: however, recent toolchains do provide the
<code class="code">pthreads</code> header and library.
</p>
<p>The presence of a working <code class="code">pthreads</code> implementation cannot be
unambiguously determined without testing for yourself: however, that
&lsquo;<samp class="samp">_REENTRANT</samp>&rsquo; is defined in C/C++ code is a good indication.
</p>
<p>Note that not all <code class="code">pthreads</code> implementations are equivalent as parts
are optional (see
<a class="uref" href="https://pubs.opengroup.org/onlinepubs/009695399/basedefs/pthread.h.html">https://pubs.opengroup.org/onlinepubs/009695399/basedefs/pthread.h.html</a>):
for example, macOS lacks the &lsquo;Barriers&rsquo; option.
</p>
<p>See also the comments on thread-safety and performance under <abbr class="abbr">OpenMP</abbr>: on
all known R platforms <abbr class="abbr">OpenMP</abbr> is implemented <em class="emph">via</em>
<code class="code">pthreads</code> and the known performance issues are in the latter.
</p>
<hr>
</div>
<div class="subsubsection-level-extent" id="Compiling-in-sub_002ddirectories">
<div class="nav-panel">
<p>
Previous: <a href="#Using-pthreads" accesskey="p" rel="prev">Using pthreads</a>, Up: <a href="#Using-Makevars" accesskey="u" rel="up">Using <samp class="file">Makevars</samp></a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsubsection" id="Compiling-in-sub_002ddirectories-1"><span>1.2.1.3 Compiling in sub-directories<a class="copiable-link" href="#Compiling-in-sub_002ddirectories-1"> &para;</a></span></h4>

<p>Package authors fairly often want to organize code in sub-directories of
<samp class="file">src</samp>, for example if they are including a separate piece of
external software to which this is an R interface.
</p>
<p>One simple way is simply to set <code class="code">OBJECTS</code> to be all the objects
that need to be compiled, including in sub-directories.  For example,
<abbr class="acronym">CRAN</abbr> package <a class="url" href="https://CRAN.R-project.org/package=RSiena"><strong class="strong">RSiena</strong></a> has
</p>
<div class="example smallexample">
<pre class="example-preformatted">SOURCES = $(wildcard data/*.cpp network/*.cpp utils/*.cpp model/*.cpp model/*/*.cpp model/*/*/*.cpp)

OBJECTS = siena07utilities.o siena07internals.o siena07setup.o siena07models.o $(SOURCES:.cpp=.o)
</pre></div>

<p>One problem with that approach is that unless GNU make extensions are
used, the source files need to be listed and kept up-to-date.  As in the
following from <abbr class="acronym">CRAN</abbr> package <a class="url" href="https://CRAN.R-project.org/package=lossDev"><strong class="strong">lossDev</strong></a>:
</p>
<div class="example smallexample">
<pre class="example-preformatted">OBJECTS.samplers = samplers/ExpandableArray.o samplers/Knots.o \
  samplers/RJumpSpline.o samplers/RJumpSplineFactory.o \
  samplers/RealSlicerOV.o samplers/SliceFactoryOV.o samplers/MNorm.o
OBJECTS.distributions = distributions/DSpline.o \
  distributions/DChisqrOV.o distributions/DTOV.o \
  distributions/DNormOV.o distributions/DUnifOV.o distributions/RScalarDist.o
OBJECTS.root = RJump.o

OBJECTS = $(OBJECTS.samplers) $(OBJECTS.distributions) $(OBJECTS.root)
</pre></div>

<p>Where the subdirectory is self-contained code with a suitable makefile,
the best approach is something like
</p>
<div class="example smallexample">
<pre class="example-preformatted">PKG_LIBS = -LCsdp/lib -lsdp $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS)

$(SHLIB): Csdp/lib/libsdp.a

Csdp/lib/libsdp.a:      
        @(cd Csdp/lib &amp;&amp; $(MAKE) libsdp.a \
          CC=&quot;$(CC)&quot; CFLAGS=&quot;$(CFLAGS) $(CPICFLAGS)&quot; AR=&quot;$(AR)&quot; RANLIB=&quot;$(RANLIB)&quot;)
</pre></div>

<p>Note the quotes: the macros can contain spaces, e.g. <code class="code">CC = &quot;gcc
-m64 -std=gnu99&quot;</code>.  Several authors have forgotten about parallel makes:
the static library in the subdirectory must be made before the shared
object (<code class="code">$(SHLIB)</code>) and so the latter must depend on the former.
Others forget the need<a class="footnote" id="DOCF45" href="#FOOT45"><sup>45</sup></a> for
position-independent code.
</p>
<p>We really do not recommend using <samp class="file">src/Makefile</samp> instead of
<samp class="file">src/Makevars</samp>, and as the example above shows, it is not
necessary.
</p>
<hr>
</div>
</div>
<div class="subsection-level-extent" id="Configure-example">
<div class="nav-panel">
<p>
Next: <a href="#Using-modern-Fortran-code" accesskey="n" rel="next">Using modern Fortran code</a>, Previous: <a href="#Using-Makevars" accesskey="p" rel="prev">Using <samp class="file">Makevars</samp></a>, Up: <a href="#Configure-and-cleanup" accesskey="u" rel="up">Configure and cleanup</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Configure-example-1"><span>1.2.2 Configure example<a class="copiable-link" href="#Configure-example-1"> &para;</a></span></h4>

<p>It may be helpful to give an extended example of using a
<samp class="file">configure</samp> script to create a <samp class="file">src/Makevars</samp> file: this is
based on that in the <a class="url" href="https://CRAN.R-project.org/package=RODBC"><strong class="strong">RODBC</strong></a> package.
</p>
<p>The <samp class="file">configure.ac</samp> file follows: <samp class="file">configure</samp> is created from
this by running <code class="command">autoconf</code> in the top-level package directory
(containing <samp class="file">configure.ac</samp>).
</p>
<blockquote class="quotation">
<div class="example smallexample">
<pre class="example-preformatted">AC_INIT([RODBC], 1.1.8) dnl package name, version

dnl A user-specifiable option
odbc_mgr=&quot;&quot;
AC_ARG_WITH([odbc-manager],
            AC_HELP_STRING([--with-odbc-manager=MGR],
                           [specify the ODBC manager, e.g. odbc or iodbc]),
            [odbc_mgr=$withval])

if test &quot;$odbc_mgr&quot; = &quot;odbc&quot; ; then
  AC_PATH_PROGS(ODBC_CONFIG, odbc_config)
fi

dnl Select an optional include path, from a configure option
dnl or from an environment variable.
AC_ARG_WITH([odbc-include],
            AC_HELP_STRING([--with-odbc-include=INCLUDE_PATH],
                           [the location of ODBC header files]),
            [odbc_include_path=$withval])
RODBC_CPPFLAGS=&quot;-I.&quot;
if test [ -n &quot;$odbc_include_path&quot; ] ; then
   RODBC_CPPFLAGS=&quot;-I. -I${odbc_include_path}&quot;
else
  if test [ -n &quot;${ODBC_INCLUDE}&quot; ] ; then
     RODBC_CPPFLAGS=&quot;-I. -I${ODBC_INCLUDE}&quot;
  fi
fi

dnl ditto for a library path
AC_ARG_WITH([odbc-lib],
            AC_HELP_STRING([--with-odbc-lib=LIB_PATH],
                           [the location of ODBC libraries]),
            [odbc_lib_path=$withval])
if test [ -n &quot;$odbc_lib_path&quot; ] ; then
   LIBS=&quot;-L$odbc_lib_path ${LIBS}&quot;
else
  if test [ -n &quot;${ODBC_LIBS}&quot; ] ; then
     LIBS=&quot;-L${ODBC_LIBS} ${LIBS}&quot;
  else
    if test -n &quot;${ODBC_CONFIG}&quot;; then
      odbc_lib_path=`odbc_config --libs | sed s/-lodbc//`
      LIBS=&quot;${odbc_lib_path} ${LIBS}&quot;
    fi
  fi
fi

dnl Now find the compiler and compiler flags to use
: ${R_HOME=`R RHOME`}
if test -z &quot;${R_HOME}&quot;; then
  echo &quot;could not determine R_HOME&quot;
  exit 1
fi
CC=`&quot;${R_HOME}/bin/R&quot; CMD config CC`
CFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CFLAGS`
CPPFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CPPFLAGS`

if test -n &quot;${ODBC_CONFIG}&quot;; then
  RODBC_CPPFLAGS=`odbc_config --cflags`
fi
CPPFLAGS=&quot;${CPPFLAGS} ${RODBC_CPPFLAGS}&quot;

dnl Check the headers can be found
AC_CHECK_HEADERS(sql.h sqlext.h)
if test &quot;${ac_cv_header_sql_h}&quot; = no ||
   test &quot;${ac_cv_header_sqlext_h}&quot; = no; then
   AC_MSG_ERROR(&quot;ODBC headers sql.h and sqlext.h not found&quot;)
fi

dnl search for a library containing an ODBC function
if test [ -n &quot;${odbc_mgr}&quot; ] ; then
  AC_SEARCH_LIBS(SQLTables, ${odbc_mgr}, ,
      AC_MSG_ERROR(&quot;ODBC driver manager ${odbc_mgr} not found&quot;))
else
  AC_SEARCH_LIBS(SQLTables, odbc odbc32 iodbc, ,
      AC_MSG_ERROR(&quot;no ODBC driver manager found&quot;))
fi

dnl for 64-bit ODBC need SQL[U]LEN, and it is unclear where they are defined.
AC_CHECK_TYPES([SQLLEN, SQLULEN], , , [# include &lt;sql.h&gt;])
dnl for unixODBC header
AC_CHECK_SIZEOF(long, 4)

dnl substitute RODBC_CPPFLAGS and LIBS
AC_SUBST(RODBC_CPPFLAGS)
AC_SUBST(LIBS)
AC_CONFIG_HEADERS([src/config.h])
dnl and do substitution in the src/Makevars.in and src/config.h
AC_CONFIG_FILES([src/Makevars])
AC_OUTPUT
</pre></div>
</blockquote>

<p>where <samp class="file">src/Makevars.in</samp> would be simply
</p>
<blockquote class="quotation">
<div class="example">
<pre class="example-preformatted">PKG_CPPFLAGS = @RODBC_CPPFLAGS@
PKG_LIBS = @LIBS@
</pre></div>
</blockquote>

<p>A user can then be advised to specify the location of the <abbr class="abbr">ODBC</abbr>
driver manager files by options like (lines broken for easier reading)
</p>
<div class="example">
<pre class="example-preformatted">R CMD INSTALL \
  --configure-args='--with-odbc-include=/opt/local/include \
  --with-odbc-lib=/opt/local/lib --with-odbc-manager=iodbc' \
  RODBC
</pre></div>

<p>or by setting the environment variables <code class="code">ODBC_INCLUDE</code> and
<code class="code">ODBC_LIBS</code>.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Using-modern-Fortran-code">
<div class="nav-panel">
<p>
Next: <a href="#Using-C_002b_002b-code" accesskey="n" rel="next">Using C++ code</a>, Previous: <a href="#Configure-example" accesskey="p" rel="prev">Configure example</a>, Up: <a href="#Configure-and-cleanup" accesskey="u" rel="up">Configure and cleanup</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-modern-Fortran-code-1"><span>1.2.3 Using modern Fortran code<a class="copiable-link" href="#Using-modern-Fortran-code-1"> &para;</a></span></h4>

<p>R assumes that source files with extension <samp class="file">.f</samp> are fixed-form
Fortran 90 (which includes Fortran 77), and passes them to the compiler
specified by macro &lsquo;<samp class="samp">FC</samp>&rsquo;.  The Fortran compiler will also accept
free-form Fortran 90/95 code with extension <samp class="file">.f90</samp> or
(most<a class="footnote" id="DOCF46" href="#FOOT46"><sup>46</sup></a>)  <samp class="file">.f95</samp>.
</p>
<a class="index-entry-id" id="index-PKG_005fFCFLAGS"></a>
<p>The same compiler is used for both fixed-form and free-form Fortran code
(with different file extensions and possibly different flags).  Macro
<code class="code">PKG_FFLAGS</code> can be used for package-specific flags: for the
un-encountered case that both are included in a single package and that
different flags are needed for the two forms, macro <code class="code">PKG_FCFLAGS</code>
is also available for free-form Fortran.
</p>
<p>The code used to build R allows a &lsquo;Fortran 90&rsquo; compiler to be
selected as &lsquo;<samp class="samp">FC</samp>&rsquo;, so platforms might be encountered which only
support Fortran 90.  However, Fortran 95 is supported on all known
platforms.
</p>
<p>Most compilers specified by &lsquo;<samp class="samp">FC</samp>&rsquo; will accept Fortran 2003, 2008 or
2018 code: such code should still use file extension <samp class="file">.f90</samp>.  Most
current platforms use <code class="command">gfortran</code> where you might need to include
<samp class="option">-std=f2003</samp>, <samp class="option">-std=f2008</samp> or (from version 8)
<samp class="option">-std=f2018</samp> in <code class="code">PKG_FFLAGS</code> or <code class="code">PKG_FCFLAGS</code>: the
default is &lsquo;GNU Fortran&rsquo;, currently Fortran 2018 (but Fortran 95 prior
to <code class="command">gfortran</code>&nbsp;8) with non-standard extensions.  The other
compilers in current use (LLVM&rsquo;s <code class="command">flang-new</code> and Intel&rsquo;s
<code class="command">ifx</code>) default to Fortran 2018.
</p>
<p>It is good practice to describe a Fortran version requirement in
<samp class="file">DESCRIPTION</samp>&rsquo;s &lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field.
</p>

<p>Modern versions of Fortran support modules, whereby compiling one source
file creates a module file which is then included in others.  (Module
files typically have a <samp class="file">.mod</samp> extension: they do depend on the
compiler used and so should never be included in a package.)  This
creates a dependence which <code class="command">make</code> will not know about and often
causes installation with a parallel make to fail.  Thus it is necessary
to add explicit dependencies to <samp class="file">src/Makevars</samp> to tell
<code class="command">make</code> the constraints on the order of compilation.  For
example, if file <samp class="file">iface.f90</samp> creates a module &lsquo;<samp class="samp">iface</samp>&rsquo; used by
files <samp class="file">cmi.f90</samp> and <samp class="file">dmi.f90</samp> then <samp class="file">src/Makevars</samp> needs
to contain something like
</p>
<div class="example">
<pre class="example-preformatted">cmi.o dmi.o: iface.o
</pre></div>

<p>Note that it is not portable (although some platforms do accept it) to
define a module of the same name in multiple source files.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Using-C_002b_002b-code">
<div class="nav-panel">
<p>
Next: <a href="#C-standards" accesskey="n" rel="next">C standards</a>, Previous: <a href="#Using-modern-Fortran-code" accesskey="p" rel="prev">Using modern Fortran code</a>, Up: <a href="#Configure-and-cleanup" accesskey="u" rel="up">Configure and cleanup</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-C_002b_002b-code-1"><span>1.2.4 Using C++ code<a class="copiable-link" href="#Using-C_002b_002b-code-1"> &para;</a></span></h4>

<p>R can be built without a C++ compiler although one is available (but
not necessarily installed) on all known R platforms.  As from R
4.0.0 a C++ compiler will be selected only if it conforms to the 2011
standard (&lsquo;C++11&rsquo;).  A minor update<a class="footnote" id="DOCF47" href="#FOOT47"><sup>47</sup></a> (&lsquo;C++14&rsquo;) was published in
December 2014 and was used by default as from R 4.1.0 if
supported.  Further revisions &lsquo;C++17&rsquo; (in December 2017) and &lsquo;C++20&rsquo;
(with many new features in December 2020) have been published since.
The next revision, &lsquo;C++23&rsquo;, is expected in 2024 and several compilers
already have extensive partial support for the final draft.
</p>
<p>The default standard for compiling R packages was changed to C++17 in
R 4.3.0 if supported, and from R 4.4.0 only a C++17 compiler will
be selected as the default C++ compiler.
</p>
<p>What standard a C++ compiler aims to support can be hard to determine:
the value<a class="footnote" id="DOCF48" href="#FOOT48"><sup>48</sup></a>  of <code class="code">__cplusplus</code> may help but
some compilers use it to denote a standard which is partially supported
and some the latest standard which is (almost) fully supported.  On a
Unix-alike <code class="command">configure</code> will try to identify a compiler and flags
for each of the standards: this relies heavily on the reported values of
<code class="code">__cplusplus</code>.
</p>

<p>The webpage
<a class="uref" href="https://en.cppreference.com/w/cpp/compiler_support">https://en.cppreference.com/w/cpp/compiler_support</a> gives
some information on which compilers are known to support recent C++
features.
</p>
<p>C++ standards have deprecated and later removed features.  Be aware that
some current compilers still accept removed features in C++17 mode,
such as <code class="code">std::unary_function</code> (deprecated in C++11, removed in C++17).
</p>
<p>Different versions of R have used different default C++ standards, so
for maximal portability a package should specify the standard it
requires.  In order to specify C++14 code in a package with a
<samp class="file">Makevars</samp> file (or <samp class="file">Makevars.win</samp> or <samp class="file">Makevars.ucrt</samp> on
Windows) should include the line
</p>
<div class="example">
<pre class="example-preformatted">CXX_STD = CXX14
</pre></div>
<p>Compilation and linking will then be done with the C++14 compiler (if
any).  Analogously for other standards (details below).  On the other
hand, specifying C++11<a class="footnote" id="DOCF49" href="#FOOT49"><sup>49</sup></a>
when the code is valid under C++14 or C++17 reduces future portability.
</p>
<p>Packages without a <samp class="file">src/Makevars</samp> or <samp class="file">src/Makefile</samp> file may
specify a C++ standard for code in the <samp class="file">src</samp> directory by including
something like &lsquo;<samp class="samp">C++14</samp>&rsquo; in the &lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field of
the <samp class="file">DESCRIPTION</samp> file, e.g.
</p>
<div class="example">
<pre class="example-preformatted">SystemRequirements: C++14
</pre></div>

<p>If a package does have a <samp class="file">src/Makevars[.win]</samp> file then also
setting the make variable &lsquo;<samp class="samp">CXX_STD</samp>&rsquo; there is recommended, as it
allows <code class="command">R CMD SHLIB</code> to work correctly in the package&rsquo;s
<samp class="file">src</samp> directory.
</p>
<p>A requirement of C++17 or later should always be declared in the
&lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field (as well as in <samp class="file">src/Makevars</samp> or
<samp class="file">src/Makefile</samp>) so this is shown on the package&rsquo;s summary pages on
<abbr class="acronym">CRAN</abbr> or similar.  This is also good practice for a requirement
of C++14.  Note that support of C++14 or C++17 is only available from
R 3.4.0, so if the package has an R version requirement it needs to
take that into account.
</p>
<p>Essentially complete C++14 support is available from GCC 5, LLVM
<code class="command">clang</code> 3.4 and currently-used versions of Apple
<code class="command">clang</code>.
</p>
<p>Code needing C++14 features can check for their presence <em class="emph">via</em>
&lsquo;SD-6 feature tests&rsquo;<a class="footnote" id="DOCF50" href="#FOOT50"><sup>50</sup></a>.  Such a check could be
</p>
<div class="example">
<pre class="example-preformatted">#include &lt;memory&gt; // header where this is defined
#if defined(__cpp_lib_make_unique) &amp;&amp; (__cpp_lib_make_unique &gt;= 201304)
using std::make_unique;
#else
// your emulation
#endif
</pre></div>

<p>C++17 (as from R 3.4.0), C++20 (as from R 4.0.0) and C++23 (as
from R 4.3.0) can be specified in an analogous way (replacing
<code class="code">14</code> by <code class="code">17</code>, <code class="code">20</code> or <code class="code">23</code>) but compiler/OS support
is platform-dependent.  Some C++17 and C++20 support is available with
the default builds of R on macOS and Windows as from R 4.0.0.
Much of <code class="command">g++</code>&rsquo;s support for C++17 needs version 7 or later: that
is more recent than some still-current Linux distributions but often
packages for later compilers are available: for RHEL/Centos 7 look for
&lsquo;devtoolset&rsquo;.
</p>
<p>Note that C++17 or later &lsquo;support&rsquo; does not mean complete support: use
feature tests as well as resources such as
<a class="uref" href="https://en.cppreference.com/w/cpp/compiler_support">https://en.cppreference.com/w/cpp/compiler_support</a>,
<a class="uref" href="https://gcc.gnu.org/projects/cxx-status.html">https://gcc.gnu.org/projects/cxx-status.html</a> and
<a class="uref" href="https://clang.llvm.org/cxx_status.html">https://clang.llvm.org/cxx_status.html</a> to see if the features you
want to use are widely implemented.  In particular, for C++23 R&rsquo;s
<code class="command">configure</code> script only checks for a compiler claiming to be
later than C++20.<a class="footnote" id="DOCF51" href="#FOOT51"><sup>51</sup></a>
</p>
<p>Attempts to specify an unknown C++ standard are silently ignored: recent
versions of R throw an error for C++98 and for known standards for
which no compiler+flags has been detected.
</p>
<p>If a package using C++ has a <code class="command">configure</code> script it is essential
that the script selects the correct C++ compiler and standard,
<em class="emph">via</em> something like
</p>
<div class="example">
<pre class="example-preformatted">CXX17=`&quot;${R_HOME}/bin/R&quot; CMD config CXX17`
if test -z &quot;$CXX17&quot;; then
  AC_MSG_ERROR([No C++17 compiler is available])
fi
CXX17STD=`&quot;${R_HOME}/bin/R&quot; CMD config CXX17STD`
CXX=&quot;${CXX17} ${CXX17STD}&quot;
CXXFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CXX17FLAGS`
## for an configure.ac file
AC_LANG(C++)
</pre></div>

<p>if C++17 was specified, but using
</p><div class="example">
<pre class="example-preformatted">CXX=`&quot;${R_HOME}/bin/R&quot; CMD config CXX`
CXXFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CXXFLAGS`
## for an configure.ac file
AC_LANG(C++)
</pre></div>
<p>if no standard was specified.
</p>
<p>If you want to compile C++ code in a subdirectory, make sure you pass
down the macros to specify the appropriate compiler, e.g. in
<samp class="file">src/Makevars</samp>
</p><div class="example">
<pre class="example-preformatted">sublibs:
         @(cd libs &amp;&amp; $(MAKE) \
            CXX=&quot;$(CXX17) $(CXX17STD)&quot; CXXFLAGS=&quot;$(CXX17FLAGS) $(CXX17PICFLAGS)&quot;)
</pre></div>

<p>The discussion above is about the standard R ways of compiling C++:
it will not apply to packages using <samp class="file">src/Makefile</samp> or building in a
subdirectory that do not set the C++ standard.  And compilers&rsquo; default
C++ standards varies widely and gets changed frequently by vendors &ndash;
for example Apple clang up to at least 15 defaults to C++98, LLVM
clang 14&ndash;15 to C++14, LLVM clang 16&ndash;18 to C++17 and <code class="command">g++</code>
11&ndash;13 to C++17.
</p>
<p>For a package with a <samp class="file">src/Makefile</samp> (or a Windows analogue),
a non-default C++ compiler can be selected by including something like
</p><div class="example">
<pre class="example-preformatted">CXX14 = `&quot;${R_HOME}/bin/R&quot; CMD config CXX14`
CXX14STD = `&quot;${R_HOME}/bin/R&quot; CMD config CXX14STD`
CXX = ${CXX14} ${CXX14STD}
CXXFLAGS = `&quot;${R_HOME}/bin/R&quot; CMD config CXX14FLAGS`
CXXPICFLAGS = `&quot;${R_HOME}/bin/R&quot; CMD config CXX14PICFLAGS`
SHLIB_LD = &quot;${R_HOME}/bin/R&quot; CMD config SHLIB_CXX14LD`
SHLIB_LDFLAGS = &quot;${R_HOME}/bin/R&quot; CMD config SHLIB_CXX14LDFLAGS`
</pre></div>
<p>and ensuring these values are used in relevant compilations, after
checking they are non-empty.  A common use of <samp class="file">src/Makefile</samp> is to
compile an executable, when likely something like (for example for
C++14)
</p><div class="example">
<pre class="example-preformatted">CXX14 = `&quot;${R_HOME}/bin/R&quot; CMD config CXX14`
CXX14STD = `&quot;${R_HOME}/bin/R&quot; CMD config CXX14STD`
CXX = ${CXX14} ${CXX14STD}
CXXFLAGS = `&quot;${R_HOME}/bin/R&quot; CMD config CXX14FLAGS`
</pre></div>
<p>suffices.  On Unix (and on Windows from R 4.3.0) this can be simplified
to
</p><div class="example">
<pre class="example-preformatted">CXX = ${CXX14} ${CXX14STD}
CXXFLAGS = ${CXX14FLAGS}
</pre></div>

<p>On a Unix-alike C++ compilation defaulted to C++11 from R 3.6.0, to
C++14 from R 4.1.0 and to C++17 from R 4.3.0. However, only &lsquo;if
available&rsquo;, so platforms using very old OSes might have used the
previous default.  Even older versions of R defaulted to the
compiler&rsquo;s default, almost certainly C++98 for compilers of comparable
vintage.
</p>
<p>On Windows the default was changed from C++98 to C++11 in R 3.6.2, to
C++14 in R 4.2.3 and to C++17 in R 4.3.0.
</p>
<p>The C++11 standard could be specified as from R 3.1.0 and C++14 or
C++17 as from R 3.4.0, for C++20 from R 4.0.0 and for C++23 from
R 4.3.0 (although they may not be supported by the compilers
in use).  C++11 support became mandatory in R 4.0.0 and C++17 support
in R 4.4.0.
</p>
<p>The <samp class="file">.so</samp>/<samp class="file">.dll</samp> in a package may need to be linked by the
C++ compiler if it or any library it links to contains compiled C++
code.  Dynamic linking usually brings in the C++ runtime library
(commonly <code class="code">libstdc++</code> but can be, for example, <code class="code">libc++</code>) but
static linking (as used for external libraries on Windows and macOS)
will not.  <code class="command">R CMD INSTALL</code> will link with the C++ compiler if
there are any top-level C++ files in <samp class="file">src</samp>, but not if these are
all in subdirectories.  The simplest way to force linking by the C++
compiler is to include an empty C++ file in <samp class="file">src</samp>..
</p>
<hr>
</div>
<div class="subsection-level-extent" id="C-standards">
<div class="nav-panel">
<p>
Next: <a href="#Using-cmake" accesskey="n" rel="next">Using <code class="command">cmake</code></a>, Previous: <a href="#Using-C_002b_002b-code" accesskey="p" rel="prev">Using C++ code</a>, Up: <a href="#Configure-and-cleanup" accesskey="u" rel="up">Configure and cleanup</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="C-standards-1"><span>1.2.5 C standards<a class="copiable-link" href="#C-standards-1"> &para;</a></span></h4>

<p>C has had standards C89/C90, C99, C11, C17 (also known as C18), and C23
is in final draft and expected to be published in early 2024.  C11 was a
minor change to C99 which introduced some new features and made others
optional, and C17 is a &lsquo;bug-fix&rsquo; update to C11.  On the other hand, C23
makes extensive changes, including making <code class="code">bool</code>, <code class="code">true</code> and
<code class="code">false</code> reserved words, finally disallowing K&amp;R-style function
declarations and clarifying the formerly deprecated meaning of function
declarations with an empty parameter list to mean zero
parameters. (There are many other additions: see for example
<a class="uref" href="https://en.cppreference.com/w/c/23">https://en.cppreference.com/w/c/23</a>.)
</p>
<p>The <code class="command">configure</code> script in recent versions of R aims to choose
a C compiler which supports C11: as the default in recent versions of
<code class="command">gcc</code>, LLVM <code class="command">clang</code> and Apple <code class="command">clang</code> is C17,
that is what is likely to be chosen.  On the other hand, until R 4.3.0
the makefiles for the Windows build specified C99.  They now use the
compiler default which for the recommended compiler is C17.
</p>
<p>Packages may want to either avoid or embrace the changes in C23, and can
do so <em class="emph">via</em> specifying &lsquo;<samp class="samp">USE_Cnn</samp>&rsquo; for 17, 23, 90 or 99 in the
&lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field of their <samp class="file">DESCRIPTION</samp> file of a
package depending on &lsquo;<samp class="samp">R (&gt;= 4.3.0)</samp>&rsquo;.  Those using a
<code class="command">configure</code> script should set the corresponding compiler and
flags, for example using
</p><div class="example">
<pre class="example-preformatted">CC=`&quot;${R_HOME}/bin/R&quot; CMD config CC23`
CFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config C23FLAGS`
CPPFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CPPFLAGS`
LDFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config LDFLAGS`
</pre></div>

<p>The (claimed) C standard in use can be checked by the macro
<code class="code">__STDC_VERSION__</code>. This is undefined in C89/C90 and should have
values <code class="code">199901L</code>, <code class="code">201112L</code> and <code class="code">201710L</code> for C99, C11
and C17.  As C23 is not yet published there is as yet no definitive
value: compilers are currently using <code class="code">202000L</code>.
C23 has macros similar to C++ &lsquo;feature tests&rsquo; for many of its changes,
for example <code class="code">__STDC_VERSION_LIMITS_H__</code>.
</p>
<p>However, note the &lsquo;claimed&rsquo; as no compiler had 100% conformance, and it
is better to use <code class="command">configure</code> to test for the feature you want to
use than to condition on the value of <code class="code">__STDC_VERSION__</code>.  In
particular, C11 alignment functionality such as <code class="code">_Alignas</code> and
<code class="code">aligned_alloc</code> is not implemented on Windows.
</p>
<p>End users can specify a standard by something like <code class="command">R CMD
INSTALL --use-C17</code>.  This overrides the &lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field,
but not for any <code class="command">configure</code> file.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Using-cmake">
<div class="nav-panel">
<p>
Previous: <a href="#C-standards" accesskey="p" rel="prev">C standards</a>, Up: <a href="#Configure-and-cleanup" accesskey="u" rel="up">Configure and cleanup</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-cmake-1"><span>1.2.6 Using <code class="command">cmake</code><a class="copiable-link" href="#Using-cmake-1"> &para;</a></span></h4>

<p>Packages often wish to include the sources of other software and compile
that for inclusion in their <samp class="file">.so</samp> or <samp class="file">.dll</samp>, which is normally
done by including (or unpacking) the sources in a subdirectory of
<samp class="file">src</samp>, as considered above.
</p>
<p>Further issues arise when the external software uses another build
system such as <code class="command">cmake</code>, principally to ensure that
<em class="emph">all</em> the settings for compilers, include and load paths <em class="emph">etc</em>
are made.  This section has already mentioned the need to set
at least some of
</p><div class="example">
<pre class="example-preformatted">CC CFLAGS CXX CXXFLAGS CPPFLAGS LDFLAGS
</pre></div>
<p><code class="code">CFLAGS</code> and <code class="code">CXXFLAGS</code> will need to include <code class="code">CPICFLAGS</code>
and <code class="code">CXXPICFLAGS</code> respectively unless (as below) <code class="command">cmake</code> is
asked to generate PIC code.
</p>
<p>Setting these (and more) as environment variables controls the behaviour
of <code class="command">cmake</code>
(<a class="uref" href="https://cmake.org/cmake/help/latest/manual/cmake-env-variables.7.html#manual:cmake-env-variables(7)">https://cmake.org/cmake/help/latest/manual/cmake-env-variables.7.html#manual:cmake-env-variables(7)</a>),
but it may be desirable to translate these into native settings such as
</p><div class="example">
<pre class="example-preformatted">CMAKE_C_COMPILER
CMAKE_C_FLAGS
CMAKE_CXX_COMPILER
CMAKE_CXX_FLAGS
CMAKE_INCLUDE_PATH
CMAKE_LIBRARY_PATH
CMAKE_SHARED_LINKER_FLAGS_INIT
CMAKE_OSX_DEPLOYMENT_TARGET
</pre></div>
<p>and it is often necessary to ensure a static library of PIC code is built by
</p><div class="example">
<pre class="example-preformatted">-DBUILD_SHARED_LIBS:bool=OFF
-DCMAKE_POSITION_INDEPENDENT_CODE:bool=ON
</pre></div>

<p>If R is to be detected or used, this must be the build being used for
package installation &ndash; <code class="command">&quot;${R_HOME}&quot;/bin/R</code>.
</p>
<p>To fix ideas, consider a package with sources for a library <samp class="file">myLib</samp>
under <samp class="file">src/libs</samp>.  Two approaches have been used.  It is often most
convenient to build the external software in a directory other than its
sources (particularly during development when the build directory can be
removed between builds rather than attempting to clean the sources) &ndash;
this is illustrated in the first approach.
</p>
<ol class="enumerate">
<li> Use the package&rsquo;s <samp class="file">configure</samp> script to create a static library
<samp class="file">src/build/libmyLib.a</samp>.  This can then be treated in the same way
as external software, for example having in <samp class="file">src/Makevars</samp>
<div class="example">
<pre class="example-preformatted">PKG_CPPFLAGS = -Ilibs/include
PKG_LIBS = build/libmyLib.a
</pre></div>
<p>(<code class="code">-Lbuild -lmyLib</code> could also be used but this explicit
specification avoids any confusion with dynamic libraries of the same
name.)
</p>
<p>The <samp class="file">configure</samp> script will need to contain something like (for C
code)
</p><div class="example">
<pre class="example-preformatted">: ${R_HOME=`R RHOME`}
if test -z &quot;${R_HOME}&quot;; then
  echo &quot;could not determine R_HOME&quot;
  exit 1
fi
CC=`&quot;${R_HOME}/bin/R&quot; CMD config CC`
CFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CFLAGS`
CPPFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config CPPFLAGS`
LDFLAGS=`&quot;${R_HOME}/bin/R&quot; CMD config LDFLAGS`

cd src
mkdir build &amp;&amp; cd build
cmake -S ../libs \
  -DCMAKE_BUILD_TYPE=Release \
  -DBUILD_SHARED_LIBS:bool=OFF \
  -DCMAKE_POSITION_INDEPENDENT_CODE:bool=ON
${MAKE}
</pre></div>

</li><li> Use <samp class="file">src/Makevars</samp> (or <samp class="file">src/Makevars.win</samp> or <samp class="file">Makevars.ucrt</samp>) to build within the
subdirectory.  This could be something like (for C code)
<div class="example">
<pre class="example-preformatted">PKG_CPPFLAGS = -Ilibs/include
PKG_LIBS = libs/libmyLib.a

$(SHLIB): mylibs

mylibs:
        (cd libs; \
          CC=&quot;$(CC)&quot; CFLAGS=&quot;$(CFLAGS)&quot; \
          CPPFLAGS=&quot;$(CPPFLAGS)&quot; LDFLAGS=&quot;$(LDFLAGS)&quot; \
	  cmake . \
	    -DCMAKE_BUILD_TYPE=Release \
	    -DBUILD_SHARED_LIBS:bool=OFF \
	    -DCMAKE_POSITION_INDEPENDENT_CODE:bool=ON; \
	  $(MAKE))

</pre></div>
<p>the compiler and other settings having been set as Make variables by an
R makefile included by <code class="command">INSTALL</code> before <samp class="file">src/Makevars</samp>.
</p>
</li></ol>

<p>A complication is that on macOS <code class="command">cmake</code> (where installed) is
commonly not on the path but at
<samp class="file">/Applications/CMake.app/Contents/bin/cmake</samp>.  One way to work
around this is for the package&rsquo;s <samp class="file">configure</samp> script to include
</p><div class="example">
<pre class="example-preformatted">if test -z &quot;$CMAKE&quot;; then CMAKE=&quot;`which cmake`&quot;; fi
if test -z &quot;$CMAKE&quot;; then CMAKE=/Applications/CMake.app/Contents/bin/cmake; fi
if test -f &quot;$CMAKE&quot;; then echo &quot;no ‘cmake’ command found&quot;; exit 1; fi
</pre></div>
<p>and for the second approach to substitute <code class="env">CMAKE</code> into
<samp class="file">src/Makevars</samp>.  This also applies to the ancillary command
<code class="command">ctest</code>, if used.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Checking-and-building-packages">
<div class="nav-panel">
<p>
Next: <a href="#Writing-package-vignettes" accesskey="n" rel="next">Writing package vignettes</a>, Previous: <a href="#Configure-and-cleanup" accesskey="p" rel="prev">Configure and cleanup</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Checking-and-building-packages-1"><span>1.3 Checking and building packages<a class="copiable-link" href="#Checking-and-building-packages-1"> &para;</a></span></h3>

<p>Before using these tools, please check that your package can be
installed.  <code class="code">R CMD check</code> will <em class="emph">inter alia</em> do this, but you
may get more detailed error messages doing the install directly.
</p>

<p>If your package specifies an encoding in its <samp class="file">DESCRIPTION</samp> file,
you should run these tools in a locale which makes use of that encoding:
they may not work at all or may work incorrectly in other locales
(although UTF-8 locales will most likely work).
</p>
<blockquote class="quotation">
<p><b class="b">Note:</b> <code class="code">R CMD check</code> and <code class="code">R CMD build</code> run R processes with
<samp class="option">--vanilla</samp> in which none of the user&rsquo;s startup files are read.
If you need <code class="env">R_LIBS</code> set (to find packages in a non-standard
library) you can set it in the environment: also you can use the check
and build environment files (as specified by the environment variables
<code class="env">R_CHECK_ENVIRON</code> and <code class="env">R_BUILD_ENVIRON</code>; if unset,
files<a class="footnote" id="DOCF52" href="#FOOT52"><sup>52</sup></a>  <samp class="file">~/.R/check.Renviron</samp> and
<samp class="file">~/.R/build.Renviron</samp> are used) to set environment variables when
using these utilities.
</p></blockquote>

<blockquote class="quotation">
<p><b class="b">Note to Windows users:</b> <code class="code">R CMD build</code> may make use of the Windows toolset (see the &ldquo;R
Installation and Administration&rdquo; manual) if present and in your path,
and it is required for packages which need it to install (including
those with <samp class="file">configure.win</samp>,  <samp class="file">cleanup.win</samp>, <samp class="file">configure.ucrt</samp>
or <samp class="file">cleanup.ucrt</samp> scripts or a
<samp class="file">src</samp> directory) and e.g. need vignettes built.
</p>
<p>You may need to set the environment variable <code class="env">TMPDIR</code> to point to a
suitable writable directory with a path not containing spaces &ndash; use
forward slashes for the separators.  Also, the directory needs to be on
a case-honouring file system (some network-mounted file systems are
not).
</p></blockquote>


<ul class="mini-toc">
<li><a href="#Checking-packages" accesskey="1">Checking packages</a></li>
<li><a href="#Building-package-tarballs" accesskey="2">Building package tarballs</a></li>
<li><a href="#Building-binary-packages" accesskey="3">Building binary packages</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Checking-packages">
<div class="nav-panel">
<p>
Next: <a href="#Building-package-tarballs" accesskey="n" rel="next">Building package tarballs</a>, Previous: <a href="#Checking-and-building-packages" accesskey="p" rel="prev">Checking and building packages</a>, Up: <a href="#Checking-and-building-packages" accesskey="u" rel="up">Checking and building packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Checking-packages-1"><span>1.3.1 Checking packages<a class="copiable-link" href="#Checking-packages-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Checking-packages"></a>

<a class="index-entry-id" id="index-R-CMD-check"></a>
<p>Using <code class="code">R CMD check</code>, the R package checker, one can test whether
<em class="emph">source</em> R packages work correctly.  It can be run on one or
more directories, or compressed package <code class="command">tar</code> archives with
extension <samp class="file">.tar.gz</samp>, <samp class="file">.tgz</samp>, <samp class="file">.tar.bz2</samp> or
<samp class="file">.tar.xz</samp>.
</p>
<p>It is strongly recommended that the final checks are run on a
<code class="command">tar</code> archive prepared by <code class="command">R CMD build</code>.
</p>
<p>This runs a series of checks, including
</p>
<ol class="enumerate">
<li> The package is installed.  This will warn about missing cross-references
and duplicate aliases in help files.

</li><li> The file names are checked to be valid across file systems and supported
operating system platforms.

</li><li> The files and directories are checked for sufficient permissions
(Unix-alikes only).

</li><li> The files are checked for binary executables, using a suitable version
of <code class="command">file</code> if available<a class="footnote" id="DOCF53" href="#FOOT53"><sup>53</sup></a>.  (There may be
rare false positives.)

</li><li> The <samp class="file">DESCRIPTION</samp> file is checked for completeness, and some of its
entries for correctness.  Unless installation tests are skipped,
checking is aborted if the package dependencies cannot be resolved at
run time.  (You may need to set <code class="env">R_LIBS</code> in the environment if
dependent packages are in a separate library tree.) One check is that
the package name is not that of a standard package, nor one of the
defunct standard packages (&lsquo;<samp class="samp">ctest</samp>&rsquo;, &lsquo;<samp class="samp">eda</samp>&rsquo;, &lsquo;<samp class="samp">lqs</samp>&rsquo;,
&lsquo;<samp class="samp">mle</samp>&rsquo;, &lsquo;<samp class="samp">modreg</samp>&rsquo;, &lsquo;<samp class="samp">mva</samp>&rsquo;, &lsquo;<samp class="samp">nls</samp>&rsquo;, &lsquo;<samp class="samp">stepfun</samp>&rsquo; and
&lsquo;<samp class="samp">ts</samp>&rsquo;).  Another check is that all packages mentioned in
<code class="code">library</code> or <code class="code">require</code>s or from which the <samp class="file">NAMESPACE</samp>
file imports or are called <em class="emph">via</em> <code class="code">::</code> or <code class="code">:::</code> are listed
(in &lsquo;<samp class="samp">Depends</samp>&rsquo;, &lsquo;<samp class="samp">Imports</samp>&rsquo;, &lsquo;<samp class="samp">Suggests</samp>&rsquo;): this is not an
exhaustive check of the actual imports.

</li><li> Available index information (in particular, for demos and vignettes) is
checked for completeness.

</li><li> The package subdirectories are checked for suitable file names and for
not being empty.  The checks on file names are controlled by the option
<samp class="option">--check-subdirs=<var class="var">value</var></samp>.  This defaults to &lsquo;<samp class="samp">default</samp>&rsquo;,
which runs the checks only if checking a tarball: the default can be
overridden by specifying the value as &lsquo;<samp class="samp">yes</samp>&rsquo; or &lsquo;<samp class="samp">no</samp>&rsquo;.  Further,
the check on the <samp class="file">src</samp> directory is only run if the package
does not contain a <samp class="file">configure</samp> script (which corresponds to the
value &lsquo;<samp class="samp">yes-maybe</samp>&rsquo;) and there is no <samp class="file">src/Makefile</samp> or
<samp class="file">src/Makefile.in</samp>.

<p>To allow a <samp class="file">configure</samp> script to generate suitable files, files
ending in &lsquo;<samp class="samp">.in</samp>&rsquo; will be allowed in the <samp class="file">R</samp> directory.
</p>
<p>A warning is given for directory names that look like R package check
directories &ndash; many packages have been submitted to <abbr class="acronym">CRAN</abbr>
containing these.
</p>
</li><li> The R files are checked for syntax errors.  Bytes which are
non-<abbr class="acronym">ASCII</abbr> are reported as warnings, but these should be
regarded as errors unless it is known that the package will always be
used in the same locale.

</li><li> It is checked that the package can be loaded, first with the usual
default packages and then only with package <strong class="strong">base</strong> already
loaded. It is checked that the namespace can be loaded in an empty
session with only the <strong class="strong">base</strong> namespace loaded.  (Namespaces and
packages can be loaded very early in the session, before the default
packages are available, so packages should work then.)

</li><li> The R files are checked for correct calls to <code class="code">library.dynam</code>.
Package startup functions are checked for correct argument lists and
(incorrect) calls to functions which modify the search path or
inappropriately generate messages.  The R code is checked for
possible problems using <a class="url" href="https://CRAN.R-project.org/package=codetools"><strong class="strong">codetools</strong></a>.  In addition, it is checked
whether S3 methods have all the arguments of the corresponding generic, and
whether the final argument of replacement functions is called
&lsquo;<samp class="samp">value</samp>&rsquo;.  All foreign function calls (<code class="code">.C</code>, <code class="code">.Fortran</code>,
<code class="code">.Call</code> and <code class="code">.External</code> calls) are tested to see if they have
a <code class="code">PACKAGE</code> argument, and if not, whether the appropriate DLL might
be deduced from the namespace of the package.  Any other calls are
reported.  (The check is generous, and users may want to supplement this
by examining the output of <code class="code">tools::checkFF(&quot;mypkg&quot;, verbose=TRUE)</code>,
especially if the intention were to always use a <code class="code">PACKAGE</code>
argument)

</li><li> The <samp class="file">Rd</samp> files are checked for correct syntax and metadata,
including the presence of the mandatory fields (<code class="code">\name</code>, <code class="code">\alias</code>,
<code class="code">\title</code> and <code class="code">\description</code>).  The <samp class="file">Rd</samp> name and
title are checked for being non-empty, and there is a check for missing
cross-references (links).

</li><li> A check is made for missing documentation entries, such as undocumented
user-level objects in the package.

</li><li> Documentation for functions, data sets, and S4 classes is checked for
consistency with the corresponding code.

</li><li> It is checked whether all function arguments given in <code class="code">\usage</code>
sections of <samp class="file">Rd</samp> files are documented in the corresponding
<code class="code">\arguments</code> section.

</li><li> The <samp class="file">data</samp> directory is checked for non-<abbr class="acronym">ASCII</abbr> characters
and for the use of reasonable levels of compression.

</li><li> C, C++ and Fortran source and header files<a class="footnote" id="DOCF54" href="#FOOT54"><sup>54</sup></a> are
tested for portable (<abbr class="abbr">LF</abbr>-only) line endings.  If there is a
<samp class="file">Makefile</samp> or <samp class="file">Makefile.in</samp> or <samp class="file">Makevars</samp> or
<samp class="file">Makevars.in</samp> file under the <samp class="file">src</samp> directory, it is checked
for portable line endings and the correct use of &lsquo;<samp class="samp">$(BLAS_LIBS)</samp>&rsquo; and
&lsquo;<samp class="samp">$(LAPACK_LIBS)</samp>&rsquo;

<p>Compiled code is checked for symbols corresponding to functions which
might terminate R or write to <samp class="file">stdout</samp>/<samp class="file">stderr</samp> instead of
the console.  Note that the latter might give false positives in that
the symbols might be pulled in with external libraries and could never
be called.  Windows<a class="footnote" id="DOCF55" href="#FOOT55"><sup>55</sup></a> users
should note that the Fortran and C++ runtime libraries are examples of
such external libraries.
</p>
</li><li> Some checks are made of the contents of the <samp class="file">inst/doc</samp> directory.
These always include checking for files that look like leftovers, and if
suitable tools (such as <code class="command">qpdf</code>) are available, checking that the
PDF documentation is of minimal size.

</li><li> The examples provided by the package&rsquo;s documentation are run.
(see <a class="pxref" href="#Writing-R-documentation-files">Writing R documentation files</a>, for information on using
<code class="code">\examples</code> to create executable example code.)  If there is a file
<samp class="file">tests/Examples/<var class="var">pkg</var>-Ex.Rout.save</samp>, the output of running the
examples is compared to that file.

<p>Of course, released packages should be able to run at least their own
examples.  Each example is run in a &lsquo;clean&rsquo; environment (so earlier
examples cannot be assumed to have been run), and with the variables
<code class="code">T</code> and <code class="code">F</code> redefined to generate an error unless they are set
in the example:
See <a data-manual="R-intro" href="https://cran.r-project.org/doc/manuals/R-intro.html#Logical-vectors">Logical vectors</a> in <cite class="cite">An Introduction to R</cite>.
</p>
</li><li> If the package sources contain a <samp class="file">tests</samp> directory then the tests
specified in that directory are run.  (Typically they will consist of a
set of <samp class="file">.R</samp> source files and target output files
<samp class="file">.Rout.save</samp>.)  Please note that the comparison will be done in the
end user&rsquo;s locale, so the target output files should be <abbr class="acronym">ASCII</abbr>
if at all possible.  (The command line option <code class="code">--test-dir=foo</code> may
be used to specify tests in a non-standard location.  For example,
unusually slow tests could be placed in <samp class="file">inst/slowTests</samp> and then
<code class="code">R CMD check --test-dir=inst/slowTests</code> would be used to run them.
Other names that have been suggested are, for example,
<samp class="file">inst/testWithOracle</samp> for tests that require Oracle to be installed,
<samp class="file">inst/randomTests</samp> for tests which use random values and may
occasionally fail by chance, etc.)

</li><li> The R code in package vignettes (see <a class="pxref" href="#Writing-package-vignettes">Writing package vignettes</a>) is
executed, and the vignettes re-made from their sources as a check of
completeness of the sources (unless there is a &lsquo;<samp class="samp">BuildVignettes</samp>&rsquo;
field in the package&rsquo;s <samp class="file">DESCRIPTION</samp> file with a false value).  If
there is a target output file <samp class="file">.Rout.save</samp> in the vignette source
directory, the output from running the code in that vignette is compared
with the target output file and any differences are reported (but not
recorded in the log file).  (If the vignette sources are in the
deprecated location <samp class="file">inst/doc</samp>, do mark such target output files to
not be installed in <samp class="file">.Rinstignore</samp>.)

<p>If there is an error<a class="footnote" id="DOCF56" href="#FOOT56"><sup>56</sup></a> in executing the R code in vignette <samp class="file"><var class="var">foo.ext</var></samp>, a log
file <samp class="file"><var class="var">foo.ext</var>.log</samp> is created in the check directory.  The
vignettes are re-made in a copy of the package sources in the
<samp class="file">vign_test</samp> subdirectory of the check directory, so for further
information on errors look in directory
<samp class="file"><var class="var">pkgname</var>/vign_test/vignettes</samp>.  (It is only retained if there
are errors or if environment variable <code class="env">_R_CHECK_CLEAN_VIGN_TEST_</code> is
set to a false value.)
</p>
</li><li> The PDF version of the package&rsquo;s manual is created (to check that the
<samp class="file">Rd</samp> files can be converted successfully).  This needs LaTeX and
suitable fonts and LaTeX packages to be installed.
See <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Making-the-manuals">Making the manuals</a> in <cite class="cite">R Installation and Administration</cite>.

</li><li> Optionally (including by <code class="command">R CMD check --as-cran</code>) the HTML
version of the manual is created and checked for compliance with the
HTML5 standard.  This requires a recent version<a class="footnote" id="DOCF57" href="#FOOT57"><sup>57</sup></a> of &lsquo;HTML
Tidy&rsquo;, either on the path or at a location specified by environment
variable <code class="env">R_TIDYCMD</code>. Up-to-date versions can be installed from
<a class="uref" href="http://binaries.html-tidy.org/">http://binaries.html-tidy.org/</a>.
</li></ol>

<p>All these tests are run with collation set to the <code class="code">C</code> locale, and
for the examples and tests with environment variable <code class="env">LANGUAGE=en</code>:
this is to minimize differences between platforms.
</p>
<p>Use <kbd class="kbd">R CMD check --help</kbd> to obtain more information about the usage
of the R package checker.  A subset of the checking steps can be
selected by adding command-line options. It also allows customization by
setting environment variables <code class="env">_R_CHECK_*_</code><!-- /@w --> as described in
<a data-manual="R-ints" href="https://cran.r-project.org/doc/manuals/R-ints.html#Tools">Tools</a> in <cite class="cite">R Internals</cite>:
a set of these customizations similar to those used by <abbr class="acronym">CRAN</abbr>
can be selected by the option <samp class="option">--as-cran</samp> (which works best if
Internet access is available).  Some Windows users may
need to set environment variable <code class="env">R_WIN_NO_JUNCTIONS</code> to a non-empty
value.  The test of cyclic declarations<a class="footnote" id="DOCF58" href="#FOOT58"><sup>58</sup></a>in <samp class="file">DESCRIPTION</samp> files needs
repositories (including <abbr class="acronym">CRAN</abbr>) set: do this in
<samp class="file">~/.Rprofile</samp>, by e.g.
</p><div class="example">
<pre class="example-preformatted">options(repos = c(CRAN=&quot;https://cran.r-project.org&quot;))
</pre></div>

<p>One check customization which can be revealing is
</p><div class="example">
<pre class="example-preformatted">_R_CHECK_CODETOOLS_PROFILE_=&quot;suppressLocalUnused=FALSE&quot;
</pre></div>
<p>which reports unused local assignments.  Not only does this point out
computations which are unnecessary because their results are unused, it
also can uncover errors.  (Two such are to intend to update an object by
assigning a value but mistype its name or assign in the wrong scope,
for example using <code class="code">&lt;-</code> where <code class="code">&lt;&lt;-</code> was intended.)  This can
give false positives, most commonly because of non-standard evaluation
for formulae and because the intention is to return objects in the
environment of a function for later use.
</p>
<p>Complete checking of a package which contains a file <samp class="file">README.md</samp>
needs a reasonably current version of  <code class="command">pandoc</code> installed: see
<a class="uref" href="https://pandoc.org/installing.html">https://pandoc.org/installing.html</a>.
</p>
<p>You do need to ensure that the package is checked in a suitable locale
if it contains non-<abbr class="acronym">ASCII</abbr> characters.  Such packages are likely
to fail some of the checks in a <code class="code">C</code> locale, and <code class="command">R CMD
check</code> will warn if it spots the problem.  You should be able to check
any package in a UTF-8 locale (if one is available).  Beware that
although a <code class="code">C</code> locale is rarely used at a console, it may be the
default if logging in remotely or for batch jobs.
</p>
<p>Often <code class="command">R CMD check</code> will need to consult a CRAN repository to
check details of uninstalled packages.  Normally this defaults to the
CRAN main site, but a mirror can be specified by setting environment
variables <code class="env">R_CRAN_WEB</code> and (rarely needed) <code class="env">R_CRAN_SRC</code> to the
URL of a CRAN mirror.
</p>
<p>It is possible to install a package and then check the installed
package. To do so first install the package and keep a log of the
installation:
</p><div class="example">
<pre class="example-preformatted">R CMD INSTALL -l <var class="var">libdir</var> <var class="var">pkg</var> &gt; <var class="var">pkg</var>.log 2&gt;&amp;1
</pre></div>
<p>and then use
</p><div class="example">
<pre class="example-preformatted">Rdev CMD check -l <var class="var">libdir</var> --install=check:<var class="var">pkg</var>.log <var class="var">pkg</var>
</pre></div>
<p>(Specifying the library is required: it ensures that the just-installed
package is the one checked.  If you know for sure only one copy is
installed you can use <samp class="option">--install=skip</samp>: this is used for R
installation&rsquo;s <code class="command">make check-recommended</code>.)
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Building-package-tarballs">
<div class="nav-panel">
<p>
Next: <a href="#Building-binary-packages" accesskey="n" rel="next">Building binary packages</a>, Previous: <a href="#Checking-packages" accesskey="p" rel="prev">Checking packages</a>, Up: <a href="#Checking-and-building-packages" accesskey="u" rel="up">Checking and building packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Building-package-tarballs-1"><span>1.3.2 Building package tarballs<a class="copiable-link" href="#Building-package-tarballs-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Building-source-packages"></a>

<a class="index-entry-id" id="index-R-CMD-build"></a>
<a class="index-entry-id" id="index-Package-builder"></a>
<a class="index-entry-id" id="index-tarballs"></a>
<p>Packages may be distributed in source form as &ldquo;tarballs&rdquo;
(<samp class="file">.tar.gz</samp> files) or in binary form. The source form can be
installed on all platforms with suitable tools and is the usual form for
Unix-like systems; the binary form is platform-specific, and is the more
common distribution form for the macOS and &lsquo;<samp class="samp">x86_64</samp>&rsquo; Windows platforms.
</p>
<p>Using <code class="command">R CMD build</code>, the R package builder, one can build
R package tarballs from their sources (for example, for subsequent
release).  It is recommended that packages are built for release by the
current release version of R or &lsquo;<samp class="samp">r-patched</samp>&rsquo;, to avoid
inadvertently picking up new features of a development version of R.
</p>
<p>Prior to actually building the package in the standard gzipped tar file
format, a few diagnostic checks and cleanups are performed.  In
particular, it is tested whether object indices exist and can be assumed
to be up-to-date, and C, C++ and Fortran source files and relevant
makefiles in a <samp class="file">src</samp> directory are tested and converted to <abbr class="abbr">LF</abbr>
line-endings if necessary.
</p>
<p>Run-time checks whether the package works correctly should be performed
using <code class="command">R CMD check</code> prior to invoking the final build procedure.
</p>
<a class="index-entry-id" id="index-_002eRbuildignore-file"></a>
<p>To exclude files from being put into the package, one can specify a list
of exclude patterns in file <samp class="file">.Rbuildignore</samp> in the top-level source
directory.  These patterns should be Perl-like regular expressions (see
the help for <code class="code">regexp</code> in R for the precise details), one per
line, to be matched case-insensitively against the file and directory
names relative to the top-level package source directory.  In addition,
directories from source control systems<a class="footnote" id="DOCF59" href="#FOOT59"><sup>59</sup></a> or from
<code class="command">eclipse</code><a class="footnote" id="DOCF60" href="#FOOT60"><sup>60</sup></a>, directories with
names <samp class="file">check</samp>, <samp class="file">chm</samp>, or ending <samp class="file">.Rcheck</samp> or <samp class="file">Old</samp>
or <samp class="file">old</samp> and files
<samp class="file">GNUMakefile</samp><a class="footnote" id="DOCF61" href="#FOOT61"><sup>61</sup></a>, <samp class="file">Read-and-delete-me</samp> or with base names
starting with &lsquo;<samp class="samp">.#</samp>&rsquo;, or starting and ending with &lsquo;<samp class="samp">#</samp>&rsquo;, or ending
in &lsquo;<samp class="samp">~</samp>&rsquo;, &lsquo;<samp class="samp">.bak</samp>&rsquo; or &lsquo;<samp class="samp">.swp</samp>&rsquo;, are excluded by
default<a class="footnote" id="DOCF62" href="#FOOT62"><sup>62</sup></a>.  In addition,
same-package tarballs (from previous builds) and their binary forms will
be excluded from the top-level directory, as well as
those files in the <samp class="file">R</samp>, <samp class="file">demo</samp> and <samp class="file">man</samp>
directories which are flagged by <code class="command">R CMD check</code> as having invalid
names.
</p>
<p>Use <kbd class="kbd">R CMD build --help</kbd> to obtain more information about the usage
of the R package builder.
</p>
<p>Unless <kbd class="kbd">R CMD build</kbd> is invoked with the
<samp class="option">--no-build-vignettes</samp> option (or the package&rsquo;s
<samp class="file">DESCRIPTION</samp> contains &lsquo;<samp class="samp">BuildVignettes: no</samp>&rsquo; or similar), it
will attempt to (re)build the vignettes (see <a class="pxref" href="#Writing-package-vignettes">Writing package vignettes</a>) in the package.  To do so it installs the current package
into a temporary library tree, but any dependent packages need to be
installed in an available library tree (see the Note: at the top of this
section).
</p>
<p>Similarly, if the <samp class="file">.Rd</samp> documentation files contain any
<code class="code">\Sexpr</code> macros (see <a class="pxref" href="#Dynamic-pages">Dynamic pages</a>), the package will be
temporarily installed to execute them.  Post-execution binary copies of
those pages containing build-time macros will be saved in
<samp class="file">build/partial.rdb</samp>.  If there are any install-time or render-time
macros, a <samp class="file">.pdf</samp> version of the package manual will be built and
installed in the <samp class="file">build</samp> subdirectory.  (This allows
<abbr class="acronym">CRAN</abbr> or other repositories to display the manual even if they
are unable to install the package.)  This can be suppressed by the
option <samp class="option">--no-manual</samp> or if package&rsquo;s <samp class="file">DESCRIPTION</samp> contains
&lsquo;<samp class="samp">BuildManual: no</samp>&rsquo; or similar.
</p>
<p>One of the checks that <code class="command">R CMD build</code> runs is for empty source
directories.  These are in most (but not all) cases unintentional, if
they are intentional use the option <samp class="option">--keep-empty-dirs</samp> (or set
the environment variable <code class="env">_R_BUILD_KEEP_EMPTY_DIRS_</code> to &lsquo;<samp class="samp">TRUE</samp>&rsquo;,
or have a &lsquo;<samp class="samp">BuildKeepEmpty</samp>&rsquo; field with a true value in the
<samp class="file">DESCRIPTION</samp> file).
</p>
<p>The <samp class="option">--resave-data</samp> option allows saved images (<samp class="file">.rda</samp> and
<samp class="file">.RData</samp> files) in the <samp class="file">data</samp> directory to be optimized for
size.  It will also compress tabular files and convert <samp class="file">.R</samp> files
to saved images.  It can take values <code class="code">no</code>, <code class="code">gzip</code> (the default
if this option is not supplied, which can be changed by setting the
environment variable <code class="env">_R_BUILD_RESAVE_DATA_</code>) and <code class="code">best</code>
(equivalent to giving it without a value), which chooses the most
effective compression.  Using <code class="code">best</code> adds a dependence on <code class="code">R
(&gt;= 2.10)</code> to the <samp class="file">DESCRIPTION</samp> file if <code class="command">bzip2</code> or
<code class="command">xz</code> compression is selected for any of the files.  If this is
thought undesirable, <samp class="option">--resave-data=gzip</samp> (which is the default
if that option is not supplied) will do what compression it can with
<code class="command">gzip</code>.  A package can control how its data is resaved by
supplying a &lsquo;<samp class="samp">BuildResaveData</samp>&rsquo; field (with one of the values given
earlier in this paragraph) in its <samp class="file">DESCRIPTION</samp> file.
</p>
<p>The <samp class="option">--compact-vignettes</samp> option will run
<code class="code">tools::compactPDF</code> over the PDF files in <samp class="file">inst/doc</samp> (and its
subdirectories) to losslessly compress them.  This is not enabled by
default (it can be selected by environment variable
<code class="env">_R_BUILD_COMPACT_VIGNETTES_</code>) and needs <code class="command">qpdf</code>
(<a class="uref" href="https://qpdf.sourceforge.io/">https://qpdf.sourceforge.io/</a>) to be available.
</p>
<p>It can be useful to run <code class="command">R CMD check --check-subdirs=yes</code> on the
built tarball as a final check on the contents.
</p>
<p>Where a non-POSIX file system is in use which does not utilize execute
permissions, some care is needed with permissions.  This applies on
Windows and to e.g. FAT-formatted drives and SMB-mounted file systems
on other OSes.  The &lsquo;mode&rsquo; of the file recorded in the tarball will be
whatever <code class="code">file.info()</code> returns.  On Windows this will record only
directories as having execute permission and on other OSes it is likely
that all files have reported &lsquo;mode&rsquo; <code class="code">0777</code>.  A particular issue is
packages being built on Windows which are intended to contain executable
scripts such as <samp class="file">configure</samp> and <samp class="file">cleanup</samp>: <code class="command">R CMD
build</code> ensures those two are recorded with execute permission.
</p>
<p>Directory <samp class="file">build</samp> of the package sources is reserved for use by
<code class="command">R CMD build</code>: it contains information which may not easily be
created when the package is installed, including index information on
the vignettes and, rarely, information on the help pages and perhaps a
copy of the PDF reference manual (see above).
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Building-binary-packages">
<div class="nav-panel">
<p>
Previous: <a href="#Building-package-tarballs" accesskey="p" rel="prev">Building package tarballs</a>, Up: <a href="#Checking-and-building-packages" accesskey="u" rel="up">Checking and building packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Building-binary-packages-1"><span>1.3.3 Building binary packages<a class="copiable-link" href="#Building-binary-packages-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Building-binary-packages"></a>

<p>Binary packages are compressed copies of installed versions of
packages.  They contain compiled shared libraries rather than C, C++ or
Fortran source code, and the R functions are included in their installed
form.  The format and filename are platform-specific; for example, a
binary package for Windows is usually supplied as a <samp class="file">.zip</samp> file,
and for the macOS platform the default binary package file extension is
<samp class="file">.tgz</samp>.
</p>
<p>The recommended method of building binary packages is to use
</p>
<p><code class="command">R CMD INSTALL --build pkg</code>
</p>
<p>where <samp class="file">pkg</samp> is either the name of a source tarball (in the usual
<samp class="file">.tar.gz</samp> format) or the location of the directory of the package
source to be built.  This operates by first installing the package and
then packing the installed binaries into the appropriate binary package
file for the particular platform.
</p>
<p>By default, <code class="command">R CMD INSTALL --build</code> will attempt to install the
package into the default library tree for the local installation of
R. This has two implications:
</p>
<ul class="itemize mark-bullet">
<li>If the installation is successful, it will overwrite any existing installation
of the same package.

</li><li>The default library tree must have write permission; if not, the package will
not install and the binary will not be created.

</li></ul>

<p>To prevent changes to the present working installation or to provide an
install location with write access, create a suitably located directory
with write access and use the <code class="command">-l</code> option to build the package
in the chosen location.  The usage is then
</p>
<p><code class="command">R CMD INSTALL -l location --build pkg</code>
</p>
<p>where <samp class="file">location</samp> is the chosen directory with write access. The package
will be installed as a subdirectory of <samp class="file">location</samp>, and the package binary
will be created in the current directory.
</p>
<p>Other options for <code class="command">R CMD INSTALL</code> can be found using <code class="command">R
CMD INSTALL --help</code>, and platform-specific details for special cases are
discussed in the platform-specific FAQs.
</p>



<p>Finally, at least one web-based service is available for building binary
packages from (checked) source code: WinBuilder (see
<a class="uref" href="https://win-builder.R-project.org/">https://win-builder.R-project.org/</a>) is able to build
&lsquo;<samp class="samp">x86_64</samp>&rsquo; Windows binaries. Note that this is intended for
developers on other platforms who do not have access to Windows but wish
to provide binaries for the Windows platform.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Writing-package-vignettes">
<div class="nav-panel">
<p>
Next: <a href="#Package-namespaces" accesskey="n" rel="next">Package namespaces</a>, Previous: <a href="#Checking-and-building-packages" accesskey="p" rel="prev">Checking and building packages</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Writing-package-vignettes-1"><span>1.4 Writing package vignettes<a class="copiable-link" href="#Writing-package-vignettes-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-vignettes"></a>
<a class="index-entry-id" id="index-Sweave"></a>


<p>In addition to the help files in <samp class="file">Rd</samp> format, R packages allow
the inclusion of documents in arbitrary other formats.  The standard
location for these is subdirectory <samp class="file">inst/doc</samp> of a source package,
the contents will be copied to subdirectory <samp class="file">doc</samp> when the package
is installed.  Pointers from package help indices to the installed
documents are automatically created.  Documents in <samp class="file">inst/doc</samp> can
be in arbitrary format, however we strongly recommend providing them in
PDF format, so users on almost all platforms can easily read them.  To
ensure that they can be accessed from a browser (as an <abbr class="acronym">HTML</abbr> index is
provided), the file names should start with an <abbr class="acronym">ASCII</abbr> letter
and be comprised entirely of <abbr class="acronym">ASCII</abbr> letters or digits or hyphen
or underscore.
</p>
<p>A special case is <em class="emph">package vignettes</em>.  Vignettes are documents in
PDF or <abbr class="acronym">HTML</abbr> format obtained from plain-text literate source files
from which R knows how to extract R code and create output (in
PDF/<abbr class="acronym">HTML</abbr> or intermediate LaTeX).  Vignette engines do this work,
using &ldquo;tangle&rdquo; and &ldquo;weave&rdquo; functions respectively.  Sweave, provided
by the R distribution, is the default engine.  Other vignette engines
besides Sweave are supported; see <a class="ref" href="#Non_002dSweave-vignettes">Non-Sweave vignettes</a>.
</p>
<p>Package vignettes have their sources in subdirectory <samp class="file">vignettes</samp> of
the package sources.  Note that the location of the vignette sources
only affects <code class="command">R CMD build</code> and <code class="command">R CMD check</code>: the
tarball built by <code class="command">R CMD build</code> includes in <samp class="file">inst/doc</samp> the
components intended to be installed.
</p>
<p>Sweave vignette sources are normally given the file extension
<samp class="file">.Rnw</samp> or <samp class="file">.Rtex</samp>, but for historical reasons
extensions<a class="footnote" id="DOCF63" href="#FOOT63"><sup>63</sup></a> <samp class="file">.Snw</samp> and
<samp class="file">.Stex</samp> are also recognized.  Sweave allows the integration of
LaTeX documents: see the <code class="code">Sweave</code> help page in R and the
<code class="code">Sweave</code> vignette in package <strong class="strong">utils</strong> for details on the
source document format.
</p>
<p>Package vignettes are tested by <code class="code">R CMD check</code> by executing all R
code chunks they contain (except those marked for non-evaluation, e.g.,
with option <code class="code">eval=FALSE</code> for Sweave).  The R working directory
for all vignette tests in <code class="code">R CMD check</code> is a <em class="emph">copy</em> of the
vignette source directory.  Make sure all files needed to run the R
code in the vignette (data sets, &hellip;) are accessible by either
placing them in the <samp class="file">inst/doc</samp> hierarchy of the source package or
by using calls to <code class="code">system.file()</code>.  All other files needed to
re-make the vignettes (such as LaTeX style files, BibTeX input
files and files for any figures not created by running the code in the
vignette) must be in the vignette source directory.  <code class="code">R CMD check</code> 
will check that vignette production has succeeded by comparing
modification times of output files in <samp class="file">inst/doc</samp> with
the source in <samp class="file">vignettes</samp>.
</p>
<p><code class="code">R CMD build</code> will automatically<a class="footnote" id="DOCF64" href="#FOOT64"><sup>64</sup></a> create the
(PDF or <abbr class="acronym">HTML</abbr> versions of the) vignettes in <samp class="file">inst/doc</samp> for
distribution with the package sources.  By including the vignette
outputs in the package sources it is not necessary that these can be
re-built at install time, i.e., the package author can use private R
packages, screen snapshots and LaTeX extensions which are only
available on their machine.<a class="footnote" id="DOCF65" href="#FOOT65"><sup>65</sup></a>
</p>
<p>By default <code class="code">R CMD build</code> will run <code class="code">Sweave</code> on all Sweave
vignette source files in <samp class="file">vignettes</samp>.  If <samp class="file">Makefile</samp> is found
in the vignette source directory, then <code class="code">R CMD build</code> will try to
run <code class="command">make</code> after the <code class="code">Sweave</code> runs, otherwise
<code class="code">texi2pdf</code> is run on each <samp class="file">.tex</samp> file produced.
</p>
<p>The first target in the <samp class="file">Makefile</samp> should take care of both
creation of PDF/<abbr class="acronym">HTML</abbr> files and cleaning up afterwards (including
after <code class="code">Sweave</code>), i.e., delete all files that shall not appear in
the final package archive.  Note that if the <code class="code">make</code> step runs R
it needs to be careful to respect the environment values of <code class="env">R_LIBS</code>
and <code class="env">R_HOME</code><a class="footnote" id="DOCF66" href="#FOOT66"><sup>66</sup></a>.
Finally, if there is a <samp class="file">Makefile</samp> and it has a &lsquo;<samp class="samp">clean:</samp>&rsquo;
target, <code class="command">make clean</code> is run.
</p>
<p>All the usual <em class="emph">caveats</em> about including a <samp class="file">Makefile</samp> apply.
It must be portable (no <abbr class="acronym">GNU</abbr> extensions), use <abbr class="abbr">LF</abbr> line endings
and must work correctly with a parallel <code class="command">make</code>: too many authors
have written things like
</p>
<div class="example">
<pre class="example-preformatted">## BAD EXAMPLE
all: pdf clean

pdf: ABC-intro.pdf ABC-details.pdf

%.pdf:  %.tex
        texi2dvi --pdf $*

clean:
        rm *.tex ABC-details-*.pdf
</pre></div>

<p>which will start removing the source files whilst <code class="command">pdflatex</code> is
working.
</p>
<p>Metadata lines can be placed in the source file, preferably in LaTeX
comments in the preamble.  One such is a <code class="code">\VignetteIndexEntry</code> of
the form
</p><div class="example">
<pre class="example-preformatted">%\VignetteIndexEntry{Using Animal}
</pre></div>
<p>Others you may see are <code class="code">\VignettePackage</code> (currently ignored),
<code class="code">\VignetteDepends</code> (a comma-separated list of package names)
and <code class="code">\VignetteKeyword</code> (which replaced
<code class="code">\VignetteKeywords</code>).  These are processed at package installation
time to create the saved data frame <samp class="file">Meta/vignette.rds</samp>.
The <code class="code">\VignetteEngine</code> statement
is described in <a class="ref" href="#Non_002dSweave-vignettes">Non-Sweave vignettes</a>.
Vignette metadata can be extracted from a source file using
<code class="code">tools::vignetteInfo</code>.
</p>
<p>At install time an <abbr class="acronym">HTML</abbr> index for all vignettes in the package is
automatically created from the <code class="code">\VignetteIndexEntry</code> statements
unless a file <samp class="file">index.html</samp> exists in directory
<samp class="file">inst/doc</samp>. This index is linked from the <abbr class="acronym">HTML</abbr> help index for
the package.  If you do supply a <samp class="file">inst/doc/index.html</samp> file it
should contain relative links only to files under the installed
<samp class="file">doc</samp> directory, or perhaps (not really an index) to <abbr class="acronym">HTML</abbr> help
files or to the <samp class="file">DESCRIPTION</samp> file, and be valid <abbr class="acronym">HTML</abbr> as
confirmed <em class="emph">via</em> the <a class="uref" href="https://validator.w3.org">W3C Markup
Validation Service</a> or <a class="uref" href="https://validator.nu/">Validator.nu</a>.
</p>
<p>Sweave/Stangle allows the document to specify the <code class="code">split=TRUE</code>
option to create a single R file for each code chunk: this will not
work for vignettes where it is assumed that each vignette source
generates a single file with the vignette extension replaced by
<samp class="file">.R</samp>.
</p>
<p>Do watch that PDFs are not too large &ndash; one in a <abbr class="acronym">CRAN</abbr> package
was 72MB!  This is usually caused by the inclusion of overly detailed
figures, which will not render well in PDF viewers.  Sometimes it is
much better to generate fairly high resolution bitmap (PNG, JPEG)
figures and include those in the PDF document.
</p>
<a class="index-entry-id" id="index-_002einstall_005fextras-file"></a>
<p>When <code class="command">R CMD build</code> builds the vignettes, it copies these and
the vignette sources from directory <samp class="file">vignettes</samp> to <samp class="file">inst/doc</samp>.
To install any other files from the <samp class="file">vignettes</samp> directory, include
a file <samp class="file">vignettes/.install_extras</samp> which specifies these as
Perl-like regular expressions on one or more lines.  (See the
description of the <samp class="file">.Rinstignore</samp> file for full details.)
</p>

<ul class="mini-toc">
<li><a href="#Encodings-and-vignettes" accesskey="1">Encodings and vignettes</a></li>
<li><a href="#Non_002dSweave-vignettes" accesskey="2">Non-Sweave vignettes</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Encodings-and-vignettes">
<div class="nav-panel">
<p>
Next: <a href="#Non_002dSweave-vignettes" accesskey="n" rel="next">Non-Sweave vignettes</a>, Previous: <a href="#Writing-package-vignettes" accesskey="p" rel="prev">Writing package vignettes</a>, Up: <a href="#Writing-package-vignettes" accesskey="u" rel="up">Writing package vignettes</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Encodings-and-vignettes-1"><span>1.4.1 Encodings and vignettes<a class="copiable-link" href="#Encodings-and-vignettes-1"> &para;</a></span></h4>

<p>Vignettes will in general include descriptive text, R input, R
output and figures, LaTeX include files and bibliographic references.
As any of these may contain non-<abbr class="acronym">ASCII</abbr> characters, the handling
of encodings can become very complicated.
</p>
<p>The vignette source file should be written in <abbr class="acronym">ASCII</abbr> or contain
a declaration of the encoding (see below).  This applies even to
comments within the source file, since vignette engines process comments
to look for options and metadata lines.  When an engine&rsquo;s weave and
tangle functions are called on the vignette source, it will be converted
to the encoding of the current R session.
</p>
<p><code class="code">Stangle()</code> will produce an R code file in the current locale&rsquo;s
encoding: for a non-<abbr class="acronym">ASCII</abbr> vignette what that is is recorded in a
comment at the top of the file.
</p>
<p><code class="code">Sweave()</code> will produce a <samp class="file">.tex</samp> file in the current
encoding, or in UTF-8 if that is declared.  Non-<abbr class="acronym">ASCII</abbr> encodings
need to be declared to LaTeX via a line like
</p><div class="example">
<pre class="example-preformatted">\usepackage[utf8]{inputenc}
</pre></div>
<p>(It is also possible to use the more recent &lsquo;<samp class="samp">inputenx</samp>&rsquo; LaTeX
package.) For files where this line is not needed (e.g. chapters
included within the body of a larger document, or non-Sweave
vignettes), the encoding may be declared using a comment like
</p><div class="example">
<pre class="example-preformatted">%\VignetteEncoding{UTF-8}
</pre></div>
<p>If the encoding is UTF-8, this can also be declared using
the declaration
</p><div class="example">
<pre class="example-preformatted">%\SweaveUTF8
</pre></div>
<p>If no declaration is given in the vignette, it will be assumed to be
in the encoding declared for the package.  If there is no encoding
declared in either place, then it is an error to use non-<abbr class="acronym">ASCII</abbr>
characters in the vignette.
</p>
<p>In any case, be aware that LaTeX may require the &lsquo;<samp class="samp">usepackage</samp>&rsquo;
declaration.
</p>
<p><code class="code">Sweave()</code> will also parse and evaluate the R code in each
chunk.  The R output will also be in the current locale (or <abbr class="acronym">UTF-8</abbr>
if so declared), and should
be covered by the &lsquo;<samp class="samp">inputenc</samp>&rsquo; declaration.  One thing people often
forget is that the R output may not be <abbr class="acronym">ASCII</abbr> even for
<abbr class="acronym">ASCII</abbr> R sources, for many possible reasons.  One common one
is the use of &lsquo;fancy&rsquo; quotes: see the R help on <code class="code">sQuote</code>: note
carefully that it is not portable to declare UTF-8 or CP1252 to cover
such quotes, as their encoding will depend on the locale used to run
<code class="code">Sweave()</code>:  this can be circumvented by setting
<code class="code">options(useFancyQuotes=&quot;UTF-8&quot;)</code> in the vignette.
</p>
<p>The final issue is the encoding of figures &ndash; this applies only to PDF
figures and not PNG etc.  The PDF figures will contain declarations for
their encoding, but the Sweave option <code class="code">pdf.encoding</code> may need to be
set appropriately: see the help for the <code class="code">pdf()</code> graphics device.
</p>
<p>As a real example of the complexities, consider the <a class="url" href="https://CRAN.R-project.org/package=fortunes"><strong class="strong">fortunes</strong></a>
package version &lsquo;<samp class="samp">1.4-0</samp>&rsquo;.  That package did not have a declared
encoding, and its vignette was in <abbr class="acronym">ASCII</abbr>.  However, the data it
displays are read from a UTF-8 CSV file and will be assumed to be in the
current encoding, so <samp class="file">fortunes.tex</samp> will be in UTF-8 in any locale.
Had <code class="code">read.table</code> been told the data were UTF-8, <samp class="file">fortunes.tex</samp>
would have been in the locale&rsquo;s encoding.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Non_002dSweave-vignettes">
<div class="nav-panel">
<p>
Previous: <a href="#Encodings-and-vignettes" accesskey="p" rel="prev">Encodings and vignettes</a>, Up: <a href="#Writing-package-vignettes" accesskey="u" rel="up">Writing package vignettes</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Non_002dSweave-vignettes-1"><span>1.4.2 Non-Sweave vignettes<a class="copiable-link" href="#Non_002dSweave-vignettes-1"> &para;</a></span></h4>

<p>Vignettes in formats other than Sweave are supported <em class="emph">via</em>
&ldquo;vignette engines&rdquo;.  For example <a class="url" href="https://CRAN.R-project.org/package=knitr"><strong class="strong">knitr</strong></a> version 1.1 or later
can create <samp class="file">.tex</samp> files from a variation on Sweave format, and
<samp class="file">.html</samp> files from a variation on &ldquo;markdown&rdquo; format. These
engines replace the <code class="code">Sweave()</code> function with other functions to
convert vignette source files into LaTeX files for processing into
<samp class="file">.pdf</samp>, or directly into <samp class="file">.pdf</samp> or <samp class="file">.html</samp> files. The
<code class="code">Stangle()</code> function is replaced with a function that extracts the
R source from a vignette.
</p>
<p>R recognizes non-Sweave vignettes using filename extensions specified
by the engine.  For example, the <a class="url" href="https://CRAN.R-project.org/package=knitr"><strong class="strong">knitr</strong></a> package supports
the extension <samp class="file">.Rmd</samp> (standing for
&ldquo;R markdown&rdquo;).  The user indicates the vignette engine
within the vignette source using a <code class="code">\VignetteEngine</code> line, for example
</p><div class="example">
<pre class="example-preformatted">%\VignetteEngine{knitr::knitr}
</pre></div>
<p>This specifies the name of a package and an engine to use in place of
Sweave in processing the vignette.  As <code class="code">Sweave</code> is the only engine
supplied with the R distribution, the package providing any other
engine must be specified in the &lsquo;<samp class="samp">VignetteBuilder</samp>&rsquo; field of the
package <samp class="file">DESCRIPTION</samp> file, and also specified in the
&lsquo;<samp class="samp">Suggests</samp>&rsquo;, &lsquo;<samp class="samp">Imports</samp>&rsquo; or &lsquo;<samp class="samp">Depends</samp>&rsquo; field (since its
namespace must be available to build or check your package).  If more
than one package is specified as a builder, they will be searched in the
order given there.  The <strong class="strong">utils</strong> package is always implicitly
appended to the list of builder packages, but may be included earlier
to change the search order.
</p>
<p>Note that a package with non-Sweave vignettes should always have a
&lsquo;<samp class="samp">VignetteBuilder</samp>&rsquo; field in the <samp class="file">DESCRIPTION</samp> file, since this
is how <code class="command">R CMD check</code> recognizes that there are vignettes to be
checked: packages listed there are required when the package is checked.
</p>
<p>The vignette engine can produce <samp class="file">.tex</samp>, <samp class="file">.pdf</samp>, or <samp class="file">.html</samp>
files as output.  If it produces <samp class="file">.tex</samp> files, R will
call <code class="code">texi2pdf</code> to convert them to <samp class="file">.pdf</samp> for display
to the user (unless there is a <samp class="file">Makefile</samp> in the <samp class="file">vignettes</samp>
directory).
</p>
<p>Package writers who would like to supply vignette engines need
to register those engines in the package <code class="code">.onLoad</code> function.
For example, that function could make the call
</p><div class="example">
<pre class="example-preformatted">tools::vignetteEngine(&quot;knitr&quot;, weave = vweave, tangle = vtangle,
                      pattern = &quot;[.]Rmd$&quot;, package = &quot;knitr&quot;)
</pre></div>
<p>(The actual registration in <a class="url" href="https://CRAN.R-project.org/package=knitr"><strong class="strong">knitr</strong></a> is more complicated, because
it supports other input formats.)  See the <code class="code">?tools::vignetteEngine</code>
help topic for details on engine registration.
</p>

<hr>
</div>
</div>
<div class="section-level-extent" id="Package-namespaces">
<div class="nav-panel">
<p>
Next: <a href="#Writing-portable-packages" accesskey="n" rel="next">Writing portable packages</a>, Previous: <a href="#Writing-package-vignettes" accesskey="p" rel="prev">Writing package vignettes</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Package-namespaces-1"><span>1.5 Package namespaces<a class="copiable-link" href="#Package-namespaces-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-namespaces"></a>

<p>R has a namespace management system for code in packages.  This
system allows the package writer to specify which variables in the
package should be <em class="emph">exported</em> to make them available to package
users, and which variables should be <em class="emph">imported</em> from other
packages.
</p>
<p>The namespace for a package is specified by the
<samp class="file">NAMESPACE</samp> file in the top level package directory.  This file
contains <em class="emph">namespace directives</em> describing the imports and exports
of the namespace.  Additional directives register any shared objects to
be loaded and any S3-style methods that are provided.  Note that
although the file looks like R code (and often has R-style
comments) it is not processed as R code.  Only very simple
conditional processing of <code class="code">if</code> statements is implemented.
</p>
<p>Packages are loaded and attached to the search path by calling
<code class="code">library</code> or <code class="code">require</code>.  Only the exported variables are
placed in the attached frame.  Loading a package that imports variables
from other packages will cause these other packages to be loaded as well
(unless they have already been loaded), but they will <em class="emph">not</em> be
placed on the search path by these implicit loads.  Thus code in the
package can only depend on objects in its own namespace and its imports
(including the <strong class="strong">base</strong> namespace) being visible<a class="footnote" id="DOCF67" href="#FOOT67"><sup>67</sup></a>.
</p>
<p>Namespaces are <em class="emph">sealed</em> once they are loaded.  Sealing means that
imports and exports cannot be changed and that internal variable
bindings cannot be changed.  Sealing allows a simpler implementation
strategy for the namespace mechanism and allows code analysis and
compilation tools to accurately identify the definition corresponding to
a global variable reference in a function body.
</p>
<p>The namespace controls the search strategy for variables used by
functions in the package.  If not found locally, R searches the
package namespace first, then the imports, then the base namespace and
then the normal search path (so the base namespace precedes the normal
search rather than being at the end of it).
</p>



<ul class="mini-toc">
<li><a href="#Specifying-imports-and-exports" accesskey="1">Specifying imports and exports</a></li>
<li><a href="#Registering-S3-methods" accesskey="2">Registering S3 methods</a></li>
<li><a href="#Load-hooks" accesskey="3">Load hooks</a></li>
<li><a href="#useDynLib" accesskey="4"><code class="code">useDynLib</code></a></li>
<li><a href="#An-example" accesskey="5">An example</a></li>
<li><a href="#Namespaces-with-S4-classes-and-methods" accesskey="6">Namespaces with S4 classes and methods</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Specifying-imports-and-exports">
<div class="nav-panel">
<p>
Next: <a href="#Registering-S3-methods" accesskey="n" rel="next">Registering S3 methods</a>, Previous: <a href="#Package-namespaces" accesskey="p" rel="prev">Package namespaces</a>, Up: <a href="#Package-namespaces" accesskey="u" rel="up">Package namespaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Specifying-imports-and-exports-1"><span>1.5.1 Specifying imports and exports<a class="copiable-link" href="#Specifying-imports-and-exports-1"> &para;</a></span></h4>

<p>Exports are specified using the <code class="code">export</code> directive in the
<samp class="file">NAMESPACE</samp> file.  A directive of the form
</p>
<a class="index-entry-id" id="index-export"></a>
<div class="example">
<pre class="example-preformatted">export(f, g)
</pre></div>

<p>specifies that the variables <code class="code">f</code> and <code class="code">g</code> are to be exported.
(Note that variable names may be quoted, and reserved words and
non-standard names such as <code class="code">[&lt;-.fractions</code> must be.)
</p>
<p>For packages with many variables to export it may be more convenient to
specify the names to export with a regular expression using
<code class="code">exportPattern</code>.  The directive
</p>
<a class="index-entry-id" id="index-exportPattern"></a>
<div class="example">
<pre class="example-preformatted">exportPattern(&quot;^[^.]&quot;)
</pre></div>

<p>exports all variables that do not start with a period.  However, such
broad patterns are not recommended for production code: it is better to
list all exports or use narrowly-defined groups.  (This pattern applies
to S4 classes.)  Beware of patterns which include names starting with a
period: some of these are internal-only variables and should never be
exported, e.g. &lsquo;<samp class="samp">.__S3MethodsTable__.</samp>&rsquo; (and loading excludes known
cases).
</p>
<p>Packages implicitly import the base namespace.
Variables exported from other packages with namespaces need to be
imported explicitly using the directives <code class="code">import</code> and
<code class="code">importFrom</code>.  The <code class="code">import</code> directive imports all exported
variables from the specified package(s).  Thus the directives
</p>
<a class="index-entry-id" id="index-import"></a>
<div class="example">
<pre class="example-preformatted">import(foo, bar)
</pre></div>

<p>specifies that all exported variables in the packages <strong class="strong">foo</strong> and
<strong class="strong">bar</strong> are to be imported.  If only some of the exported variables
from a package are needed, then they can be imported using
<code class="code">importFrom</code>.  The directive
</p>
<a class="index-entry-id" id="index-importFrom"></a>
<div class="example">
<pre class="example-preformatted">importFrom(foo, f, g)
</pre></div>

<p>specifies that the exported variables <code class="code">f</code> and <code class="code">g</code> of the
package <strong class="strong">foo</strong> are to be imported.  Using <code class="code">importFrom</code>
selectively rather than <code class="code">import</code> is good practice and recommended
notably when importing from packages with more than a dozen exports and
especially from those written by others (so what they export can change
in future).
</p>
<p>To import every symbol from a package but for a few exceptions,
pass the <code class="code">except</code> argument to <code class="code">import</code>. The directive
</p>
<div class="example">
<pre class="example-preformatted">import(foo, except=c(bar, baz))
</pre></div>

<p>imports every symbol from <strong class="strong">foo</strong> except <code class="code">bar</code> and
<code class="code">baz</code>. The value of <code class="code">except</code> should evaluate to something
coercible to a character vector, after substituting each symbol for
its corresponding string.
</p>
<p>It is possible to export variables from a namespace which it has
imported from other namespaces: this has to be done explicitly and not
<em class="emph">via</em> <code class="code">exportPattern</code>.
</p>
<p>If a package only needs a few objects from another package it can use a
fully qualified variable reference in the code instead of a formal
import.  A fully-qualified reference to the function <code class="code">f</code> in package
<strong class="strong">foo</strong> is of the form <code class="code">foo::f</code>.  This is slightly less efficient
than a formal import and also loses the advantage of recording all
dependencies in the <samp class="file">NAMESPACE</samp> file (but they still need to be
recorded in the <samp class="file">DESCRIPTION</samp> file).  Evaluating <code class="code">foo::f</code> will
cause package <strong class="strong">foo</strong> to be loaded, but not attached, if it was not
loaded already&mdash;this can be an advantage in delaying the loading of a
rarely used package.  However, if <strong class="strong">foo</strong> is listed only in
&lsquo;<samp class="samp">Suggests</samp>&rsquo; or &lsquo;<samp class="samp">Enhances</samp>&rsquo; this also delays the check that it is
installed: it is good practice to use such imports conditionally (e.g.
<em class="emph">via</em> <code class="code">requireNamespace(&quot;<var class="var">foo</var>&quot;, quietly = TRUE)</code>).
</p>
<p>Using the <code class="code">foo::f</code> form will be necessary when a package needs to
use a function of the same name from more than one namespace.
</p>
<p>Using <code class="code">foo:::f</code> instead of <code class="code">foo::f</code> allows access to
unexported objects.  This is generally not recommended, as the existence
or semantics of unexported objects may be changed by the package author
in routine maintenance.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Registering-S3-methods">
<div class="nav-panel">
<p>
Next: <a href="#Load-hooks" accesskey="n" rel="next">Load hooks</a>, Previous: <a href="#Specifying-imports-and-exports" accesskey="p" rel="prev">Specifying imports and exports</a>, Up: <a href="#Package-namespaces" accesskey="u" rel="up">Package namespaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Registering-S3-methods-1"><span>1.5.2 Registering S3 methods<a class="copiable-link" href="#Registering-S3-methods-1"> &para;</a></span></h4>

<p>The standard method for S3-style <code class="code">UseMethod</code> dispatching might fail
to locate methods defined in a package that is imported but not attached
to the search path.  To ensure that these methods are available the
packages defining the methods should ensure that the generics are
imported and register the methods using <code class="code">S3method</code> directives.  If
a package defines a function <code class="code">print.foo</code> intended to be used as a
<code class="code">print</code> method for class <code class="code">foo</code>, then the directive
</p>
<a class="index-entry-id" id="index-S3method"></a>
<div class="example">
<pre class="example-preformatted">S3method(print, foo)
</pre></div>

<p>ensures that the method is registered and available for <code class="code">UseMethod</code>
dispatch, and the function <code class="code">print.foo</code> does not need to be exported.
Since the generic <code class="code">print</code> is defined in <strong class="strong">base</strong> it does not need
to be imported explicitly.
</p>
<p>(Note that function and class names may be quoted, and reserved words
and non-standard names such as <code class="code">[&lt;-</code> and <code class="code">function</code> must
be.)
</p>
<p>It is possible to specify a third argument to S3method, the function to
be used as the method, for example
</p>
<div class="example">
<pre class="example-preformatted">S3method(print, check_so_symbols, .print.via.format)
</pre></div>

<p>when <code class="code">print.check_so_symbols</code> is not needed.
</p>
<p>As from R 3.6.0 one can also use <code class="code">S3method()</code> directives to
perform <em class="emph">delayed</em> registration.  With
</p><div class="example">
<pre class="example-preformatted">if(getRversion() &gt;= &quot;3.6.0&quot;) {
    S3method(pkg::gen, cls)
}
</pre></div>
<p>function <code class="code">gen.cls</code> will get registered as an S3 method for class
<code class="code">cls</code> and generic <code class="code">gen</code> from package <code class="code">pkg</code> only when the
namespace of <code class="code">pkg</code> is loaded.  This can be employed to deal with
situations where the method is not &ldquo;immediately&rdquo; needed, and having to
pre-load the namespace of <code class="code">pkg</code> (and all its strong dependencies)
in order to perform immediate registration is considered too onerous.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Load-hooks">
<div class="nav-panel">
<p>
Next: <a href="#useDynLib" accesskey="n" rel="next"><code class="code">useDynLib</code></a>, Previous: <a href="#Registering-S3-methods" accesskey="p" rel="prev">Registering S3 methods</a>, Up: <a href="#Package-namespaces" accesskey="u" rel="up">Package namespaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Load-hooks-1"><span>1.5.3 Load hooks<a class="copiable-link" href="#Load-hooks-1"> &para;</a></span></h4>

<a class="index-entry-id" id="index-_002eonLoad"></a>
<a class="index-entry-id" id="index-_002eonAttach"></a>
<p>There are a number of hooks called as packages are loaded, attached,
detached, and unloaded.  See <code class="code">help(&quot;.onLoad&quot;)</code> for more details.
</p>
<p>Since loading and attaching are distinct operations, separate hooks are
provided for each.  These hook functions are called <code class="code">.onLoad</code> and
<code class="code">.onAttach</code>.  They both take arguments<a class="footnote" id="DOCF68" href="#FOOT68"><sup>68</sup></a> <code class="code">libname</code> and
<code class="code">pkgname</code>; they should be defined in the namespace but not
exported.
</p>
<a class="index-entry-id" id="index-_002eonUnload"></a>
<a class="index-entry-id" id="index-_002eonDetach"></a>
<a class="index-entry-id" id="index-_002eLast_002elib"></a>
<p>Packages can use a <code class="code">.onDetach</code> or <code class="code">.Last.lib</code> function
(provided the latter is exported from the namespace) when <code class="code">detach</code>
is called on the package.  It is called with a single argument, the full
path to the installed package.  There is also a hook <code class="code">.onUnload</code>
which is called when the namespace is unloaded (<em class="emph">via</em> a call to
<code class="code">unloadNamespace</code>, perhaps called by <code class="code">detach(unload = TRUE)</code>)
with argument the full path to the installed package&rsquo;s directory.
Functions <code class="code">.onUnload</code> and <code class="code">.onDetach</code> should be defined in the
namespace and not exported, but <code class="code">.Last.lib</code> does need to be
exported.
</p>
<p>Packages are not likely to need <code class="code">.onAttach</code> (except perhaps for a
start-up banner); code to set options and load shared objects should be
placed in a <code class="code">.onLoad</code> function, or use made of the <code class="code">useDynLib</code>
directive described next.
</p>
<p>User-level hooks are also available: see the help on function
<code class="code">setHook</code>.
</p>
<p>These hooks are often used incorrectly.  People forget to export
<code class="code">.Last.lib</code>.   Compiled code should be loaded in <code class="code">.onLoad</code> (or
<em class="emph">via</em> a <code class="code">useDynLb</code> directive: see below) and unloaded in
<code class="code">.onUnload</code>.  Do remember that a package&rsquo;s namespace can be loaded
without the namespace being attached (e.g. by <code class="code">pkgname::fun</code>) and
that a package can be detached and re-attached whilst its namespace
remains loaded.
</p>
<p>It is good practice for these functions to be quiet.  Any messages
should use <code class="code">packageStartupMessage</code> so users (include check scripts)
can suppress them if desired.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="useDynLib">
<div class="nav-panel">
<p>
Next: <a href="#An-example" accesskey="n" rel="next">An example</a>, Previous: <a href="#Load-hooks" accesskey="p" rel="prev">Load hooks</a>, Up: <a href="#Package-namespaces" accesskey="u" rel="up">Package namespaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="useDynLib-1"><span>1.5.4 <code class="code">useDynLib</code><a class="copiable-link" href="#useDynLib-1"> &para;</a></span></h4>

<p>A <samp class="file">NAMESPACE</samp> file can contain one or more <code class="code">useDynLib</code>
directives which allows shared objects that need to be
loaded.<a class="footnote" id="DOCF69" href="#FOOT69"><sup>69</sup></a>  The directive
</p>
<a class="index-entry-id" id="index-useDynLib"></a>
<div class="example">
<pre class="example-preformatted">useDynLib(foo)
</pre></div>

<p>registers the shared object <code class="code">foo</code><a class="footnote" id="DOCF70" href="#FOOT70"><sup>70</sup></a> for loading with <code class="code">library.dynam</code>.
Loading of registered object(s) occurs after the package code has been
loaded and before running the load hook function.  Packages that would
only need a load hook function to load a shared object can use the
<code class="code">useDynLib</code> directive instead.
</p>
<p>The <code class="code">useDynLib</code> directive also accepts the names of the native
routines that are to be used in R <em class="emph">via</em> the <code class="code">.C</code>, <code class="code">.Call</code>,
<code class="code">.Fortran</code> and <code class="code">.External</code> interface functions.  These are given as
additional arguments to the directive, for example,
</p>
<div class="example">
<pre class="example-preformatted">useDynLib(foo, myRoutine, myOtherRoutine)
</pre></div>

<p>By specifying these names in the <code class="code">useDynLib</code> directive, the native
symbols are resolved when the package is loaded and R variables
identifying these symbols are added to the package&rsquo;s namespace with
these names.  These can be used in the <code class="code">.C</code>, <code class="code">.Call</code>,
<code class="code">.Fortran</code> and <code class="code">.External</code> calls in place of the name of the
routine and the <code class="code">PACKAGE</code> argument.  For instance, we can call the
routine <code class="code">myRoutine</code> from R with the code
</p>
<div class="example">
<pre class="example-preformatted"> .Call(myRoutine, x, y)
</pre></div>

<p>rather than
</p>
<div class="example">
<pre class="example-preformatted"> .Call(&quot;myRoutine&quot;, x, y, PACKAGE = &quot;foo&quot;)
</pre></div>

<p>There are at least two benefits to this approach.  Firstly, the symbol
lookup is done just once for each symbol rather than each time the
routine is invoked.  Secondly, this removes any ambiguity in resolving
symbols that might be present in more than one DLL.  However, this
approach is nowadays deprecated in favour of supplying registration
information (see below).
</p>
<p>In some circumstances, there will already be an R variable in the
package with the same name as a native symbol. For example, we may have
an R function in the package named <code class="code">myRoutine</code>.  In this case,
it is necessary to map the native symbol to a different R variable
name. This can be done in the <code class="code">useDynLib</code> directive by using named
arguments. For instance, to map the native symbol name <code class="code">myRoutine</code>
to the R variable <code class="code">myRoutine_sym</code>, we would use
</p>
<div class="example">
<pre class="example-preformatted">useDynLib(foo, myRoutine_sym = myRoutine, myOtherRoutine)
</pre></div>

<p>We could then call that routine from R using the command
</p>
<div class="example">
<pre class="example-preformatted"> .Call(myRoutine_sym, x, y)
</pre></div>

<p>Symbols without explicit names are assigned to the R variable with
that name.
</p>
<p>In some cases, it may be preferable not to create R variables in the
package&rsquo;s namespace that identify the native routines.  It may be too
costly to compute these for many routines when the package is loaded
if many of these routines are not likely to be used.  In this case,
one can still perform the symbol resolution correctly using the DLL,
but do this each time the routine is called.  Given a reference to the
DLL as an R variable, say <code class="code">dll</code>, we can call the routine
<code class="code">myRoutine</code> using the expression
</p>
<div class="example">
<pre class="example-preformatted"> .Call(dll$myRoutine, x, y)
</pre></div>

<p>The <code class="code">$</code> operator resolves the routine with the given name in the
DLL using a call to <code class="code">getNativeSymbol</code>.  This is the same
computation as above where we resolve the symbol when the package is
loaded. The only difference is that this is done each time in the case
of <code class="code">dll$myRoutine</code>.
</p>
<p>In order to use this dynamic approach (e.g., <code class="code">dll$myRoutine</code>), one
needs the reference to the DLL as an R variable in the package.  The
DLL can be assigned to a variable by using the <code class="code">variable =
dllName</code> format used above for mapping symbols to R variables.  For
example, if we wanted to assign the DLL reference for the DLL
<code class="code">foo</code> in the example above to the variable <code class="code">myDLL</code>, we would
use the following directive in the <samp class="file">NAMESPACE</samp> file:
</p>
<div class="example">
<pre class="example-preformatted">myDLL = useDynLib(foo, myRoutine_sym = myRoutine, myOtherRoutine)
</pre></div>

<p>Then, the R variable <code class="code">myDLL</code> is in the package&rsquo;s namespace and
available for calls such as <code class="code">myDLL$dynRoutine</code> to access routines
that are not explicitly resolved at load time.
</p>
<p>If the package has registration information (see <a class="ref" href="#Registering-native-routines">Registering native routines</a>), then we can use that directly rather than specifying the
list of symbols again in the <code class="code">useDynLib</code> directive in the
<samp class="file">NAMESPACE</samp> file.  Each routine in the registration information is
specified by giving a name by which the routine is to be specified along
with the address of the routine and any information about the number and
type of the parameters.  Using the <code class="code">.registration</code> argument of
<code class="code">useDynLib</code>, we can instruct the namespace mechanism to create
R variables for these symbols.  For example, suppose we have the
following registration information for a DLL named <code class="code">myDLL</code>:
</p>
<div class="example">
<pre class="example-preformatted">static R_NativePrimitiveArgType foo_t[] = {
    REALSXP, INTSXP, STRSXP, LGLSXP
};

static const R_CMethodDef cMethods[] = {
   {&quot;foo&quot;, (DL_FUNC) &amp;foo, 4, foo_t},
   {&quot;bar_sym&quot;, (DL_FUNC) &amp;bar, 0},
   {NULL, NULL, 0, NULL}
};

static const R_CallMethodDef callMethods[] = {
   {&quot;R_call_sym&quot;, (DL_FUNC) &amp;R_call, 4},
   {&quot;R_version_sym&quot;, (DL_FUNC) &amp;R_version, 0},
   {NULL, NULL, 0}
};
</pre></div>

<p>Then, the directive in the <samp class="file">NAMESPACE</samp> file
</p>
<div class="example">
<pre class="example-preformatted">useDynLib(myDLL, .registration = TRUE)
</pre></div>

<p>causes the DLL to be loaded and also for the R variables <code class="code">foo</code>,
<code class="code">bar_sym</code>, <code class="code">R_call_sym</code> and <code class="code">R_version_sym</code> to be
defined in the package&rsquo;s namespace.
</p>
<p>Note that the names for the R variables are taken from the entry in
the registration information and do not need to be the same as the name
of the native routine.  This allows the creator of the registration
information to map the native symbols to non-conflicting variable names
in R, e.g. <code class="code">R_version</code> to <code class="code">R_version_sym</code> for use in an
R function such as
</p>
<div class="example">
<pre class="example-preformatted">R_version &lt;- function()
{
  .Call(R_version_sym)
}
</pre></div>

<p>Using argument <code class="code">.fixes</code> allows an automatic prefix to be added to
the registered symbols, which can be useful when working with an
existing package.  For example, package <a class="url" href="https://CRAN.R-project.org/package=KernSmooth"><strong class="strong">KernSmooth</strong></a> has
</p>
<div class="example">
<pre class="example-preformatted">useDynLib(KernSmooth, .registration = TRUE, .fixes = &quot;F_&quot;)
</pre></div>

<p>which makes the R variables corresponding to the Fortran symbols
<code class="code">F_bkde</code> and so on, and so avoid clashes with R code in the
namespace.
</p>
<p><strong class="strong">NB</strong>: Using these arguments for a package which does not register
native symbols merely slows down the package loading (although many
<abbr class="acronym">CRAN</abbr> packages have done so).  Once symbols are registered,
check that the corresponding R variables are not accidentally
exported by a pattern in the <samp class="file">NAMESPACE</samp> file.
</p>

<hr>
</div>
<div class="subsection-level-extent" id="An-example">
<div class="nav-panel">
<p>
Next: <a href="#Namespaces-with-S4-classes-and-methods" accesskey="n" rel="next">Namespaces with S4 classes and methods</a>, Previous: <a href="#useDynLib" accesskey="p" rel="prev"><code class="code">useDynLib</code></a>, Up: <a href="#Package-namespaces" accesskey="u" rel="up">Package namespaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="An-example-1"><span>1.5.5 An example<a class="copiable-link" href="#An-example-1"> &para;</a></span></h4>

<p>As an example consider two packages named <strong class="strong">foo</strong> and <strong class="strong">bar</strong>.  The
R code for package <strong class="strong">foo</strong> in file <samp class="file">foo.R</samp> is
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">x &lt;- 1
f &lt;- function(y) c(x,y)
foo &lt;- function(x) .Call(&quot;foo&quot;, x, PACKAGE=&quot;foo&quot;)
print.foo &lt;- function(x, ...) cat(&quot;&lt;a foo&gt;\n&quot;)
</pre></div>
</td></tr></table>
</blockquote>

<p>Some C code defines a C function compiled into DLL <code class="code">foo</code> (with an
appropriate extension).  The <samp class="file">NAMESPACE</samp> file for this package is
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">useDynLib(foo)
export(f, foo)
S3method(print, foo)
</pre></div>
</td></tr></table>
</blockquote>

<p>The second package <strong class="strong">bar</strong> has code file <samp class="file">bar.R</samp>
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">c &lt;- function(...) sum(...)
g &lt;- function(y) f(c(y, 7))
h &lt;- function(y) y+9
</pre></div>
</td></tr></table>
</blockquote>

<p>and <samp class="file">NAMESPACE</samp> file
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">import(foo)
export(g, h)
</pre></div>
</td></tr></table>
</blockquote>

<p>Calling <code class="code">library(bar)</code> loads <strong class="strong">bar</strong> and attaches its exports to
the search path.  Package <strong class="strong">foo</strong> is also loaded but not attached to
the search path.  A call to <code class="code">g</code> produces
</p>
<div class="example">
<pre class="example-preformatted">&gt; g(6)
[1]  1 13
</pre></div>

<p>This is consistent with the definitions of <code class="code">c</code> in the two settings:
in <strong class="strong">bar</strong> the function <code class="code">c</code> is defined to be equivalent to
<code class="code">sum</code>, but in <strong class="strong">foo</strong> the variable <code class="code">c</code> refers to the
standard function <code class="code">c</code> in <strong class="strong">base</strong>.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Namespaces-with-S4-classes-and-methods">
<div class="nav-panel">
<p>
Previous: <a href="#An-example" accesskey="p" rel="prev">An example</a>, Up: <a href="#Package-namespaces" accesskey="u" rel="up">Package namespaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Namespaces-with-S4-classes-and-methods-1"><span>1.5.6 Namespaces with S4 classes and methods<a class="copiable-link" href="#Namespaces-with-S4-classes-and-methods-1"> &para;</a></span></h4>

<p>Some additional steps are needed for packages which make use of formal
(S4-style) classes and methods (unless these are purely used
internally).  The package should have
<code class="code">Depends: methods</code><a class="footnote" id="DOCF71" href="#FOOT71"><sup>71</sup></a> in its <samp class="file">DESCRIPTION</samp> and <code class="code">import(methods)</code> or
<code class="code">importFrom(methods, ...)</code> plus any classes and methods which are
to be exported need to be declared in the <samp class="file">NAMESPACE</samp> file.  For
example, the <strong class="strong">stats4</strong> package has
</p>
<a class="index-entry-id" id="index-exportClasses"></a>
<a class="index-entry-id" id="index-exportMethods"></a>

<div class="example">
<pre class="example-preformatted">export(mle) # exporting methods implicitly exports the generic
importFrom(&quot;stats&quot;, approx, optim, pchisq, predict, qchisq, qnorm, spline)
## For these, we define methods or (AIC, BIC, nobs) an implicit generic:
importFrom(&quot;stats&quot;, AIC, BIC, coef, confint, logLik, nobs, profile,
           update, vcov)
exportClasses(mle, profile.mle, summary.mle)
## All methods for imported generics:
exportMethods(coef, confint, logLik, plot, profile, summary,
              show, update, vcov)
## implicit generics which do not have any methods here
export(AIC, BIC, nobs)
</pre></div>

<a class="index-entry-id" id="index-exportPattern-1"></a>
<a class="index-entry-id" id="index-exportClassPattern"></a>
<p>All S4 classes to be used outside the package need to be listed in an
<code class="code">exportClasses</code> directive. Alternatively, they can be specified
using <code class="code">exportClassPattern</code><a class="footnote" id="DOCF72" href="#FOOT72"><sup>72</sup></a> in the same style as
for <code class="code">exportPattern</code>.  To export methods for generics from other
packages an <code class="code">exportMethods</code> directive can be used.
</p>
<p>Note that exporting methods on a generic in the namespace will also
export the generic, and exporting a generic in the namespace will also
export its methods.  If the generic function is not local to this
package, either because it was imported as a generic function or because
the non-generic version has been made generic solely to add S4 methods
to it (as for functions such as <code class="code">coef</code> in the example above), it
can be declared <em class="emph">via</em> either or both of <code class="code">export</code> or
<code class="code">exportMethods</code>, but the latter is clearer (and is used in the
<strong class="strong">stats4</strong> example above).  In particular, for primitive functions
there is no generic function, so <code class="code">export</code> would export the
primitive, which makes no sense.  On the other hand, if the generic is
local to this package, it is more natural to export the function itself
using <code class="code">export()</code>, and this <em class="emph">must</em> be done if an implicit
generic is created without setting any methods for it (as is the case
for <code class="code">AIC</code> in <strong class="strong">stats4</strong>).
</p>
<p>A non-local generic function is only exported to ensure that calls to
the function will dispatch the methods from this package (and that is
not done or required when the methods are for primitive functions).  For
this reason, you do not need to document such implicitly created generic
functions, and <code class="code">undoc</code> in package <strong class="strong">tools</strong> will not report them.
</p>
<p>If a package uses S4 classes and methods exported from another package,
but does not import the entire namespace of the other
package<a class="footnote" id="DOCF73" href="#FOOT73"><sup>73</sup></a>, it needs
to import the classes and methods explicitly, with directives
</p>
<a class="index-entry-id" id="index-importClassesFrom"></a>
<a class="index-entry-id" id="index-importMethodsFrom"></a>

<div class="example">
<pre class="example-preformatted">importClassesFrom(package, ...)
importMethodsFrom(package, ...)
</pre></div>

<p>listing the classes and functions with methods respectively.  Suppose we
had two small packages <strong class="strong">A</strong> and <strong class="strong">B</strong> with <strong class="strong">B</strong> using <strong class="strong">A</strong>.
Then they could have <code class="code">NAMESPACE</code> files
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">export(f1, ng1)
exportMethods(&quot;[&quot;)
exportClasses(c1)
</pre></div>
</td></tr></table>
</blockquote>

<p>and
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">importFrom(A, ng1)
importClassesFrom(A, c1)
importMethodsFrom(A, f1)
export(f4, f5)
exportMethods(f6, &quot;[&quot;)
exportClasses(c1, c2)
</pre></div>
</td></tr></table>
</blockquote>

<p>respectively.
</p>
<p>Note that <code class="code">importMethodsFrom</code> will also import any generics defined
in the namespace on those methods.
</p>
<p>It is important if you export S4 methods that the corresponding generics
are available.  You may for example need to import <code class="code">coef</code> from
<strong class="strong">stats</strong> to make visible a function to be converted into its
implicit generic.  But it is better practice to make use of the generics
exported by <strong class="strong">stats4</strong> as this enables multiple packages to
unambiguously set methods on those generics.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Writing-portable-packages">
<div class="nav-panel">
<p>
Next: <a href="#Diagnostic-messages" accesskey="n" rel="next">Diagnostic messages</a>, Previous: <a href="#Package-namespaces" accesskey="p" rel="prev">Package namespaces</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Writing-portable-packages-1"><span>1.6 Writing portable packages<a class="copiable-link" href="#Writing-portable-packages-1"> &para;</a></span></h3>

<p>This section contains advice on writing packages to be used on multiple
platforms or for distribution (for example to be submitted to a package
repository such as <abbr class="acronym">CRAN</abbr>).
</p>

<p>Portable packages should have simple file names: use only alphanumeric
<abbr class="acronym">ASCII</abbr> characters and period (<code class="code">.</code>), and avoid those names
not allowed under Windows (see <a class="pxref" href="#Package-structure">Package structure</a>).
</p>
<p>Many of the graphics devices are platform-specific: even <code class="code">X11()</code>
(aka <code class="code">x11()</code>) which although emulated on Windows may not be
available on a Unix-alike (and is not the preferred screen device on OS
X).  It is rarely necessary for package code or examples to open a new
device, but if essential,<a class="footnote" id="DOCF74" href="#FOOT74"><sup>74</sup></a> use <code class="code">dev.new()</code>.
</p>
<p>Use <code class="command">R CMD build</code> to make the release <samp class="file">.tar.gz</samp> file.
</p>
<p><code class="command">R CMD check</code> provides a basic set of checks, but often further
problems emerge when people try to install and use packages submitted to
<abbr class="acronym">CRAN</abbr> &ndash; many of these involve compiled code.  Here are some
further checks that you can do to make your package more portable.
</p>
<ul class="itemize mark-bullet">
<li>If your package has a <samp class="file">configure</samp> script, provide a
<samp class="file">configure.win</samp> or <samp class="file">configure.ucrt</samp> script to be used on Windows (an
empty <samp class="file">configure.win</samp> file if no actions are needed).

</li><li>If your package has a <samp class="file">Makevars</samp> or <samp class="file">Makefile</samp> file, make sure
that you use only portable make features.  Such files should be
<abbr class="abbr">LF</abbr>-terminated<a class="footnote" id="DOCF75" href="#FOOT75"><sup>75</sup></a> (including the final
line of the file) and not make use of GNU extensions.  (The POSIX
specification is available at
<a class="uref" href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/make.html">https://pubs.opengroup.org/onlinepubs/9699919799/utilities/make.html</a>;
anything not documented there should be regarded as an extension to be
avoided.  Further advice can be found at
<a class="uref" href="https://www.gnu.org/software/autoconf/manual/autoconf.html#Portable-Make">https://www.gnu.org/software/autoconf/manual/autoconf.html#Portable-Make</a>.                                )
Commonly misused GNU extensions are conditional inclusions (<code class="code">ifeq</code>
and the like), <code class="code">${shell ...}</code>, <code class="code">${wildcard ...}</code> and
similar, and the use of <code class="code">+=</code><a class="footnote" id="DOCF76" href="#FOOT76"><sup>76</sup></a> and <code class="code">:=</code>.  Also, the use of <code class="code">$&lt;</code> other
than in implicit rules is a GNU extension, as is the <code class="code">$^</code> macro.
As is the use of  <code class="code">.PHONY</code> (some other makes ignore it).
Unfortunately makefiles which use GNU extensions often run on other
platforms but do not have the intended results.

<p>Note that the <samp class="option">-C</samp> flag for <code class="command">make</code> is not included in the
POSIX specification and is not implemented by some of the
<code class="command">make</code>s which have been used with R.  However, it is more
commonly implemented (e.g. by FreeBSD <code class="command">make</code>) than the GNU-specific
<samp class="option">--directory=</samp>.
</p>
<p>You should not rely on built-in/default <code class="command">make</code> rules, even when
specified by POSIX, as some <code class="command">make</code>s do not have the POSIX ones
and others have altered them.
</p>
<p>The use of <code class="code">${shell ...}</code> can be avoided by using backticks, e.g.
</p>
<div class="example">
<pre class="example-preformatted">PKG_CPPFLAGS = `gsl-config --cflags`
</pre></div>

<p>which works in all versions of <code class="command">make</code> known<a class="footnote" id="DOCF77" href="#FOOT77"><sup>77</sup></a> to be
used with R.
</p>
<p>If you really must require GNU make, declare it in the <samp class="file">DESCRIPTION</samp>
file by
</p>
<div class="example">
<pre class="example-preformatted">SystemRequirements: GNU make
</pre></div>

<p>and ensure that you use the value of environment variable <code class="env">MAKE</code>
(and not just <code class="command">make</code>) in your scripts.  (On some platforms GNU
make is available under a name such as <code class="command">gmake</code>, and there
<code class="code">SystemRequirements</code> is used to set <code class="env">MAKE</code>.)
</p>
<p>If you only need GNU make for parts of the package which are rarely
needed (for example to create bibliography files under
<samp class="file">vignettes</samp>), use a file called <samp class="file">GNUmakefile</samp> rather than
<samp class="file">Makefile</samp> as GNU make (only) will use the former.
</p>
<p>macOS has used GNU make for many years (it previously used BSD make),
but the version has been frozen at 3.81 (from 2006).
</p>
<p>Since the only viable make for Windows is GNU make, it is permissible to
use GNU extensions in files <samp class="file">Makevars.win</samp>, <samp class="file">Makevars.ucrt</samp>,
<samp class="file">Makefile.win</samp> or <samp class="file">Makefile.ucrt</samp>.
</p>
</li><li>If you use <samp class="file">src/Makevars</samp> to compile code in a subdirectory,
ensure that you have followed all the advice above.  In particular
<ul class="itemize mark-bullet">
<li>Anticipate a parallel <code class="command">make</code>.  See <a class="xref" href="#Using-Makevars">Using <samp class="file">Makevars</samp></a>.

</li><li>Pass macros down to the makefile in the subdirectory, including
<strong class="strong">all</strong> the needed compiler flags (including PIC and visibility
flags).  If they are used (even by a default rule) in the subdirectory&rsquo;s
Makefile, this includes macros &lsquo;<samp class="samp">AR</samp>&rsquo; and &lsquo;<samp class="samp">RANLIB</samp>&rsquo;.
See <a class="xref" href="#Compiling-in-sub_002ddirectories">Compiling in sub-directories</a>, which has a C example.  A C++
example:

<div class="example">
<pre class="example-preformatted">pkg/libpkg.a:
        (cd pkg &amp;&amp; $(MAKE) -f make_pkg libpkg.a \
         CXX=&quot;$(CXX)&quot; CXXFLAGS=&quot;$(CXXFLAGS) $(CXXPICFLAGS) $(C_VISIBILITY)&quot; \
         AR=&quot;$(AR)&quot; RANLIB=&quot;$(RANLIB)&quot;)
</pre></div>

</li><li>Ensure that cleanup will be performed by <code class="command">R CMD build</code>, for
example in a <code class="code">cleanup</code> script or a &lsquo;<samp class="samp">clean</samp>&rsquo; target.
</li></ul>

</li><li>If your package uses a <samp class="file">src/Makefile</samp> file to compile code to be
linked into R, ensure that it uses exactly the same compiler and flag
settings that R uses when compiling such code: people often forget
&lsquo;<samp class="samp">PIC</samp>&rsquo; flags.  If <code class="code">R CMD config</code> is used, this needs something
like (for C++)

<div class="example">
<pre class="example-preformatted">RBIN = `&quot;${R_HOME}/bin/R&quot;`
CXX = `&quot;${RBIN}&quot; CMD config CXX`
CXXFLAGS = `&quot;${RBIN}&quot; CMD config CXXFLAGS` `&quot;${RBIN}&quot; CMD config CXXPICFLAGS`
</pre></div>

</li><li>Names of source files including <samp class="file">=</samp> (such as
<samp class="file">src/complex_Sig=gen.c</samp>) will confuse some <code class="command">make</code> programs
and should be avoided.

</li><li>Bash extensions also need to be avoided in shell scripts, including
expressions in Makefiles (which are passed to the shell for processing).
Some R platforms use strict<a class="footnote" id="DOCF78" href="#FOOT78"><sup>78</sup></a>
Bourne shells: an earlier R toolset on Windows<a class="footnote" id="DOCF79" href="#FOOT79"><sup>79</sup></a> and some Unix-alike OSes use
<code class="command">ash</code> (<a class="uref" href="https://en.wikipedia.org/wiki/Almquist_shell">https://en.wikipedia.org/wiki/Almquist_shell</a>,
a &lsquo;lightweight shell with few builtins) or derivatives such as <code class="command">dash</code>.
Beware of assuming that all the POSIX command-line utilities are
available, especially on Windows where only a subset (which has changed
by version of <samp class="file">Rtools</samp>) is provided for use with R.  One
particular issue is the use of <code class="command">echo</code>, for which two behaviours
are allowed
(<a class="uref" href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html">https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html</a>)
and both have occurred as defaults on R platforms: portable
applications should use neither <samp class="option">-n</samp> (as the first argument) nor
escape sequences.  The recommended replacement for <code class="command">echo -n</code> is
the command <code class="command">printf</code>.  Another common issue is the construction
<div class="example">
<pre class="example-preformatted">export FOO=value
</pre></div>
<p>which is <code class="command">bash</code>-specific (first set the variable then export it
by name).
</p>
<p>Using <code class="code">test -e</code> (or <code class="code">[ -e ]</code>) in shell scripts is not fully
portable<a class="footnote" id="DOCF80" href="#FOOT80"><sup>80</sup></a>: <code class="code">-f</code> is normally what is intended.  Flags
<samp class="option">-a</samp> and <samp class="option">-o</samp> are nowadays declared obsolescent by POSIX
and should not be used.
</p>
<p>Use of &lsquo;brace expansion&rsquo;, e.g.,
</p><div class="example">
<pre class="example-preformatted">rm -f src/*.{o,so,d}
</pre></div>
<p>is not portable.
</p>
<p>The <samp class="option">-o</samp> flag for <code class="command">set</code> in shell scripts is optional in
POSIX and not supported on all the platforms R is used on.
</p>
<p>The variable &lsquo;<samp class="samp">OSTYPE</samp>&rsquo; is shell-specific and its values are
rather unpredictable and may include a version such as
&lsquo;<samp class="samp">darwin19.0</samp>&rsquo;: <code class="command">`uname`</code> is often what is intended (with
common values &lsquo;<samp class="samp">Darwin</samp>&rsquo;, &lsquo;<samp class="samp">Linux</samp>&rsquo; and &lsquo;<samp class="samp">SunOS</samp>&rsquo;).
</p>
<p>On macOS which shell <samp class="file">/bin/sh</samp> invokes is user- and
platform-dependent: it might be <code class="command">bash</code> version 3.2,
<code class="command">dash</code> or <code class="command">zsh</code> (for new accounts it is <code class="command">zsh</code>,
for accounts ported from Mojave or earlier it is usually
<code class="command">bash</code>).
</p>
</li><li>R is not built by default as a shared library on non-Windows
platforms (although it commonly is on macOS to support the GUI), so
there need not be a file <samp class="file">libR.so</samp> nor <samp class="file">libR.dylib</samp>.  Users of
<code class="command">cmake</code> or <code class="command">rust</code> have all too frequently assumed
otherwise, so do ensure your package is checked under a vanilla R build.
See <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Configuration-options">Configuration options</a> in <cite class="cite">R Installation and Administration</cite>.

</li><li>Make use of the abilities of your compilers to check the
standards-conformance of your code.  For example, <code class="command">gcc</code>,
<code class="command">clang</code> and
<code class="command">gfortran</code><a class="footnote" id="DOCF81" href="#FOOT81"><sup>81</sup></a>  can be used with options <samp class="option">-Wall -pedantic</samp> to alert
you to potential problems.  This is particularly important for C++,
where <code class="code">g++ -Wall -pedantic</code> will alert you to the use of some of
the GNU extensions which fail to compile on most other C++ compilers. If
R was not configured accordingly, one can achieve this <em class="emph">via</em>
personal <samp class="file">Makevars</samp> files.
See <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Customizing-package-compilation">Customizing package compilation</a> in <cite class="cite">R Installation and Administration</cite>,

<p>Portable C++ code needs to follow all of the 2011, 2014 and 2017
standards (including not using deprecated/removed features) or to
specify C+11/14/17/20/23 where available (which is not the case on all
R platforms).  Currently C++20 support is patchy across R
platforms.
</p>
<p>If using Fortran with the GNU compiler, use the flags <samp class="option">-std=f95
-Wall -pedantic</samp> which reject most GNU extensions and features from
later standards.  (Although R only requires Fortran 90,
<code class="command">gfortran</code> does not have a way to specify that standard.)  Also
consider <samp class="option">-std=f2008</samp> as some recent compilers have Fortran 2008
or even 2018 as the minimum supported standard.
</p>
<p>As from macOS 11 (late 2020), its C compiler sets the flag
<samp class="option">-Werror=implicit-function-declaration</samp> by default which forces
stricter conformance to C99.  This can be used on other platforms with
<code class="command">gcc</code> or <code class="command">clang</code>.  If your package has a
(<code class="command">autoconf</code>-generated) <code class="command">configure script</code>, try
installing it whilst using this flag, and read through the
<samp class="file">config.log</samp> file &mdash; compilation warnings and errors can lead to
features which are present not being detected.  (If possible do this on
several platforms.)
</p>
</li><li><code class="command">R CMD check</code> performs some checks for non-portable
compiler/linker flags in <samp class="file">src/Makevars</samp>.  However, it cannot check
the meaning of such flags, and some are commonly accepted but with
compiler-specific meanings.  There are other non-portable flags which
are not checked, nor are <samp class="file">src/Makefile</samp> files and makefiles in
sub-directories.  As a comment in the code says

<blockquote class="quotation">
<p>It is hard to think of anything apart from <samp class="option">-I*</samp> and <samp class="option">-D*</samp>
that is safe for general use &hellip;
</p></blockquote>

<p>although <samp class="option">-pthread</samp> is pretty close to portable.  (Option
<samp class="option">-U</samp> is portable but little use on the command line as it will
only cancel built-in defines (not portable) and those defined earlier on
the command line (R does not use any).)
</p>
<p>The GNU option <samp class="option">-pipe</samp> used to be widely accepted by
C/C++/Fortran compilers, but has been removed in
<code class="command">flang-new</code>&nbsp;18<!-- /@w -->.  In any case, it should not be used in
distributed code as it may lead to excessive memory use.
</p>
<p>People have used <code class="command">configure</code> to customize <samp class="file">src/Makevars</samp>,
including for specific compilers.  This is unsafe for several reasons.
First, unintended compilers might meet the check&mdash;for example, several
compilers other than GCC identify themselves as &lsquo;GCC&rsquo; whilst being only
partially conformant.  Second, future versions of compilers may behave
differently (including updates to quite old series) so for example
<samp class="option">-Werror</samp> (and specializations) can make a package
non-installable under a future version.  Third, using flags to suppress
diagnostic messages can hide important information for debugging on a
platform not tested by the package maintainer.  (<code class="command">R CMD check</code>
can optionally report on unsafe flags which were used.)
</p>
<p>Avoid the use of <samp class="option">-march</samp> and especially <samp class="option">-march=native</samp>.
This allows the compiler to generate code that will only run on a
particular class of CPUs (that of the compiling machine for
&lsquo;<samp class="samp">native</samp>&rsquo;).  People assume this is a &lsquo;minimum&rsquo; CPU specification,
but that is not how it is documented for <code class="command">gcc</code> (it is accepted
by <code class="command">clang</code> but apparently it is undocumented what precisely it
does, and it can be accepted and may be ignored for other compilers).
(For personal use <samp class="option">-mtune</samp> is safer, but still not portable
enough to be used in a public package.)  Not even <code class="command">gcc</code> supports
&lsquo;<samp class="samp">native</samp>&rsquo; for all CPUs, and it can do surprising things if it finds
a CPU released later than its version.
</p>
</li><li>Do be very careful with passing arguments between R, C and Fortran
code.  In particular, <code class="code">long</code> in C will be 32-bit on some R
platforms (including 64-bit Windows), but 64-bit on most modern Unix and
Linux platforms.  It is rather unlikely that the use of <code class="code">long</code> in C
code has been thought through: if you need a longer type than <code class="code">int</code>
you should use a configure test for a C99/C++11 type such as
<code class="code">int_fast64_t</code> (and failing that, <code class="code">long long</code>) and typedef
your own type, or use another suitable type (such as <code class="code">size_t</code>, but
beware that is unsigned and <code class="code">ssize_t</code> is not portable).

<p>It is not safe to assume that <code class="code">long</code> and pointer types are the same
size, and they are not on 64-bit Windows.  If you need to convert
pointers to and from integers use the C99/C++11 integer types
<code class="code">intptr_t</code> and <code class="code">uintptr_t</code> (in the headers <code class="code">&lt;stdint.h&gt;</code>
and <code class="code">&lt;cstdint&gt;</code>: they are not required to be implemented by the
standards but are used in C code by R itself).
</p>
<p>Note that <code class="code">integer</code> in Fortran corresponds to <code class="code">int</code> in C on
all R platforms.  There is no such guarantee for Fortran
<code class="code">logical</code>, and recent <code class="command">gfortran</code> maps it to
<code class="code">int_least32_t</code> on most platforms.
</p>
</li><li>Under no circumstances should your compiled code ever call <code class="code">abort</code>
or <code class="code">exit</code><a class="footnote" id="DOCF82" href="#FOOT82"><sup>82</sup></a>: these terminate the user&rsquo;s R process, quite possibly
losing all unsaved work.  One usage that could call <code class="code">abort</code> is the
<code class="code">assert</code> macro in C or C++ functions, which should never be active
in production code.  The normal way to ensure that is to define the
macro <code class="code">NDEBUG</code>, and <code class="command">R CMD INSTALL</code> does so as part of the
compilation flags.  Beware of including headers (including from other
packages) which could undefine it, now or in future versions.  If you
wish to use <code class="code">assert</code> during development. you can include
<code class="code">-UNDEBUG</code> in <code class="code">PKG_CPPFLAGS</code> or <code class="code">#undef</code> it in your
headers or code files.  Note that your own <samp class="file">src/Makefile</samp> or
makefiles in sub-directories may also need to define <code class="code">NDEBUG</code>.

<p>This applies not only to your own code but to any external software you
compile in or link to.
</p>
</li><li>Compiled code should not write to <samp class="file">stdout</samp> or <samp class="file">stderr</samp> and C++
and Fortran I/O should not be used.  As with the previous item such
calls may come from external software and may never be called, but
package authors are often mistaken about that.

</li><li>Compiled code should not call the system random number generators such
as <code class="code">rand</code>, <code class="code">drand48</code> and <code class="code">random</code><a class="footnote" id="DOCF83" href="#FOOT83"><sup>83</sup></a>, but rather use the
interfaces to R&rsquo;s RNGs described in <a class="ref" href="#Random-numbers">Random number generation</a>.  In
particular, if more than one package initializes a system RNG (e.g.
<em class="emph">via</em> <code class="code">srand</code>), they will interfere with each other.  This
applies also to Fortran 90&rsquo;s <code class="code">random_number</code> and
<code class="code">random_seed</code>, and Fortran 2018&rsquo;s <code class="code">random_init</code>.  And to GNU
Fortran&rsquo;s<!-- /@w --> <code class="code">rand</code>, <code class="code">irand</code> and <code class="code">srand</code>.  Except for
<code class="code">drand48</code>, what PRNG these functions use is
implementation-dependent.

<p>Nor should the C++11 random number library be used nor any other
third-party random number generators such as those in GSL.
</p>
</li><li>Use of <code class="code">sprintf</code> and <code class="code">vsprintf</code> is regarded as a potential
security risk and warned about on some platforms.<a class="footnote" id="DOCF84" href="#FOOT84"><sup>84</sup></a>  <code class="command">R CMD check</code> reports if any calls
are found.

</li><li>Errors in memory allocation and reading/writing outside arrays are very
common causes of crashes (e.g., segfaults) on some machines.
See <a class="ref" href="#Checking-memory-access">Checking memory access</a> for tools which can be used to look for this.

</li><li>Many platforms will allow unsatisfied entry points in compiled code, but
will crash the application (here R) if they are ever used.  Some
(notably Windows) will not.  Looking at the output of

<div class="example">
<pre class="example-preformatted">nm -pg mypkg.so
</pre></div>

<p>and checking if any of the symbols marked <code class="code">U</code> is unexpected is a
good way to avoid this.
</p>
</li><li>Linkers have a lot of freedom in how to resolve entry points in
dynamically-loaded code, so the results may differ by platform.  One
area that has caused grief is packages including copies of standard
system software such as <code class="code">libz</code> (especially those already linked
into R).  In the case in point, entry point <code class="code">gzgets</code> was
sometimes resolved against the old version compiled into the package,
sometimes against the copy compiled into R and sometimes against the
system dynamic library.  The only safe solution is to rename the entry
points in the copy in the package.  We have even seen problems with
entry point name <code class="code">myprintf</code>, which is a system entry
point<a class="footnote" id="DOCF85" href="#FOOT85"><sup>85</sup></a> on some Linux systems.

<p>A related issue is the naming of libraries built as part of the package
installation.  macOS and Windows have case-insensitive file systems, so
using
</p><div class="example">
<pre class="example-preformatted">-L. -lLZ4
</pre></div>
<p>in <code class="code">PKG_LIBS</code> will match <code class="code">liblz4</code>.  And <code class="code">-L.</code> only
appends to the list of searched locations, and <code class="code">liblz4</code> might be
found in an earlier-searched location (and has been).  The only safe way
is to give an explicit path, for example
</p><div class="example">
<pre class="example-preformatted">./libLZ4.a
</pre></div>

</li><li>Conflicts between symbols in DLLs are handled in very platform-specific
ways.  Good ways to avoid trouble are to make as many symbols as
possible static (check with <code class="code">nm -pg</code>), and to use names which are
clearly tied to your package (which also helps users if anything does go
wrong).  Note that symbol names starting with <code class="code">R_</code> are regarded as
part of R&rsquo;s namespace and should not be used in packages.

</li><li>It is good practice for DLLs to register their symbols
(see <a class="pxref" href="#Registering-native-routines">Registering native routines</a>), restrict visibility
(see <a class="pxref" href="#Controlling-visibility">Controlling visibility</a>) and not allow symbol search
(see <a class="pxref" href="#Registering-native-routines">Registering native routines</a>).  It should be possible for a DLL
to have only one visible symbol, <code class="code">R_init_<var class="var">pkgname</var></code>, on
suitable platforms<a class="footnote" id="DOCF86" href="#FOOT86"><sup>86</sup></a>,
which would completely avoid symbol conflicts.

</li><li>It is not portable to call compiled code in R or other packages
<em class="emph">via</em> <code class="code">.Internal</code>, <code class="code">.C</code>, <code class="code">.Fortran</code>, <code class="code">.Call</code> or
<code class="code">.External</code>, since such interfaces are subject to change without
notice and will probably result in your code terminating the R
process.

</li><li>Do not use (hard or symbolic) file links in your package sources.
Where possible <code class="command">R CMD build</code> will replace them by copies.

</li><li>If you do not yourself have a Windows system, consider submitting your
source package to WinBuilder (<a class="uref" href="https://win-builder.r-project.org/">https://win-builder.r-project.org/</a>)
before distribution.  If you need to check on an M1 Mac, there is a
check service at
<a class="uref" href="https://mac.r-project.org/macbuilder/submit.html">https://mac.r-project.org/macbuilder/submit.html</a>.

</li><li>It is bad practice for package code to alter the search path using
<code class="code">library</code>, <code class="code">require</code> or <code class="code">attach</code> and this often does not
work as intended.  For alternatives, see <a class="ref" href="#Suggested-packages">Suggested packages</a> and
<code class="code">with()</code>.

</li><li>Examples can be run interactively <em class="emph">via</em> <code class="code">example</code> as well as
in batch mode when checking.  So they should behave appropriately in
both scenarios, conditioning by <code class="code">interactive()</code> the parts which
need an operator or observer.  For instance, progress
bars<a class="footnote" id="DOCF87" href="#FOOT87"><sup>87</sup></a> are only appropriate in
interactive use, as is displaying help pages or calling <code class="code">View()</code>
(see below).

</li><li>Be careful with the order of entries in macros such as <code class="code">PKG_LIBS</code>.
Some linkers will re-order the entries, and behaviour can differ between
dynamic and static libraries.  Generally <samp class="option">-L</samp> options should
precede<a class="footnote" id="DOCF88" href="#FOOT88"><sup>88</sup></a> the libraries (typically
specified by <samp class="option">-l</samp> options) to be found from those directories,
and libraries are searched once in the order they are specified.  Not
all linkers allow a space after <samp class="option">-L</samp> .

</li><li>Care is needed with the use of <code class="code">LinkingTo</code>.  This puts one or more
directories on the include search path ahead of system headers but
(prior to R 3.4.0) after those specified in the <code class="code">CPPFLAGS</code> macro
of the R build (which normally includes <code class="code">-I/usr/local/include</code>,
but most platforms ignore that and include it with the system headers).

<p>Any confusion would be avoided by having <code class="code">LinkingTo</code> headers in a
directory named after the package.  In any case, name conflicts of
headers and directories under package <samp class="file">include</samp> directories should
be avoided, both between packages and between a package and system and
third-party software.
</p>
</li><li>The <code class="command">ar</code> utility is often used in makefiles to make static
libraries.  Its modifier <code class="code">u</code> is defined by POSIX but is disabled in
GNU <code class="command">ar</code> on some Linux distributions which use
&lsquo;deterministic mode&rsquo;.  The safest way to make a static library is to first
remove any existing file of that name then use <code class="command">$(AR) -cr</code> and then
<code class="command">$(RANLIB)</code> if needed (which is system-dependent: on most
systems<a class="footnote" id="DOCF89" href="#FOOT89"><sup>89</sup></a> <code class="command">ar</code> always
maintains a symbol table).  The POSIX standard says options should be
preceded by a hyphen (as in <samp class="option">-cr</samp>), although most OSes accept
them without.
Note that on some systems <code class="command">ar -cr</code> must have at least one file
specified.

<p>The <code class="code">s</code> modifier (to replace a separate call to <code class="command">ranlib</code>)
is required by X/OPEN but not POSIX, so <code class="command">ar -crs</code> is not
portable.
</p>
<p>For portability the <code class="code">AR</code> and <code class="code">RANLIB</code> macros should always be
used &ndash; some builds require wrappers such as <code class="command">gcc-ar</code> or extra
arguments to specify plugins.
</p>
</li><li>The <code class="command">strip</code> utility is platform-specific (and <abbr class="acronym">CRAN</abbr>
prohibits removing debug symbols).  For example the options
<samp class="option">--strip-debug</samp> and <samp class="option">--strip-unneeded</samp> of the GNU version
are not supported on macOS: the POSIX standard for <code class="command">strip</code>
does not mention any options, and what calling it without options does
is platform-dependent.  Stripping a <samp class="file">.so</samp> file could even prevent
it being dynamically loaded into R on an untested platform.

<p><code class="command">ld -S</code> invokes <code class="command">strip --strip-debug</code> for GNU
<code class="command">ld</code> (and similarly on macOS) but is not portable: in particular
on Solaris it did something completely different and took an argument.
</p>
</li><li>Some people have a need to set a locale.  Locale names are not portable,
and e.g. &lsquo;<samp class="samp">fr_FR.utf8</samp>&rsquo; is commonly used on Linux but not accepted
on macOS.  &lsquo;<samp class="samp">fr_FR.UTF-8</samp>&rsquo; is more portable, being accepted on recent
Linux, <abbr class="abbr">AIX</abbr>, FreeBSD, macOS and Solaris (at least).  However, some Linux
distributions micro-package, so locales defined by <strong class="strong">glibc</strong>
(including these examples) may not be installed.

</li><li>Avoid spaces in file names, not least as they can cause difficulties for
external tools.  An example was a package with a <a class="url" href="https://CRAN.R-project.org/package=knitr"><strong class="strong">knitr</strong></a>
vignette that used spaces in plot names: this caused some older versions
of <code class="command">pandoc</code> to fail with a baffling error message.

<p>Non-ASCII filenames can also cause problems (particularly in non-UTF-8
locales).
</p>
</li><li>Take care in naming LaTeX macros (also known as &lsquo;commands&rsquo;) in
vignette sources: if these are also defined in a future version of one
of the LaTeX packages used there will be a fatal error.  One instance
in 2021 was package &lsquo;<samp class="samp">hyperref</samp>&rsquo; newly defining &lsquo;<samp class="samp">\C</samp>&rsquo;, &lsquo;<samp class="samp">\F</samp>&rsquo;,
&lsquo;<samp class="samp">\G</samp>&rsquo;, &lsquo;<samp class="samp">\U</samp>&rsquo; and &lsquo;<samp class="samp">\textapprox</samp>&rsquo;.  If you are confident that
your definitions will be the only ones relevant you can use
&lsquo;<samp class="samp">\renewcommand</samp>&rsquo; but it is better to use names clearly associated
with your package.

</li><li>Make sure that any version requirement for Java code is both declared in
the &lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field<a class="footnote" id="DOCF90" href="#FOOT90"><sup>90</sup></a> and tested at
runtime (not least as the Java installation when the package is
installed might not be the same as when the package is run and will not
be for binary packages).


<p>When specifying a minimum Java version please use the official version
names, which are (confusingly)
</p><div class="example">
<pre class="example-preformatted">1.1 1.2 1.3 1.4 5.0 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
</pre></div>
<p>and as from 2018 a year.month scheme such as &lsquo;<samp class="samp">18.9</samp>&rsquo; is also in
use.  Fortunately only the integer values are likely to be relevant.
If at all possible, use one of the <abbr class="acronym">LTS</abbr> versions (8, 11, 17, 21 &hellip;)
as the minimum version.  The preferred form of version specification is
</p><div class="example">
<pre class="example-preformatted">SystemRequirements: Java (&gt;= 11)
</pre></div>

<p>A suitable test for Java at least version 8 for packages using
<a class="url" href="https://CRAN.R-project.org/package=rJava"><strong class="strong">rJava</strong></a> would be something like
</p><div class="example">
<pre class="example-preformatted">.jinit()
jv &lt;- .jcall(&quot;java/lang/System&quot;, &quot;S&quot;, &quot;getProperty&quot;, &quot;java.runtime.version&quot;)
if(substr(jv, 1L, 2L) == &quot;1.&quot;) {
  jvn &lt;- as.numeric(paste0(strsplit(jv, &quot;[.]&quot;)[[1L]][1:2], collapse = &quot;.&quot;))
  if(jvn &lt; 1.8) stop(&quot;Java &gt;= 8 is needed for this package but not available&quot;)
}
</pre></div>
<p>Java 9 changed the format of this string (which used to be something
like &lsquo;<samp class="samp">1.8.0_292-b10</samp>&rsquo;); Java 11 gave <code class="code">jv</code> as &lsquo;<samp class="samp">11+28</samp>&rsquo;
whereas Java 11.0.11 gave &lsquo;<samp class="samp">11.0.11+9</samp>&rsquo;.
(<a class="uref" href="https://openjdk.org:443/jeps/322">https://openjdk.org:443/jeps/322</a> details the current scheme.
Note that it is necessary to allow for pre-releases like
&lsquo;<samp class="samp">11-ea+22</samp>&rsquo;.)
</p>
<p>Note too that the compiler used to produce a <code class="code">jar</code> can impose a minimum
Java version, often resulting in an arcane message like
</p>
<div class="example">
<pre class="example-preformatted">java.lang.UnsupportedClassVersionError: ... Unsupported major.minor version 52.0
</pre></div>
<p>(Where <a class="uref" href="https://en.wikipedia.org/wiki/Java_class_file">https://en.wikipedia.org/wiki/Java_class_file</a> maps
class-file version numbers to Java versions.)  Compile with something
like <code class="command">javac -target 11</code> to ensure this is avoided.  Note this
also applies to packages distributing (or even downloading) compiled
Java code produced by others, so their requirements need to be checked
(they are often not documented accurately) and accounted for.  It should
be possible to check the class-file version <em class="emph">via</em> command-line
utility <code class="command">javap</code>, if necessary after extracting the <samp class="file">.class</samp>
files from a <samp class="file">.jar</samp> archive.  For example,
</p><div class="example">
<pre class="example-preformatted">jar xvf some.jar
javap -verbose path/to/some.class | grep major
</pre></div>

<p>Some packages have stated a requirement on a particular <abbr class="abbr">JDK</abbr>, but a
package should only be requiring a <abbr class="abbr">JRE</abbr> unless providing its own Java
interface.
</p>
<p>Java 8 is still in widespread use (and may remain so because of licence
changes and support on older OSes: OpenJDK has security support until
March 2026).  On the other hand, newer platforms may only have support
for recent versions of Java: for &lsquo;<samp class="samp">arm64</samp>&rsquo; macOS the first
officially supported version was 17.
</p>
</li><li>A package with a hard-to-satisfy system requirement is by definition not
portable, annoyingly so if this is not declared in the
&lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field.  The most common example is the use of
<code class="command">pandoc</code>, which is only available for a very limited range of
platforms (and has onerous requirements to install from source) and has
capabilities<a class="footnote" id="DOCF91" href="#FOOT91"><sup>91</sup></a> that vary by build but are not documented.  Several recent
versions of <code class="command">pandoc</code> for macOS did not work on R&rsquo;s then
target of High Sierra (and this too was undocumented).  Another example
is the Rust compilation system (<code class="command">cargo</code> and <code class="command">rustc</code>).

<p>Usage of external commands should always be conditional on a test for
presence (perhaps using <code class="code">Sys.which</code>), as well as declared in the
&lsquo;<samp class="samp">SystemRequirements</samp>&rsquo; field.  A package should pass its checks
without warnings nor errors without the external command being present.
</p>
<p>An external command can be a (possibly optional) requirement for an
imported or suggested package but needed for examples, tests or
vignettes in the package itself.  Such usages should always be declared
and conditional.
</p>
<p>Interpreters for scripting languages such as Perl, Python and Ruby need
to be declared as system requirements and used conditionally: for
example macOS 10.16 was announced not to have them (but released as
macOS 11 with them); later it was announced that macOS 12.3 does not
have Python 2 and only a minimal install of Python 3 is included.
Python 2 has passed end-of-life and been removed from many major
distributions.  Support for Rust or Go cannot be assumed.
</p>
<p>Command <code class="command">cmake</code> is not commonly installed, and where it is, it
might not be on the path.  In particular, the most common location on
macOS is <samp class="file">/Applications/CMake.app/Contents/bin/cmake</samp> and that
should be looked for if <code class="command">cmake</code> is not found on the path.
</p>
</li><li>Be sure to use portable encoding names: none of <code class="code">utf8</code>, <code class="code">mac</code>
and <code class="code">macroman</code> is portable.  See the help for <code class="code">file</code> for more
details.


</li><li>Do not invoke R by plain <code class="command">R</code>, <code class="command">Rscript</code> or (on
Windows) <code class="command">Rterm</code> in your examples, tests, vignettes, makefiles
or other scripts.  As pointed out in several places earlier in this
manual, use something like
<div class="example">
<pre class="example-preformatted">&quot;$(R_HOME)/bin/Rscript&quot;
&quot;$(R_HOME)/bin$(R_ARCH_BIN)/Rterm&quot;
</pre></div>
<p>with appropriate quotes (as, although not recommended, <code class="env">R_HOME</code> can
contain spaces).
</p>
</li><li>Do not use <code class="env">R_HOME</code> in makefiles except when passing them to the shell.
Specifically, do not use <code class="env">R_HOME</code> in the argument to <code class="code">include</code>,
as <code class="env">R_HOME</code> can contain spaces. Quoting the argument to <code class="code">include</code>
does not help. A portable and the recommended way to avoid the problem of spaces in
<code class="code">${R_HOME}</code> is using option <code class="code">-f</code> of <code class="command">make</code>.  This is
easy to do with recursive invocation of <code class="command">make</code>, which is also the
only usual situation when <code class="env">R_HOME</code> is needed in the argument for
<code class="code">include</code>.

<div class="example">
<pre class="example-preformatted">$(MAKE) -f &quot;${R_HOME}/etc${R_ARCH}/Makeconf&quot; -f Makefile.inner
</pre></div>

</li><li>If distributing datasets involving date-times, consider if a time zone
needs to be specified. The most portable way to distribute date-times is
as objects of class <code class="code">&quot;POSIXct&quot;</code> and as these record the time in
UTC, the time represented is independent of the time zone: but how it is
printed may not be.  Objects of class <code class="code">&quot;POSIXlt&quot;</code> should have a
<code class="code">&quot;tzone&quot;</code> attribute.  Dates (e.g, birthdays) are conventionally
considered independently of time zone.

</li><li>If at all possible avoid any Internet access during package
installation.  Installation and use may well be on different
machines/accounts and those allowed to install software may have no
Internet access, and being self-contained helps ensure long-term
reproducibility.
</li></ul>


<p>Do be careful in what your tests (and examples) actually test.  Bad
practice seen in distributed packages include:
</p>
<ul class="itemize mark-bullet">
<li>It is not reasonable to test the time taken by a command: you cannot
know how fast or how heavily loaded an R platform might be.  At best
you can test a ratio of times, and even that is fraught with
difficulties and not advisable: for example, the garbage collector may
trigger at unpredictable times following heuristics that may change
without notice.

</li><li>Do not test the exact format of R messages (from R itself or from
other packages): They change, and they can be translated.

<p>Packages have even tested the exact format of system error messages,
which are platform-dependent and perhaps locale-dependent.  For example,
in late 2021 <code class="code">libcurl</code> changed its warning/error messages,
including when URLs are not found.
</p>
</li><li>Do not test for the absence of warnings (something users of
<a class="url" href="https://CRAN.R-project.org/package=testthat"><strong class="strong">testthat</strong></a> are fond of).  Future changes in either R or
packages you make use of can create new warnings, and your tests should
not make these into errors.  (Some deprecation notices may be intended
to remain as warnings for a long time.)

</li><li>If you use functions such as <code class="code">View</code>, remember that in testing there
is no one to look at the output.  It is better to use something like one of
<div class="example">
<pre class="example-preformatted">if(interactive()) View(obj) else print(head(obj))
if(interactive()) View(obj) else str(obj)
</pre></div>

</li><li>Be careful when comparing file paths.  There can be multiple paths to a
single file, and some of these can be very long character strings.  If
possible canonicalize paths before comparisons, but study
<code class="code">?normalizePath</code> to be aware of the pitfalls.

</li><li>Only test the accuracy of results if you have done a formal error
analysis.  Things such as checking that probabilities numerically sum to
one are silly: numerical tests should always have a tolerance.  That the
tests on your platform achieve a particular tolerance says little about
other platforms.  R is configured by default to make use of long
doubles where available, but they may not be available or be too slow
for routine use.  Most R platforms use &lsquo;<samp class="samp">ix86</samp>&rsquo; or
&lsquo;<samp class="samp">x86_64</samp>&rsquo; CPUs: these may use extended precision registers on
some but not all of their <abbr class="abbr">FPU</abbr> instructions.  Thus the achieved precision
can depend on the compiler version and optimization flags&mdash;our
experience is that 32-bit builds tend to be less precise than 64-bit
ones.  But not all platforms use those CPUs, and not all<a class="footnote" id="DOCF92" href="#FOOT92"><sup>92</sup></a> which use them configure them to allow the use of extended
precision.  In particular, current ARM CPUs do not have extended
precision nor long doubles, and <code class="command">clang</code> currently has long
double the same as double on all ARM CPUs.  On the other hand some CPUs
have higher-precision modes which may be used for <code class="code">long double</code>,
notably 64-bit PowerPC and Sparc.

<p>If you must try to establish a tolerance empirically, configure and
build R with <samp class="option">--disable-long-double</samp> and use appropriate
compiler flags (such as <samp class="option">-ffloat-store</samp> and
<samp class="option">-fexcess-precision=standard</samp> for <code class="command">gcc</code>, depending on the
CPU type<a class="footnote" id="DOCF93" href="#FOOT93"><sup>93</sup></a>) to
mitigate the effects of extended-precision calculations.  The platform
most often seen to give different numerical results is &lsquo;<samp class="samp">arm64</samp>&rsquo; macOS,
so be sure to include that in any empirical determination.
</p>
<p>Tests which involve random inputs or non-deterministic algorithms should
normally set a seed or be tested for many seeds.
</p>
</li><li>Tests should use <code class="code">options(warn = 1)</code> as reporting

<div class="example">
<pre class="example-preformatted">There were 22 warnings (use warnings() to see them)
</pre></div>

<p>is pointless, especially for automated checking systems.
</p>
</li><li>If your package uses dates/times, ensure that it works in all timezones,
especially those near boundaries (problems have most often be seen in
&lsquo;<samp class="samp">Europe/London</samp>&rsquo; (zero offset in Winter) and
&lsquo;<samp class="samp">Pacific/Auckland</samp>&rsquo;, near enough the International Date line) and
with offsets not in whole hours (Adelaide, Chatham Islands, &hellip;).
More extreme examples are &lsquo;<samp class="samp">Africa/Conakry</samp>&rsquo; (permanent UTC),
&lsquo;<samp class="samp">Asia/Calcutta</samp>&rsquo; (no DST, permanent half-hour offset)
and &lsquo;<samp class="samp">Pacific/Kiritimati</samp>&rsquo;(no DST, more than 12 hours ahead of UTC).

</li></ul>

<ul class="mini-toc">
<li><a href="#PDF-size" accesskey="1">PDF size</a></li>
<li><a href="#Check-timing" accesskey="2">Check timing</a></li>
<li><a href="#Encoding-issues" accesskey="3">Encoding issues</a></li>
<li><a href="#Portable-C-and-C_002b_002b-code" accesskey="4">Portable C and C++ code</a></li>
<li><a href="#Portable-Fortran-code" accesskey="5">Portable Fortran code</a></li>
<li><a href="#Binary-distribution" accesskey="6">Binary distribution</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="PDF-size">
<div class="nav-panel">
<p>
Next: <a href="#Check-timing" accesskey="n" rel="next">Check timing</a>, Previous: <a href="#Writing-portable-packages" accesskey="p" rel="prev">Writing portable packages</a>, Up: <a href="#Writing-portable-packages" accesskey="u" rel="up">Writing portable packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="PDF-size-1"><span>1.6.1 PDF size<a class="copiable-link" href="#PDF-size-1"> &para;</a></span></h4>

<p>There are a several tools available to reduce the size of PDF files:
often the size can be reduced substantially with no or minimal loss in
quality. Not only do large files take up space: they can stress the PDF
viewer and take many minutes to print (if they can be printed at all).
</p>
<p><code class="command">qpdf</code> (<a class="uref" href="https://qpdf.sourceforge.io/">https://qpdf.sourceforge.io/</a>) can compress
losslessly.  It is fairly readily available (e.g. it is included in
<code class="code">rtools</code>, has packages in Debian/Ubuntu/Fedora, and is
installed as part of the <abbr class="acronym">CRAN</abbr> macOS distribution of R).
<code class="command">R CMD build</code> has an option to run <code class="command">qpdf</code> over PDF files
under <samp class="file">inst/doc</samp> and replace them if at least 10Kb and 10% is
saved.  The full path to the <code class="command">qpdf</code> command can be supplied as
environment variable <code class="env">R_QPDF</code> (and is on the <abbr class="acronym">CRAN</abbr> binary
of R for macOS).  It seems MiKTeX does not use PDF object
compression and so <code class="command">qpdf</code> can reduce considerably the sizes of
files it outputs: MiKTeX&rsquo;s defaults can be overridden by code in the
preamble of an Sweave or LaTeX file &mdash; see how this is done for the
R reference manual at
<a class="uref" href="https://svn.r-project.org/R/trunk/doc/manual/refman.top">https://svn.r-project.org/R/trunk/doc/manual/refman.top</a>.
</p>
<p>Other tools can reduce the size of PDFs containing bitmap images at
excessively high resolution.  These are often best re-generated (for
example <code class="code">Sweave</code> defaults to 300&nbsp;<abbr class="abbr">ppi</abbr>, and 100&ndash;150 is more
appropriate for a package manual).  These tools include Adobe Acrobat
(not Reader), Apple&rsquo;s Preview<a class="footnote" id="DOCF94" href="#FOOT94"><sup>94</sup></a>  and Ghostscript (which
converts PDF to PDF by
</p>
<div class="example">
<pre class="example-preformatted">ps2pdf <var class="var">options</var> -dAutoRotatePages=/None -dPrinted=false <var class="var">in</var>.pdf <var class="var">out</var>.pdf
</pre></div>

<p>and suitable options might be
</p>
<div class="example">
<pre class="example-preformatted">-dPDFSETTINGS=/ebook
-dPDFSETTINGS=/screen
</pre></div>

<p>See <a class="uref" href="https://ghostscript.readthedocs.io/en/latest/VectorDevices.html">https://ghostscript.readthedocs.io/en/latest/VectorDevices.html</a> for
more such and consider all the options for image downsampling).  There
have been examples in <abbr class="acronym">CRAN</abbr> packages for which current versions
of Ghostscript produced much bigger reductions than earlier ones (e.g.
at the upgrades from <code class="code">9.50</code> to <code class="code">9.52</code>, from <code class="code">9.55</code> to
<code class="code">9.56</code> and then to <code class="code">10.00.0</code>).
</p>
<p>We come across occasionally large PDF files containing excessively
complicated figures using PDF vector graphics: such figures are often
best redesigned or failing that, output as PNG files.
</p>
<p>Option <samp class="option">--compact-vignettes</samp> to <code class="command">R CMD build</code> defaults to
value &lsquo;<samp class="samp">qpdf</samp>&rsquo;: use &lsquo;<samp class="samp">both</samp>&rsquo; to try harder to reduce the size,
provided you have Ghostscript available (see the help for
<code class="code">tools::compactPDF</code>).
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Check-timing">
<div class="nav-panel">
<p>
Next: <a href="#Encoding-issues" accesskey="n" rel="next">Encoding issues</a>, Previous: <a href="#PDF-size" accesskey="p" rel="prev">PDF size</a>, Up: <a href="#Writing-portable-packages" accesskey="u" rel="up">Writing portable packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Check-timing-1"><span>1.6.2 Check timing<a class="copiable-link" href="#Check-timing-1"> &para;</a></span></h4>

<p>There are several ways to find out where time is being spent in the
check process.  Start by setting the environment variable
<code class="env">_R_CHECK_TIMINGS_</code> to &lsquo;<samp class="samp">0</samp>&rsquo;.  This will report the total CPU
times (not Windows) and elapsed times for installation and running
examples, tests and vignettes, under each sub-architecture if
appropriate.  For tests and vignettes, it reports the time for each as
well as the total.
</p>
<p>Setting <code class="env">_R_CHECK_TIMINGS_</code> to a positive value sets a threshold (in
seconds elapsed time) for reporting timings.
</p>
<p>If you need to look in more detail at the timings for examples, use
option <samp class="option">--timings</samp> to <code class="command">R CMD check</code> (this is set by
<samp class="option">--as-cran</samp>).  This adds a summary to the check output for all
the examples with CPU or elapsed time of more than 5 seconds.  It
produces a file <samp class="file"><var class="var">mypkg</var>.Rcheck/<var class="var">mypkg</var>-Ex.timings</samp>
containing timings for each help file: it is a tab-delimited file which
can be read into R for further analysis.
</p>
<p>Timings for the tests and vignette runs are given at the bottom of the
corresponding log file: note that log files for successful vignette runs
are only retained if environment variable
<code class="env">_R_CHECK_ALWAYS_LOG_VIGNETTE_OUTPUT_</code> is set to a true value.
</p>

<hr>
</div>
<div class="subsection-level-extent" id="Encoding-issues">
<div class="nav-panel">
<p>
Next: <a href="#Portable-C-and-C_002b_002b-code" accesskey="n" rel="next">Portable C and C++ code</a>, Previous: <a href="#Check-timing" accesskey="p" rel="prev">Check timing</a>, Up: <a href="#Writing-portable-packages" accesskey="u" rel="up">Writing portable packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Encoding-issues-1"><span>1.6.3 Encoding issues<a class="copiable-link" href="#Encoding-issues-1"> &para;</a></span></h4>

<p>The issues in this subsection have been much alleviated by the change in
R 4.2.0 to running the Windows port of R in a UTF-8 locale where
available.  However, Windows users might be running an earlier version
of R on an earlier version of Windows which does not support UTF-8
locales.
</p>
<p>Care is needed if your package contains non-<abbr class="acronym">ASCII</abbr> text, and in
particular if it is intended to be used in more than one locale.  It is
possible to mark the encoding used in the <samp class="file">DESCRIPTION</samp> file and in
<samp class="file">.Rd</samp> files, as discussed elsewhere in this manual.
</p>
<p>First, consider carefully if you really need non-<abbr class="acronym">ASCII</abbr> text.
Some users of R will only be able to view correctly text in their
native language group (e.g. Western European, Eastern European,
Simplified Chinese) and <abbr class="acronym">ASCII</abbr>.<a class="footnote" id="DOCF95" href="#FOOT95"><sup>95</sup></a>.  Other characters may not be rendered at all,
rendered incorrectly, or cause your R code to give an error.  For
<samp class="file">.Rd</samp> documentation, marking the encoding and including
<abbr class="acronym">ASCII</abbr> transliterations is likely to do a reasonable job.  The
set of characters which is commonly supported is wider than it used to
be around 2000, but non-Latin alphabets (Greek, Russian, Georgian,
&hellip;) are still often problematic and those with double-width
characters (Chinese, Japanese, Korean, emoji) often need specialist
fonts to render correctly.
</p>
<p>Several <abbr class="acronym">CRAN</abbr> packages have messages in their R code in French (and a
few in German).  A better way to tackle this is to use the
internationalization facilities discussed elsewhere in this manual.
</p>
<p>Function <code class="code">showNonASCIIfile</code> in package <strong class="strong">tools</strong> can help in
finding non-<abbr class="acronym">ASCII</abbr> bytes in files.
</p>
<p>There is a portable way to have arbitrary text in character strings
(only) in your R code, which is to supply them in Unicode as
&lsquo;<samp class="samp">\uxxxx</samp>&rsquo; escapes (or, rarely needed except for emojis,
&lsquo;<samp class="samp">\Uxxxxxxxx</samp>&rsquo; escapes).  If there are any characters not in the
current encoding the parser will encode the character string as UTF-8
and mark it as such.  This applies also to character strings in
datasets: they can be prepared using &lsquo;<samp class="samp">\uxxxx</samp>&rsquo; escapes or encoded in
UTF-8 in a UTF-8 locale, or even converted to UTF-8 <em class="emph">via</em>
<code class="code">iconv()</code>.  If you do this, make sure you have &lsquo;<samp class="samp">R (&gt;= 2.10)</samp>&rsquo;
(or later) in the &lsquo;<samp class="samp">Depends</samp>&rsquo; field of the <samp class="file">DESCRIPTION</samp> file.
</p>
<p>R sessions running in non-UTF-8 locales will if possible re-encode
such strings for display (and this is done by <code class="command">RGui</code> on older
versions of Windows, for example).  Suitable fonts will need to be
selected or made available<a class="footnote" id="DOCF96" href="#FOOT96"><sup>96</sup></a>  both for the console/terminal and graphics devices
such as &lsquo;<samp class="samp">X11()</samp>&rsquo; and &lsquo;<samp class="samp">windows()</samp>&rsquo;.  Using &lsquo;<samp class="samp">postscript</samp>&rsquo; or
&lsquo;<samp class="samp">pdf</samp>&rsquo; will choose a default 8-bit encoding depending on the
language of the UTF-8 locale, and your users would need to be told how
to select the &lsquo;<samp class="samp">encoding</samp>&rsquo; argument.
</p>
<p>Note that the previous two paragraphs only apply to character strings in
R code.  Non-ASCII characters are particularly prevalent in comments
(in the R code of the package, in examples, tests, vignettes and even
in the <samp class="file">NAMESPACE</samp> file) but should be avoided there.  Most commonly
people use the Windows extensions to Latin-1 (often directional single
and double quotes, ellipsis, bullet and en and em dashes) which are not
supported in strict Latin-1 locales nor in CJK locales on Windows.  A
surprisingly common misuse is to use a right quote in &lsquo;<samp class="samp">don't</samp>&rsquo;
instead of the correct apostrophe.
</p>
<p>Datasets can include marked UTF-8 or Latin-1 character strings.  As R
is nowadays unlikely to be run in a Latin-1 or Windows&rsquo; CP1252 locale,
for performance reasons these should be converted to UTF-8.
</p>
<p>If you want to run <code class="command">R CMD check</code> on a Unix-alike over a package
that sets a package encoding in its <samp class="file">DESCRIPTION</samp> file <em class="emph">and do
not use a UTF-8 locale</em> you may need to specify a suitable locale
<em class="emph">via</em> environment variable <code class="env">R_ENCODING_LOCALES</code>.  The default
is equivalent to the value
</p>
<div class="example">
<pre class="example-preformatted">&quot;latin1=en_US:latin2=pl_PL:UTF-8=en_US.UTF-8:latin9=fr_FR.iso885915@euro&quot;
</pre></div>

<p>(which is appropriate for a system based on <code class="code">glibc</code>: macOS requires
<code class="code">latin9=fr_FR.ISO8859-15</code>) except that if the current locale is
UTF-8 then the package code is translated to UTF-8 for syntax checking,
so it is strongly recommended to check in a UTF-8 locale.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Portable-C-and-C_002b_002b-code">
<div class="nav-panel">
<p>
Next: <a href="#Portable-Fortran-code" accesskey="n" rel="next">Portable Fortran code</a>, Previous: <a href="#Encoding-issues" accesskey="p" rel="prev">Encoding issues</a>, Up: <a href="#Writing-portable-packages" accesskey="u" rel="up">Writing portable packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Portable-C-and-C_002b_002b-code-1"><span>1.6.4 Portable C and C++ code<a class="copiable-link" href="#Portable-C-and-C_002b_002b-code-1"> &para;</a></span></h4>


<p>Writing portable C and C++ code is mainly a matter of observing the
standards (C99, C++14 or where declared C++11/17/20) and testing that
extensions (such as POSIX functions) are supported.  Do make maximal use
of your compiler diagnostics &mdash; this typically means using flags
<samp class="option">-Wall</samp> and <samp class="option">-pedantic</samp> for both C and C++ and additionally
<samp class="option">-Werror=implicit-function-declaration</samp> and
<samp class="option">-Wstrict-prototypes</samp> for C (on some platforms and compiler
versions) these are part of <samp class="option">-Wall</samp> or <samp class="option">-pedantic</samp>).
</p>
<p><strong class="strong">C++ standards</strong>: From version 3.6.0 (3.6.2 on Windows), R
defaulted to C++11 where available<a class="footnote" id="DOCF97" href="#FOOT97"><sup>97</sup></a>; from R 4.1.0 to C++14
and from R 4.3.0 to C++17 (where available).  However, in earlier
versions the default standard was that of the compiler used, often C++98
or C++14, and the default is likely to change in future.  For maximal
portability a package should either specify a standard (see <a class="pxref" href="#Using-C_002b_002b-code">Using C++ code</a>) or be tested under all of C++11, C++98, C++14 and C++17.
(Specifying C++14 or later will limit portability.)
</p>
<p>Note that the &lsquo;TR1&rsquo; C++ extensions are not part of any of these
standards and the <code class="code">&lt;tr1/<var class="var">name</var>&gt;</code> headers are not supplied by some of
the compilers used for R, including on macOS.  (Use the C++11
versions instead.)
</p>
<p>A common error is to assume recent versions of compilers or OSes.  In
production environments &lsquo;long term support&rsquo; versions of OSes may be in
use for many years,<a class="footnote" id="DOCF98" href="#FOOT98"><sup>98</sup></a> and their compilers may not
be updated during that time.  For example, GCC 4.8 was still in use in
2022 and could be (in RHEL 7) until 2028: that supports neither C++14
nor C++17.
</p>
<p>The POSIX standards only require recently-defined functions to be
declared if certain macros are defined with large enough values, and on
some compiler/OS combinations<a class="footnote" id="DOCF99" href="#FOOT99"><sup>99</sup></a> they are not declared otherwise.  So you may
need to include something like one of
</p><div class="example">
<pre class="example-preformatted">#define _XOPEN_SOURCE 600
</pre></div>
<p>or
</p><div class="example">
<pre class="example-preformatted">#ifdef __GLIBC__
# define _POSIX_C_SOURCE 200809L
#endif
</pre></div>
<p>before <em class="emph">any</em> headers.  (<code class="code">strdup</code>, <code class="code">strncasecmp</code> and
<code class="code">strnlen</code> are such functions &ndash;  there were several older platforms
which did not have the POSIX 2008 function <code class="code">strnlen</code>.)
</p>
<p>However, some common errors are worth pointing out here.  It can be
helpful to look up functions at
<a class="uref" href="https://cplusplus.com/reference/">https://cplusplus.com/reference/</a> or
<a class="uref" href="https://en.cppreference.com/w/">https://en.cppreference.com/w/</a> and compare what is defined in the
various standards.
</p>
<p>More care is needed for functions such as <code class="code">mallinfo</code> which are not
specified by any of these standards&mdash;hopefully the <code class="command">man</code> page
on your system will tell you so.  Searching online for such pages for
various OSes (preferably at least Linux and macOS, and the FreeBSD
manual pages at <a class="uref" href="https://man.freebsd.org/cgi/man.cgi">https://man.freebsd.org/cgi/man.cgi</a> allow you to
select many OSes) should reveal useful information but a
<samp class="file">configure</samp> script is likely to be needed to check availability and
functionality.
</p>
<p>Both the compiler and OS (<em class="emph">via</em> system header files, which may
differ by architecture even for nominally the same OS) affect the
compilability of C/C++ code.  Compilers from the GCC, LLVM
(<code class="command">clang</code> and <code class="command">flang</code>) Intel and Oracle Developer Studio
suites have been used with R, and both LLVM <code class="command">clang</code> and
Oracle have more than one implementation of C++ headers and library.
The range of possibilities makes comprehensive empirical checking
impossible, and regrettably compilers are patchy at best on warning
about non-standard code.
</p>
<ul class="itemize mark-bullet">
<li>Mathematical functions such as <code class="code">sqrt</code> are defined in C++11 for
floating-point arguments: <code class="code">float</code>, <code class="code">double</code>, <code class="code">long
double</code> and possibly more.  The standard specifies what happens with an
argument of integer type but this is not always implemented, resulting
in a report of &lsquo;overloading ambiguity&rsquo;: this was commonly seen on
Solaris, but for <code class="code">pow</code> also seen on macOS and other platforms
using <code class="command">clang++</code>.

<p>A not-uncommonly-seen problem is to mistakenly call <code class="code">floor(x/y)</code> or
<code class="code">ceil(x/y)</code> for <code class="code">int</code> arguments <code class="code">x</code> and <code class="code">y</code>.  Since
<code class="code">x/y</code> does integer division, the result is of type <code class="code">int</code> and
&lsquo;overloading ambiguity&rsquo; may be reported.  Some people have (pointlessly)
called <code class="code">floor</code> and <code class="code">ceil</code> on arguments of integer type, which
may have an &lsquo;overloading ambiguity&rsquo;.
</p>
<p>A surprising common misuse is things like <code class="code">pow(10, -3)</code>: this
should be the constant <code class="code">1e-3</code>.  Note that there are constants such
as <code class="code">M_SQRT2</code> defined <em class="emph">via</em> <samp class="file">Rmath.h</samp><a class="footnote" id="DOCF100" href="#FOOT100"><sup>100</sup></a> for <code class="code">sqrt(2.0)</code>, frequently mis-coded as
<code class="code">sqrt(2)</code>.
</p>
</li><li>Function <code class="code">fabs</code> is defined only for floating-point types, except in
C++11 and later which have overloads for <code class="code">std::fabs</code> in
<samp class="file">&lt;cmath&gt;</samp> for integer types.  Function <code class="code">abs</code> is defined in
C99&rsquo;s <samp class="file">&lt;stdlib.h&gt;</samp> for <code class="code">int</code> and in C++&rsquo;s <samp class="file">&lt;cstdlib&gt;</samp> for
integer types, overloaded in <samp class="file">&lt;cmath&gt;</samp> for floating-point types.
C++11 has additional overloads for <code class="code">std::abs</code> in <samp class="file">&lt;cmath&gt;</samp> for
integer types.  The effect of calling <code class="code">abs</code> with a floating-point
type is implementation-specific: it may truncate to an integer.  For
clarity and to avoid compiler warnings, use <code class="code">abs</code> for integer types
and <code class="code">fabs</code> for double values, and when using C++ include
<samp class="file">&lt;cmath&gt;</samp> and use the <code class="code">std::</code> prefix.

</li><li>It is an error (and make little sense, although has been seen) to call
macros/functions <code class="code">isnan</code>, <code class="code">isinf</code> and <code class="code">isfinite</code> for
integer arguments: a few compilers give a compilation error.  Function
<code class="code">finite</code> is obsolete, and some compilers will warn about its
use<a class="footnote" id="DOCF101" href="#FOOT101"><sup>101</sup></a>.

</li><li>The GNU C/C++ compilers support a large number of non-portable
extensions.  For example, <code class="code">INFINITY</code> (which is a <em class="emph">float</em> value
in C99 and C++11), for which R provides the portable double value
<code class="code">R_PosInf</code> (and <code class="code">R_NegInf</code> for <code class="code">-INFINITY</code>).  And
<code class="code">NAN</code><a class="footnote" id="DOCF102" href="#FOOT102"><sup>102</sup></a> is just one NaN
<em class="emph">float</em> value: for use with R, <code class="code">NA_REAL</code> is often what is
intended, but <code class="code">R_NaN</code> is also available.

<p>Some (but not all) extensions are listed at
<a class="uref" href="https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html">https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html</a> and
<a class="uref" href="https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Extensions.html">https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Extensions.html</a>.
</p>
<p>Other GNU extensions which have bitten package writers are the use of
non-portable characters such as &lsquo;<samp class="samp">$</samp>&rsquo; in identifiers and use of C++
headers under <samp class="file">ext</samp>.
</p>
<p>item
Including C-style headers in C++ code is not portable.  Including the
legacy header<a class="footnote" id="DOCF103" href="#FOOT103"><sup>103</sup></a> <samp class="file">math.h</samp> in C++ code may conflict with <samp class="file">cmath</samp> which
may be included by other headers.  In C++11, functions like <code class="code">sqrt</code>
and <code class="code">isnan</code> are defined for <code class="code">double</code> arguments in
<samp class="file">math.h</samp> and for a range of types including <code class="code">double</code> in
<samp class="file">cmath</samp>.  Similar issues have been seen for <samp class="file">stdlib.h</samp> and
<samp class="file">cstdlib</samp>.  Including the C++ header first used to be a sufficient
workaround but for some 2016 compilers only one could be included.
</p>
</li><li>Be careful to include the headers which define the functions you use.
Some compilers/OSes include other system headers in their headers which
are not required by the standards, and so code may compile on such
systems and not on others.  (A prominent example is the C++ header
<code class="code">&lt;random&gt;</code> which is indirectly included by <code class="code">&lt;algorithm&gt;</code> by
<code class="command">g++</code>.  Another issue is the C header <code class="code">&lt;time.h&gt;</code> which is
included by other headers on Linux and Windows but not macOS.)
<code class="command">g++</code>&nbsp;11 often needs explicit inclusion of the C++ headers
<code class="code">&lt;limits&gt;</code> (for <code class="code">numeric_limits</code>) or <code class="code">&lt;exception&gt;</code> (for
<code class="code">set_terminate</code> and similar), whereas earlier versions included
these in other headers. <code class="command">g++</code>&nbsp;13 requires the
explicit inclusion of <code class="code">&lt;cstdint&gt;</code> for types such as <code class="code">uint32_t</code>
which was previously included implicitly.  (For more such, see
<a class="uref" href="https://gcc.gnu.org/gcc-13/porting_to.html">https://gcc.gnu.org/gcc-13/porting_to.html</a>.)

<p>Note that <code class="code">malloc</code>, <code class="code">calloc</code>, <code class="code">realloc</code> and <code class="code">free</code>
are defined by C99 in the header <samp class="file">stdlib.h</samp> and (in the
<code class="code">std::</code> namespace) by C++ header <samp class="file">cstdlib</samp>.  Some earlier
implementations used a header <samp class="file">malloc.h</samp>, but that is not portable
and does not exist on macOS.
</p>
<p>This also applies to types such as <code class="code">ssize_t</code>.  The POSIX standards
say that is declared in headers <code class="code">unistd.h</code> and <code class="code">sys/types.h</code>,
and the latter is often included indirectly by other headers on some
but not all systems.
</p>
<p>Similarly for constants: for example <code class="code">SIZE_MAX</code> is defined in
<code class="code">stdint.h</code> alongside <code class="code">size_t</code>.
</p>
</li><li>Some headers are not portable: we have just mentioned <samp class="file">malloc.h</samp>
and often <abbr class="acronym">CRAN</abbr> submissions attempt to use <samp class="file">endian.h</samp>.
The latter is a <code class="code">glibc</code> extension: some OSes have
<samp class="file">machine/endian.h</samp> or <samp class="file">sys/endian.h</samp> but some have neither.

</li><li>Use <code class="code">#include &quot;my.h&quot;</code> not <code class="code">#include &lt;my.h&gt;</code> for headers in
your package.  The second form is intended for system headers and the
search order for such headers is platform-dependent (and may not include
the current directory).  For extra safety, name headers in a way that
cannot be confused with a system header so not, for example,
<samp class="file">types.h</samp>.

</li><li>For C++ code, be careful to specify namespaces where needed.  Many
functions are defined by the standards to be in the <code class="code">std</code>
namespace, but <code class="command">g++</code> puts many such also in the C++ main
namespace.  One way to do so is to use declarations such as
<div class="example">
<pre class="example-preformatted">using std::floor;
</pre></div>
<p>but it is usually preferable to use explicit namespace prefixes in the code.
</p>
<p>Examples seen in <abbr class="acronym">CRAN</abbr> packages include
</p><div class="example">
<pre class="example-preformatted">abs acos atan bind calloc ceil div exp fabs floor fmod free log malloc
memcpy memset pow printf qsort round sin sprintf sqrt strcmp strcpy
strerror strlen strncmp strtol tan trunc
</pre></div>
<p>This problem is less common than it used to be, but in 2019
LLVM <code class="command">clang</code> did not have <code class="code">bind</code> in the main namespace.  Also
seen has been type <code class="code">size_t</code> defined only in the <code class="code">std</code> namespace.
</p>
<p><strong class="strong">NB:</strong> These functions are only guaranteed to be in the
<code class="code">std</code> namespace if the correct C++ header is included, e.g.
<code class="code">&lt;cmath&gt;</code> rather than <code class="code">&lt;math.h&gt;</code>.
</p>
<p>If you define functions in C++ which are inspired by later standards, put
them in a namespace and refer to them using the namespace.  We have seen
conflicts with <code class="code">std::make_unique</code> from C++14 and <code class="code">std::byte</code>,
<code class="code">std::data</code>, <code class="code">std::sample</code> and <code class="code">std::size</code> from C++17.
</p>
</li><li>In C++ code
<div class="example">
<pre class="example-preformatted">using namesapace std; 
</pre></div>
<p>is not good practice, and has caused platform-dependent errors if
included before headers, especially system headers (which may be
included by other headers). The best practice is to use explicit
<code class="code">std::</code> prefixes for all functions declared by the C++ standard to
be in that namespace.
</p>
</li><li>Some C++ compilers refuse to compile constructs such as
<div class="example">
<pre class="example-preformatted">      if(ptr &gt; 0) { ....}
</pre></div>
<p>which compares a pointer to the integer <code class="code">0</code>.  This could just use
<code class="code">if(ptr)</code> (pointer addresses cannot be negative) but if needed
pointers can be tested against <code class="code">nullptr</code> (C++11) or <code class="code">NULL</code>.
</p>
</li><li>Macros defined by the compiler/OS can cause problems.  Identifiers
starting with an underscore followed by an upper-case letter or another
underscore are reserved for system macros and should not be used in
portable code (including not as guards in C/C++ headers).  Other macros,
typically upper-case, may be defined by the compiler or system headers
and can cause problems.
Some of these can be avoided by defining <code class="code">_POSIX_C_SOURCE</code>
before including any system headers, but it is better to only use
all-upper-case names which have a unique prefix such as the package
name.

</li><li><code class="code">typedef</code>s in OS headers can conflict with those in the package:
examples have included <code class="code">ulong</code>, <code class="code">index_t</code>, <code class="code">single</code> and
<code class="code">thread</code>.  (Note that these may conflict with other uses as
identifiers, e.g. defining a C++ function called <code class="code">single</code>.)
The POSIX standard reserves (in §2.2.2) all identifiers ending in
<code class="code">_t</code>.

</li><li>Some compilers do not allow a space between <code class="code">-D</code> and the macro to
be defined.  Similarly for <code class="code">-U</code>.

</li><li>If you use <abbr class="abbr">OpenMP</abbr>, check carefully that you have followed the advice in
the subsection on <a class="ref" href="#OpenMP-support"><abbr class="abbr">OpenMP</abbr> support</a>.  In particular, any use of
<abbr class="abbr">OpenMP</abbr> in C/C++ code will need to use
<div class="example">
<pre class="example-preformatted">#ifdef _OPENMP
# include &lt;omp.h&gt;
#endif
</pre></div>
<p>Any use of <abbr class="abbr">OpenMP</abbr> functions, e.g. <code class="code">omp_set_num_threads</code>, also
needs to be conditioned.  To avoid incessant warnings such as
</p><div class="example">
<pre class="example-preformatted">warning: ignoring #pragma omp parallel [-Wunknown-pragmas]
</pre></div>

<p>uses of such pragmas should also be conditioned (or commented out if
they are used in code in a package not enabling <abbr class="abbr">OpenMP</abbr> on any platform).
</p>
<p>Do not hardcode <samp class="option">-lgomp</samp>: not only is that specific to the
GCC family of compilers, using the correct linker flag often sets up the
run-time path to the library.
</p>
</li><li>Package authors commonly assume things are part of C/C++ when they are
not: the most common example is POSIX<a class="footnote" id="DOCF104" href="#FOOT104"><sup>104</sup></a> function
<code class="code">strdup</code>.  The most common C library on Linux, <code class="code">glibc</code>, will
hide the declarations of such extensions unless a &lsquo;feature-test macro&rsquo;
is defined <strong class="strong">before</strong> (almost) any system header is included.  So
for <code class="code">strdup</code> you need
<div class="example">
<pre class="example-preformatted">#define _POSIX_C_SOURCE 200809L
...
#include &lt;string.h&gt;
...
strdup call(s)
</pre></div>
<p>where the appropriate value can be found by <code class="command">man strdup</code> on
Linux.  (Use of <code class="code">strncasecmp</code> is similar.)
</p>
<p>However, modes of <code class="command">gcc</code> with &lsquo;GNU EXTENSIONS&rsquo; (which are the
default, either <samp class="option">-std=gnu99</samp> or <samp class="option">-std=gnu11</samp>) declare
enough macros to ensure that missing declarations are rarely seen.
</p>
<p>This applies also to constants such as <code class="code">M_PI</code> and <code class="code">M_LN2</code>,
which are part of the X/Open standard: to use these define
<code class="code">_XOPEN_SOURCE</code> before including any headers, or include the R
header <samp class="file">Rmath.h</samp>.
</p>
</li><li>Using <code class="code">alloca</code> portably is tricky: it is neither an ISO C/C++ nor a
POSIX function.  An adequately portable preamble is
<div class="example">
<pre class="example-preformatted">#ifdef __GNUC__
/* Includes GCC, clang and Intel compilers */
# undef alloca
# define alloca(x) __builtin_alloca((x))
#elif defined(__sun) || defined(_AIX)
/* this was necessary (and sufficient) for Solaris 10 and AIX 6: */
# include &lt;alloca.h&gt;
#endif
</pre></div>

</li><li>Compiler writers feel free to implement features from later standards
than the one specified, so for example they may implement or warn on
C++14/17/20 features when C++11 is specified.  Portable code will not
use such features &ndash; it can be hard to know what they are but the most
common warnings are
<div class="example">
<pre class="example-preformatted">'register' storage class specifier is deprecated and incompatible with C++17

ISO C++11 does not allow conversion from string literal to ‘char *’
</pre></div>
<p>(where conversion should be to <code class="code">const char *</code>).  Keyword
<code class="code">register</code> was not mentioned in C++98, deprecated in C++11 and
removed in C++17.
</p>
<p>There are quite a lot of other C++98 features deprecated in C++11 and
removed in C++17, and LLVM <code class="command">clang</code> 9 and later warn about them
(and as from version 16 they have been removed). Examples include
<code class="code">bind1st</code>/<code class="code">bind2nd</code> (use <code class="code">std::bind</code> or
lambdas<a class="footnote" id="DOCF105" href="#FOOT105"><sup>105</sup></a>)
<code class="code">std::auto_ptr</code> (replaced by <code class="code">std::unique_ptr</code>),
<code class="code">std::mem_fun_ref</code> and <code class="code">std::ptr_fun</code>.
</p>
</li><li>Later versions of standards may add reserved words: for example
<code class="code">bool</code>, <code class="code">false</code> and <code class="code">true</code> became keywords in C23 and are
no longer available as variable names.  As noted above, C++17 uses
<code class="code">byte</code>, <code class="code">data</code>, <code class="code">sample</code> and <code class="code">size</code>.

<p>So avoid common words and keywords from other programming languages.
</p>
</li><li>Be careful about including C headers in C++ code.  Issues include
<ul class="itemize mark-bullet">
<li>Use of the <code class="code">register</code> storage class specifier (see the previous but
one item).
</li><li>The C99 keyword <code class="code">restrict</code> is not part of<a class="footnote" id="DOCF106" href="#FOOT106"><sup>106</sup></a> any C++ standard and is rejected by some
C++ compilers.
</li><li>Inclusion by such headers of C-style headers such as <samp class="file">math.h</samp> (see above).
</li></ul>
<p>The most portable way to interface to other software with a C API is to
use C code (which can normally be mixed with C++ code in a package).
</p>
</li><li><code class="code">reinterpret_cast</code> in C++ is not safe for pointers: for example the types
may have different alignment requirements.  Use <code class="code">memcpy</code> to copy
the contents to a fresh variable of the destination type.

</li><li>Avoid platform-specific code if at all possible, but if you need to test
for a platform ensure that all platforms are covered.  For example,
<code class="code">__unix__</code> is not defined on all Unix-alikes, in particular not on
macOS.  A reasonably portable way to condition code for a Unix-alike is
<div class="example">
<pre class="example-preformatted">#if defined (__unix__) || (defined (__APPLE__) &amp;&amp; defined (__MACH__))
#endif
</pre></div>
<p>but
</p><div class="example">
<pre class="example-preformatted">#ifdef _WIN32
// Windows-specific code
# if defined(_M_ARM64) || defined(__aarch64__)
// for ARM
# else
// for Intel
# endif
#else
// Unix-alike code
#endif
</pre></div>
<p>would be better.  For a Unix-alike it is much better to use
<code class="command">configure</code> to test for the functionality needed than make
assumptions about OSes (and people all too frequently forget R is
used on platforms other than Linux, Windows and macOS &mdash; and some
forget macOS).
</p>
</li><li>Headers in subdirectories are often not portable.  For C++, this
includes <samp class="file">bits/</samp>, <samp class="file">tr1/</samp> and <samp class="file">tr2/</samp>, none of which exist
on macOS (and <samp class="file">ext/</samp> exists there but with different content from
<code class="command">g++</code>-based platforms).  Header <samp class="file">bits/stdc++.h</samp> is both not
portable and not recommended for end-user code even on platforms which
include it.

</li><li>Be careful if using <code class="code">malloc</code> or <code class="code">calloc</code>.  First, their return
value must always be checked to see if the allocation succeeded &ndash; it is
almost always easier to use R&rsquo;s <code class="code">R_Calloc</code>, which does check.
Second, the first argument is of type <code class="code">size_t</code> and recent compilers
are warning about passing signed arguments (which could get promoted to
ridiculously large values).

</li><li>For C code, consider using the flag <samp class="option">-Wstrict-prototypes</samp> which
is supported by <code class="command">gcc</code> and LLVM and Apple <code class="command">clang</code>.  This
has found quite a number of errors where functions have been declared
without arguments and is likely to become the default in future
compilers.  (It already is for LLVM <code class="command">clang</code> in C23 mode.)  Note
that using <code class="code">f()</code> for a function without any parameters was
deprecated in C99 and C11, but it expected to be non-deprecated in C23.
However, <code class="code">f(void)</code> is supported by all standards and avoids any
uncertainty.

<p>LLVM <code class="command">clang</code> has a separate warning
<samp class="option">-Wdeprecated-non-prototype</samp> which is enabled by
<samp class="option">-Wstrict-prototypes</samp>.  This warns on K&amp;R-style usage, which will
not be accepted in C23.
</p>
</li><li>Several C entry points are warned against in their <code class="command">man</code> pages
on most systems, often in very strong terms such as &rsquo;<strong class="strong">Do not use
these functions</strong>&rsquo;.  macOS has started to warn<a class="footnote" id="DOCF107" href="#FOOT107"><sup>107</sup></a> if these are used
for <code class="code">sprintf</code>, <code class="code">vsprintf</code>, <code class="code">gets</code>, <code class="code">mktemp</code>,
<code class="code">tempmam</code> and <code class="code">tmpnam</code>.  It is highly recommended that you use
safer alternatives (on any platform) but the warning can be avoided by
defining &lsquo;<samp class="samp">_POSIX_C_SOURCE</samp>&rsquo; to for example &lsquo;<samp class="samp">200809L</samp>&rsquo; before
including the (C or C++) header which defines them.  (However, this may
hide other extensions.)

</li><li>Compilers may interpret comments in source code, so it is necessary to
remove any intended for a compiler to interpret.  The main example has
been comments for Visual Fortran (as the Intel Fortran compiler has been
known on Windows<a class="footnote" id="DOCF108" href="#FOOT108"><sup>108</sup></a>) like
<div class="example">
<pre class="example-preformatted">!DEC$ ATTRIBUTES DLLEXPORT,C,REFERENCE,ALIAS:'kdenestmlcvb' :: kdenestmlcvb
</pre></div>
<p>which are interpreted by Intel Fortran on all platforms (and are
inappropriate for use with R on Windows).  <code class="command">gfortran</code> has
similar forms starting with <code class="code">!GCC$</code>.
</p>
</li><li>The C++ <code class="code">new</code> operator takes argument <code class="code">std::size_t size</code>,
which is unsigned.  Using a signed integer type such as <code class="code">int</code> may
lead to compiler warnings such as
<div class="example">
<pre class="example-preformatted">warning: argument 1 value ‘18446744073709551615’ exceeds maximum object
  size 9223372036854775807  [-Walloc-size-larger-than=]
</pre></div>
<p>(especially if <abbr class="abbr">LTO</abbr> is used).  So don&rsquo;t do that!
</p>
</li><li>Some authors feel the need to print (using <code class="code">Rprintf</code> or
similar) vector lengths or indices which are of type <code class="code">R_xlen_t</code>.
That may be a 32-bit or (most commonly) 64-bit type but which integer
type it is mapped to is platform-specific.  The safest way is to cast
the length to double and use a double format.  So one could use
something like
<div class="example">
<pre class="example-preformatted">    SEXP Robj; R_xlen_t nelem;
    error(&quot;Actual: %0.f; Expected %0.f\n&quot;, (double) XLENGTH(Robj), (double) nelem);
</pre></div>
<p>(This could print to full precision, lengths well beyond the address space
limits of current OSes, let alone practical limits.)
</p>
<p>If you do want to use an integer format, be aware that <code class="code">R_xlen_t</code>
is implemented by the <code class="code">int</code>, <code class="code">long</code> or <code class="code">long long</code> type
on current platforms and even on 64-bit ones need not be the same type
as <code class="code">int64_t</code>.
So the values will need to be cast to the type assumed by the format
(and <code class="code">%lld</code> was not supported on Windows until R&nbsp;4.2.0).
</p>
</li></ul>

<p>Some additional information for C++ is available at
<a class="uref" href="https://journal.r-project.org/archive/2011-2/RJournal_2011-2_Plummer.pdf">https://journal.r-project.org/archive/2011-2/RJournal_2011-2_Plummer.pdf</a>
by Martyn Plummer.
</p>
<ul class="mini-toc">
<li><a href="#Common-symbols" accesskey="1">Common symbols</a></li>
<li><a href="#C_002b_002b17-issues" accesskey="2">C++17 issues</a></li>
</ul>
<hr>
<div class="subsubsection-level-extent" id="Common-symbols">
<div class="nav-panel">
<p>
Next: <a href="#C_002b_002b17-issues" accesskey="n" rel="next">C++17 issues</a>, Previous: <a href="#Portable-C-and-C_002b_002b-code" accesskey="p" rel="prev">Portable C and C++ code</a>, Up: <a href="#Portable-C-and-C_002b_002b-code" accesskey="u" rel="up">Portable C and C++ code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsubsection" id="Common-symbols-1"><span>1.6.4.1 Common symbols<a class="copiable-link" href="#Common-symbols-1"> &para;</a></span></h4>

<p>Most OSes (including all those commonly used for R) have the concept
of &lsquo;tentative definitions&rsquo; where global C variables are defined without
an initializer.  Traditionally the linker resolves all tentative
definitions of the same variable in different object files to the same
object, or to a non-tentative definition.  However,
<code class="command">gcc</code>&nbsp;10<a class="footnote" id="DOCF109" href="#FOOT109"><sup>109</sup></a> and
LLVM <code class="command">clang</code>&nbsp;11<a class="footnote" id="DOCF110" href="#FOOT110"><sup>110</sup></a>
changed their default so that tentative definitions cannot be
merged and the linker will give an error if the same variable is defined
in more than one object file.  To avoid this, all but one of the C
source files should declare the variable <code class="code">extern</code> &mdash; which means
that any such variables included in header files need to be declared
<code class="code">extern</code>.  A commonly used idiom (including by R itself) is to
define all global variables as <code class="code">extern</code> in a header, say
<samp class="file">globals.h</samp> (and nowhere else), and then in one (and one only)
source file use
</p><div class="example">
<pre class="example-preformatted">#define extern
# include &quot;globals.h&quot;
#undef extern
</pre></div>

<p>A cleaner approach is not to have global variables at all, but to place
in a single file common variables (declared <code class="code">static</code>) followed by
all the functions which make use of them: this may result in more
efficient code.
</p>
<p>The &lsquo;modern&rsquo; behaviour can be seen<a class="footnote" id="DOCF111" href="#FOOT111"><sup>111</sup></a> by using
compiler flag <samp class="option">-fno-common</samp> as part of &lsquo;<samp class="samp">CFLAGS</samp>&rsquo; in earlier
versions of <code class="command">gcc</code> and <code class="command">clang</code>.
</p>
<p><samp class="option">-fno-common</samp> is said to be particularly beneficial for ARM CPUs.
</p>
<p>This is not pertinent to C++ which does not permit tentative definitions.
</p>
<hr>
</div>
<div class="subsubsection-level-extent" id="C_002b_002b17-issues">
<div class="nav-panel">
<p>
Previous: <a href="#Common-symbols" accesskey="p" rel="prev">Common symbols</a>, Up: <a href="#Portable-C-and-C_002b_002b-code" accesskey="u" rel="up">Portable C and C++ code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsubsection" id="C_002b_002b17-issues-1"><span>1.6.4.2 C++17 issues<a class="copiable-link" href="#C_002b_002b17-issues-1"> &para;</a></span></h4>

<p>R 4.3.0 and later default to C++17 when compiling C++, and that
finally removed many C++98 features which were deprecated as long ago as
C++11.  Compiler/runtime authors have been slow to remove these, but
LLVM <code class="command">clang</code> with its <code class="code">libc++</code> runtime library finally
started to do so in 2023 &ndash; some others warn but some do not.
</p>
<p>The principal offender is the &lsquo;Boost&rsquo; collection of C++ headers and
libraries.  There are two little-documented ways to work around aspects
of its outdated code.  One is to add
</p><div class="example">
<pre class="example-preformatted">-D_HAS_AUTO_PTR_ETC=0
</pre></div>
<p>to <code class="code">PKG_CPPLAGS</code> in <samp class="file">src/Makevars</samp>, <samp class="file">src/Makevars.win</samp>
and <samp class="file">src/Makevars.ucrt</samp>.  This covers
the removal of
</p><div class="example">
<pre class="example-preformatted">std::auto_ptr
std::unary_function
std::binary_function
std::random_shuffle
std::binder1st
std::binder2nd
</pre></div>
<p>with most issues seen with code that includes <samp class="file">boost/functional.hpp</samp>,
usually indirectly.
</p>
<p>A rarer issue is the use of illegal values for <code class="code">enum</code> types,
usually negative ones such as
</p><div class="example">
<pre class="example-preformatted">BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (value - 1));
</pre></div>
<p>in <samp class="file">boost/mpl/aux_/integral_wrapper.hpp</samp>.  Adding
</p><div class="example">
<pre class="example-preformatted"> -Wno-error=enum-constexpr-conversion
</pre></div>
<p>to <code class="code">PKG_CXXFLAGS</code> will allow this, but that flag is only accepted
by recent versions of LLVM <code class="command">clang</code> (and will not be in future)
so needs a <code class="command">configure</code> test.
</p>
<p>Pre=built versions of current <code class="command">clang</code>/<code class="code">libc++</code> are
usually available from
<a class="uref" href="https://github.com/llvm/llvm-project/releases">https://github.com/llvm/llvm-project/releases</a> for a wide range of
platforms (but the Windows builds there are not compatible with
<code class="code">Rtools</code> and the macOS ones are unsigned).  To select
<code class="code">libc++</code> add <samp class="option">-stdlib=libc++</samp> to <code class="code">CXX</code>, for example
by having
</p><div class="example">
<pre class="example-preformatted">CXX=&quot;/path/to/clang/clang++ -std=gnu++17 -stdlib=libc++&quot;
</pre></div>
<p>in <samp class="file">~/.R/Makevars</samp>.
</p>
<p>Another build for Windows which may be sufficiently compatible with
<code class="code">Rtools</code> can be found at
<a class="uref" href="https://github.com/mstorsjo/llvm-mingw">https://github.com/mstorsjo/llvm-mingw</a>: this uses <code class="code">libc++</code>.
</p>
<hr>
</div>
</div>
<div class="subsection-level-extent" id="Portable-Fortran-code">
<div class="nav-panel">
<p>
Next: <a href="#Binary-distribution" accesskey="n" rel="next">Binary distribution</a>, Previous: <a href="#Portable-C-and-C_002b_002b-code" accesskey="p" rel="prev">Portable C and C++ code</a>, Up: <a href="#Writing-portable-packages" accesskey="u" rel="up">Writing portable packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Portable-Fortran-code-1"><span>1.6.5 Portable Fortran code<a class="copiable-link" href="#Portable-Fortran-code-1"> &para;</a></span></h4>

<p>For many years almost all known R platforms used <code class="command">gfortran</code>
as their Fortran compiler, but now there are LLVM and &lsquo;classic&rsquo;
<code class="command">flang</code> and the Intel compilers
<code class="command">ifort</code><a class="footnote" id="DOCF112" href="#FOOT112"><sup>112</sup></a> and <code class="command">ifx</code> are now
free-of-change.
</p>
<p>There is still a lot of Fortran code in <abbr class="acronym">CRAN</abbr> packages which
predates Fortran 77.  Modern Fortran compilers are being written to
target a minimum standard of Fortran 2018. and it is desirable that
Fortran code in packages complies with that standard.  For
<code class="command">gfortran</code> this can be checked by adding <samp class="option">-std=f2018</samp> to
<code class="code">FFLAGS</code>.  The most commonly seen issues are
</p>
<ul class="itemize mark-bullet">
<li>The use of <code class="code">DFLOAT</code>, which was superseded by <code class="code">DBLE</code> in Fortran
77.  Also, use of <code class="code">DCMPLX</code>, <code class="code">DCONJG</code>, <code class="code">DIMAG</code> and
similar.

</li><li>The use of GNU Fortran extensions.  Some are listed at
<a class="uref" href="https://gcc.gnu.org/onlinedocs/gfortran/Extensions-implemented-in-GNU-Fortran.html">https://gcc.gnu.org/onlinedocs/gfortran/Extensions-implemented-in-GNU-Fortran.html</a>.
Others which have caused problems include <code class="code">etime</code>, <code class="code">getpid</code>,
<code class="code">isnan</code><a class="footnote" id="DOCF113" href="#FOOT113"><sup>113</sup></a> and <code class="code">sizeof</code>.

<p>One that frequently catches package writers is that it allows
out-of-order declarations: in standard-conformant Fortran variables must
be declared (explicitly or implicitly) before use in other declarations
such as dimensions.
</p>
</li></ul>
<p>Unfortunately this flags extensions such as <code class="code">DOUBLE COMPLEX</code> and
<code class="code">COMPLEX*16</code>.  R has tested that <code class="code">DOUBLE COMPLEX</code> works and
so is preferred to <code class="code">COMPLEX*16</code>.  (One can also use something like
<code class="code">COMPLEX(KIND=KIND(0.0D0))</code>.)
</p>
<p>GNU Fortran 10 and later give a compilation error for the previously
widespread practice of passing a Fortran array element where an array is
expected, or a scalar instead of a length-one array.  See
<a class="uref" href="https://gcc.gnu.org/gcc-10/porting_to.html">https://gcc.gnu.org/gcc-10/porting_to.html</a>.  As do the Intel
Fortran compilers, and they can be stricter.
</p>
<p>The use of <code class="code">IMPLICIT NONE</code> is highly recommended &ndash; Intel compilers
with <samp class="option">-warn</samp> will warn on variables without an explicit type.
</p>
<p>Common non-portable constructions include
</p><ul class="itemize mark-bullet">
<li>The use of Fortran types such as <code class="code">REAL(KIND=8)</code> is very far from
portable.  According to the standards this merely enumerates different
supported types, so <code class="code">DOUBLE PRECISION</code> might be <code class="code">REAL(KIND=3)</code>
(and is on an actual compiler).  Even if for a particular compiler the
value indicates the size in bytes, which values are supported is
platform-specific &mdash; for example <code class="command">gfortran</code> supports values of 4
and 8 on all current platforms and 10 and 16 on a few (but not for
example on all &lsquo;<samp class="samp">arm</samp>&rsquo; CPUs).

<p>The same applies to <code class="code">INTEGER(KIND=4)</code> and <code class="code">COMPLEX(KIND=16)</code>.
</p>
<p>Many uses of integer and real variable in Fortran code in packages will
interwork with C (for example <code class="code">.Fortran</code> is written in C), and R
has checked that <code class="code">INTEGER</code> and <code class="code">DOUBLE PRECISION</code> correspond to
the C types <code class="code">int</code> and <code class="code">double</code>.  To make this explicit, from
Fortran 2003 one can use the named constants <code class="code">c_int</code>,
<code class="code">c_double</code> and <code class="code">c_double_complex</code> from module
<code class="code">iso_c_binding</code>.
</p>
</li><li>The Intel compilers only recognize the extensions <samp class="file">.f</samp> (fixed-form)
and <samp class="file">.f90</samp> (free-form) and not <samp class="file">.f95</samp>. <code class="command">R CMD INSTALL</code>
works around this for packages without a <samp class="file">src/Makefile</samp>.

</li><li>Use of extensions <samp class="file">.F</samp> and <code class="code">.F90</code> to indicate source code to
be preprocessed: the preprocessor used is compiler-specific and may or
may not be <code class="command">cpp</code>.

</li><li>Fixed form Fortran (with extension <samp class="file">.f</samp>) should only use 72
columns, and free-form at most 132 columns.  This includes trailing
comments.  Over-long lines may be silently truncated or give a warning.
%% The Intel compilers warn.

</li></ul>


<hr>
</div>
<div class="subsection-level-extent" id="Binary-distribution">
<div class="nav-panel">
<p>
Previous: <a href="#Portable-Fortran-code" accesskey="p" rel="prev">Portable Fortran code</a>, Up: <a href="#Writing-portable-packages" accesskey="u" rel="up">Writing portable packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Binary-distribution-1"><span>1.6.6 Binary distribution<a class="copiable-link" href="#Binary-distribution-1"> &para;</a></span></h4>

<p>If you want to distribute a binary version of a package on Windows or
macOS, there are further checks you need to do to check it is portable:
it is all too easy to depend on external software on your own machine
that other users will not have.
</p>
<p>For Windows, check what other DLLs your package&rsquo;s DLL depends on
(&lsquo;imports&rsquo; from in the DLL tools&rsquo; parlance).  A convenient GUI-based
tool to do so is &lsquo;Dependency Walker&rsquo;
(<a class="uref" href="https://www.dependencywalker.com/">https://www.dependencywalker.com/</a>) for both 32-bit and 64-bit
DLLs &ndash; note that this will report as missing links to R&rsquo;s own DLLs
such as <samp class="file">R.dll</samp> and <samp class="file">Rblas.dll</samp>.  The command-line tool
<code class="command">objdump</code> in the appropriate toolchain will also reveal what
DLLs are imported from.  If you use a toolchain other than one provided
by the R developers or use your own makefiles, watch out in
particular for dependencies on the toolchain&rsquo;s runtime DLLs such as
<samp class="file">libgfortran</samp>, <samp class="file">libstdc++</samp> and <samp class="file">libgcc_s</samp>.
</p>
<p>For macOS, using <code class="code">R CMD otool -L</code> on the package&rsquo;s shared object(s)
in the <samp class="file">libs</samp> directory will show what they depend on: watch for
any dependencies in <samp class="file">/usr/local/lib</samp> or
<samp class="file">/usr/local/gfortran/lib</samp>, notably <samp class="file">libgfortran.?.dylib</samp> and
<samp class="file">libquadmath.0.dylib</samp>.
(For ways to fix these,
see <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Building-binary-packages">Building binary-packages</a> in <cite class="cite">R Installation and Administration</cite>.)
</p>
<p>Many people (including the <abbr class="acronym">CRAN</abbr> package repository) will not
accept source packages containing binary files as the latter are a
security risk.  If you want to distribute a source package which needs
external software on Windows or macOS, options include
</p><ul class="itemize mark-bullet">
<li>To arrange for installation of the package to download the additional
software from a URL, as e.g. package <a class="url" href="https://CRAN.R-project.org/package=Cairo"><strong class="strong">Cairo</strong></a> used to.

</li><li>To negotiate with Tomas Kalibera to include Windows software in
<code class="code">Rtools</code> or with Simon Urbanek to include macOS software in his
&lsquo;recipes&rsquo; system.

</li><li>(For <abbr class="acronym">CRAN</abbr>.)
To negotiate with Uwe Ligges to host the additional components on
WinBuilder, and write a <samp class="file">configure.win</samp> file to install them.

</li></ul>

<p>Be aware that license requirements you may require you to supply the
sources for the additional components (and will if your package has a
GPL-like license).
</p>

<hr>
</div>
</div>
<div class="section-level-extent" id="Diagnostic-messages">
<div class="nav-panel">
<p>
Next: <a href="#Internationalization" accesskey="n" rel="next">Internationalization</a>, Previous: <a href="#Writing-portable-packages" accesskey="p" rel="prev">Writing portable packages</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Diagnostic-messages-1"><span>1.7 Diagnostic messages<a class="copiable-link" href="#Diagnostic-messages-1"> &para;</a></span></h3>

<p>Diagnostic messages can be made available for translation, so it is
important to write them in a consistent style.  Using the tools
described in the next section to extract all the messages can give a
useful overview of your consistency (or lack of it).
Some guidelines follow.
</p>
<ul class="itemize mark-bullet">
<li>Messages are sentence fragments, and not viewed in isolation.  So it is
conventional not to capitalize the first word and not to end with a
period (or other punctuation).

</li><li>Try not to split up messages into small pieces.  In C error messages use
a single format string containing all English words in the messages.

<p>In R error messages do not construct a message with <code class="code">paste</code> (such
messages will not be translated) but <em class="emph">via</em> multiple arguments to
<code class="code">stop</code> or <code class="code">warning</code>, or <em class="emph">via</em> <code class="code">gettextf</code>.
</p>
</li><li>Do not use colloquialisms such as &ldquo;can&rsquo;t&rdquo; and &ldquo;don&rsquo;t&rdquo;.

</li><li>Conventionally single quotation marks are used for quotations such as

<div class="example">
<pre class="example-preformatted">'ord' must be a positive integer, at most the number of knots
</pre></div>

<p>and double quotation marks when referring to an R character string or
a class, such as
</p>
<div class="example">
<pre class="example-preformatted">'format' must be &quot;normal&quot; or &quot;short&quot; - using &quot;normal&quot;
</pre></div>

<p>Since <abbr class="acronym">ASCII</abbr> does not contain directional quotation marks, it
is best to use &lsquo;<samp class="samp">'</samp>&rsquo; and let the translator (including automatic
translation) use directional quotations where available.  The range of
quotation styles is immense: unfortunately we cannot reproduce them in a
portable <code class="code">texinfo</code> document.  But as a taster, some languages use
&lsquo;up&rsquo; and &lsquo;down&rsquo; (comma) quotes rather than left or right quotes, and
some use guillemets (and some use what Adobe calls &lsquo;guillemotleft&rsquo; to
start and others use it to end).
</p>
<p>In R messages it is also possible to use <code class="code">sQuote</code> or <code class="code">dQuote</code> as in
</p>
<div class="example">
<pre class="example-preformatted">        stop(gettextf(&quot;object must be of class %s or %s&quot;,
                      dQuote(&quot;manova&quot;), dQuote(&quot;maov&quot;)),
             domain = NA)
</pre></div>

</li><li>Occasionally messages need to be singular or plural (and in other
languages there may be no such concept or several plural forms &ndash;
Slovenian has four).  So avoid constructions such as was once used in
<code class="code">library</code>

<div class="example">
<pre class="example-preformatted">if((length(nopkgs) &gt; 0) &amp;&amp; !missing(lib.loc)) {
    if(length(nopkgs) &gt; 1)
        warning(&quot;libraries &quot;,
                paste(sQuote(nopkgs), collapse = &quot;, &quot;),
                &quot; contain no packages&quot;)
    else
        warning(&quot;library &quot;, paste(sQuote(nopkgs)),
                &quot; contains no package&quot;)
}
</pre></div>

<p>and was replaced by
</p>
<div class="example">
<pre class="example-preformatted">if((length(nopkgs) &gt; 0) &amp;&amp; !missing(lib.loc)) {
    pkglist &lt;- paste(sQuote(nopkgs), collapse = &quot;, &quot;)
    msg &lt;- sprintf(ngettext(length(nopkgs),
                            &quot;library %s contains no packages&quot;,
                            &quot;libraries %s contain no packages&quot;,
                            domain = &quot;R-base&quot;),
                   pkglist)
    warning(msg, domain=NA)
}
</pre></div>

<p>Note that it is much better to have complete clauses as here, since
in another language one might need to say
&lsquo;There is no package in library %s&rsquo; or
&lsquo;There are no packages in libraries %s&rsquo;.
</p>
</li></ul>

<hr>
</div>
<div class="section-level-extent" id="Internationalization">
<div class="nav-panel">
<p>
Next: <a href="#CITATION-files" accesskey="n" rel="next">CITATION files</a>, Previous: <a href="#Diagnostic-messages" accesskey="p" rel="prev">Diagnostic messages</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Internationalization-1"><span>1.8 Internationalization<a class="copiable-link" href="#Internationalization-1"> &para;</a></span></h3>

<p>There are mechanisms to translate the R- and C-level error and warning
messages.  There are only available if R is compiled with <abbr class="abbr">NLS</abbr> support
(which is requested by <code class="command">configure</code> option <samp class="option">--enable-nls</samp>,
the default).
</p>
<p>The procedures make use of <code class="code">msgfmt</code> and <code class="code">xgettext</code> which are
part of <abbr class="acronym">GNU</abbr> <code class="code">gettext</code> and this will need to be installed:
&lsquo;<samp class="samp">x86_64</samp>&rsquo; Windows users can find pre-compiled binaries at
<a class="uref" href="https://www.stats.ox.ac.uk/pub/Rtools/goodies/gettext-tools.zip">https://www.stats.ox.ac.uk/pub/Rtools/goodies/gettext-tools.zip</a>.
</p>

<ul class="mini-toc">
<li><a href="#C_002dlevel-messages" accesskey="1">C-level messages</a></li>
<li><a href="#R-messages" accesskey="2">R messages</a></li>
<li><a href="#Preparing-translations" accesskey="3">Preparing translations</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="C_002dlevel-messages">
<div class="nav-panel">
<p>
Next: <a href="#R-messages" accesskey="n" rel="next">R messages</a>, Previous: <a href="#Internationalization" accesskey="p" rel="prev">Internationalization</a>, Up: <a href="#Internationalization" accesskey="u" rel="up">Internationalization</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="C_002dlevel-messages-1"><span>1.8.1 C-level messages<a class="copiable-link" href="#C_002dlevel-messages-1"> &para;</a></span></h4>

<p>The process of enabling translations is
</p>
<ul class="itemize mark-bullet">
<li>In a header file that will be included in all the C (or C++ or Objective
C/C++) files containing messages that should be translated, declare

<div class="example">
<pre class="example-preformatted">#include &lt;R.h&gt;  /* to include Rconfig.h */

#ifdef ENABLE_NLS
#include &lt;libintl.h&gt;
#define _(String) dgettext (&quot;<var class="var">pkg</var>&quot;, String)
/* replace <var class="var">pkg</var> as appropriate */
#else
#define _(String) (String)
#endif
</pre></div>

</li><li>For each message that should be translated, wrap it in <code class="code">_(...)</code>,
for example

<div class="example">
<pre class="example-preformatted">error(_(&quot;'ord' must be a positive integer&quot;));
</pre></div>

<p>If you want to use different messages for singular and plural forms, you
need to add
</p>
<div class="example">
<pre class="example-preformatted">#ifndef ENABLE_NLS
#define dngettext(pkg, String, StringP, N) (N == 1 ? String : StringP)
#endif
</pre></div>

<p>and mark strings by
</p>
<div class="example">
<pre class="example-preformatted">dngettext(&quot;<var class="var">pkg</var>&quot;, <var class="var">&lt;singular string&gt;</var>, <var class="var">&lt;plural string&gt;</var>, n)
</pre></div>

</li><li>In the package&rsquo;s <samp class="file">src</samp> directory run

<div class="example">
<pre class="example-preformatted">xgettext --keyword=_ -o <var class="var">pkg</var>.pot *.c
</pre></div>

</li></ul>

<p>The file <samp class="file">src/<var class="var">pkg</var>.pot</samp> is the template file, and
conventionally this is shipped as <samp class="file">po/<var class="var">pkg</var>.pot</samp>.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="R-messages">
<div class="nav-panel">
<p>
Next: <a href="#Preparing-translations" accesskey="n" rel="next">Preparing translations</a>, Previous: <a href="#C_002dlevel-messages" accesskey="p" rel="prev">C-level messages</a>, Up: <a href="#Internationalization" accesskey="u" rel="up">Internationalization</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="R-messages-1"><span>1.8.2 R messages<a class="copiable-link" href="#R-messages-1"> &para;</a></span></h4>

<p>Mechanisms are also available to support the automatic translation of
R <code class="code">stop</code>, <code class="code">warning</code> and <code class="code">message</code> messages.  They make
use of message catalogs in the same way as C-level messages, but using
domain <code class="code">R-<var class="var">pkg</var></code> rather than <code class="code"><var class="var">pkg</var></code>.  Translation of
character strings inside <code class="code">stop</code>, <code class="code">warning</code> and <code class="code">message</code>
calls is automatically enabled, as well as other messages enclosed in
calls to <code class="code">gettext</code> or <code class="code">gettextf</code>.  (To suppress this, use
argument <code class="code">domain=NA</code>.)
</p>
<p>Tools to prepare the <samp class="file">R-<var class="var">pkg</var>.pot</samp> file are provided in package
<strong class="strong">tools</strong>: <code class="code">xgettext2pot</code> will prepare a file from all strings
occurring inside <code class="code">gettext</code>/<code class="code">gettextf</code>, <code class="code">stop</code>,
<code class="code">warning</code> and <code class="code">message</code> calls.  Some of these are likely to be
spurious and so the file is likely to need manual editing.
<code class="code">xgettext</code> extracts the actual calls and so is more useful when
tidying up error messages.
</p>
<p>The R function <code class="code">ngettext</code> provides an interface to the C
function of the same name: see example in the previous section.  It is
safest to use <code class="code">domain=&quot;R-<var class="var">pkg</var>&quot;</code> explicitly in calls to
<code class="code">ngettext</code>, and necessary for earlier versions of R unless they
are calls directly from a function in the package.
</p>

<hr>
</div>
<div class="subsection-level-extent" id="Preparing-translations">
<div class="nav-panel">
<p>
Previous: <a href="#R-messages" accesskey="p" rel="prev">R messages</a>, Up: <a href="#Internationalization" accesskey="u" rel="up">Internationalization</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Preparing-translations-1"><span>1.8.3 Preparing translations<a class="copiable-link" href="#Preparing-translations-1"> &para;</a></span></h4>

<p>Once the template files have been created, translations can be made.
Conventional translations have file extension <samp class="file">.po</samp> and are placed
in the <samp class="file">po</samp> subdirectory of the package with a name that is either
&lsquo;<samp class="samp"><var class="var">ll</var>.po</samp>&rsquo; or &lsquo;<samp class="samp">R-<var class="var">ll</var>.po</samp>&rsquo; for translations of the C and R
messages respectively to language with code &lsquo;<samp class="samp"><var class="var">ll</var></samp>&rsquo;.
</p>
<p>See <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Localization-of-messages">Localization of messages</a> in <cite class="cite">R Installation and Administration</cite>, for details of language codes.
</p>
<p>There is an R function, <code class="code">update_pkg_po</code> in package <strong class="strong">tools</strong>,
to automate much of the maintenance of message translations.  See its
help for what it does in detail.
</p>
<p>If this is called on a package with no existing translations, it creates
the directory <samp class="file"><var class="var">pkgdir</var>/po</samp>, creates a template file of R
messages, <samp class="file"><var class="var">pkgdir</var>/po/R-<var class="var">pkg</var>.pot</samp>, within it, creates the
&lsquo;<samp class="samp">en@quot</samp>&rsquo; translation and installs that.  (The &lsquo;<samp class="samp">en@quot</samp>&rsquo;
pseudo-language interprets quotes in their directional forms in suitable
(e.g. UTF-8) locales.)
</p>
<p>If the package has C source files in its <samp class="file">src</samp> directory
that are marked for translation, use
</p>
<div class="example">
<pre class="example-preformatted">touch <var class="var">pkgdir</var>/po/<var class="var">pkg</var>.pot
</pre></div>

<p>to create a dummy template file, then call <code class="code">update_pkg_po</code> again
(this can also be done before it is called for the first time).
</p>
<p>When translations to new languages are added in the <samp class="file"><var class="var">pkgdir</var>/po</samp>
directory, running the same command will check and then
install the translations.
</p>
<p>If the package sources are updated, the same command will update the
template files, merge the changes into the translation <samp class="file">.po</samp> files
and then installed the updated translations.  You will often see that
merging marks translations as &lsquo;fuzzy&rsquo; and this is reported in the
coverage statistics.  As fuzzy translations are <em class="emph">not</em> used, this is
an indication that the translation files need human attention.
</p>
<p>The merged translations are run through <code class="code">tools::checkPofile</code> to
check that C-style formats are used correctly: if not the mismatches are
reported and the broken translations are not installed.
</p>
<p>This function needs the GNU <code class="command">gettext-tools</code> installed and on the
path: see its help page.
</p>

<a class="index-entry-id" id="index-CITATION-1"></a>
<a class="index-entry-id" id="index-citation-1"></a>
<hr>
</div>
</div>
<div class="section-level-extent" id="CITATION-files">
<div class="nav-panel">
<p>
Next: <a href="#Package-types" accesskey="n" rel="next">Package types</a>, Previous: <a href="#Internationalization" accesskey="p" rel="prev">Internationalization</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="CITATION-files-1"><span>1.9 CITATION files<a class="copiable-link" href="#CITATION-files-1"> &para;</a></span></h3>

<p>An installed file named <samp class="file">CITATION</samp> will be used by the
<code class="code">citation()</code> function.  (It should be in the <samp class="file">inst</samp>
subdirectory of the package sources.)
</p>
<p>The <samp class="file">CITATION</samp> file is parsed as R code (in the package&rsquo;s
declared encoding, or in <abbr class="acronym">ASCII</abbr> if none is declared).
It will contain calls to function <code class="code">bibentry</code>.
Here is that for <a class="url" href="https://CRAN.R-project.org/package=nlme"><strong class="strong">nlme</strong></a>:
</p>
<div class="example">
<pre class="example-preformatted">## R package reference generated from DESCRIPTION metadata
citation(auto = meta)

## NLME book
bibentry(bibtype = &quot;Book&quot;,
         title = &quot;Mixed-Effects Models in S and S-PLUS&quot;,
         author = c(person(c(&quot;Jos&eacute;&quot;, &quot;C.&quot;), &quot;Pinheiro&quot;),
                    person(c(&quot;Douglas&quot;, &quot;M.&quot;), &quot;Bates&quot;)),
         year = &quot;2000&quot;, publisher = &quot;Springer&quot;, address = &quot;New York&quot;,
         doi = &quot;10.1007/b98882&quot;)
</pre></div>

<p>Note how the first call auto-generates citation information
from object <code class="code">meta</code>, a parsed version of the <samp class="file">DESCRIPTION</samp> file
&ndash; it is tempting to hardcode such information, but it normally then
gets outdated.  How the first entry would look like as a <code class="code">bibentry</code>
call can be seen from
<code class="code">print(citation(&quot;<var class="var">pkgname</var>&quot;, auto = TRUE), style = &quot;R&quot;)</code>
for any installed package.  Auto-generated information is
returned by default if no <samp class="file">CITATION</samp> file is present.
</p>
<p>See <code class="code">?bibentry</code> for further details of the
information which can be provided.
In case a bibentry contains LaTeX markup (e.g., for accented
characters or mathematical symbols), it may be necessary to provide a
text representation to be used for printing <em class="emph">via</em> the
<code class="code">textVersion</code> argument to <code class="code">bibentry</code>.  E.g., earlier versions
of <a class="url" href="https://CRAN.R-project.org/package=nlme"><strong class="strong">nlme</strong></a> additionally used something like
</p>
<div class="example">
<pre class="example-preformatted">         textVersion =
         paste0(&quot;Jose Pinheiro, Douglas Bates, Saikat DebRoy, &quot;,
                &quot;Deepayan Sarkar and the R Core Team (&quot;,
                sub(&quot;-.*&quot;, &quot;&quot;, meta$Date),
                &quot;). nlme: Linear and Nonlinear Mixed Effects Models. &quot;,
                sprintf(&quot;R package version %s&quot;, meta$Version), &quot;.&quot;)
</pre></div>

<p>The <samp class="file">CITATION</samp> file should itself produce no output when
<code class="code">source</code>-d.
</p>
<p>It is desirable (and essential for <abbr class="acronym">CRAN</abbr>) that the
<samp class="file">CITATION</samp> file does not contain calls to functions such as
<code class="code">packageDescription</code> which assume the package is installed in a
library tree on the package search path.
</p>
<hr>
</div>
<div class="section-level-extent" id="Package-types">
<div class="nav-panel">
<p>
Next: <a href="#Services" accesskey="n" rel="next">Services</a>, Previous: <a href="#CITATION-files" accesskey="p" rel="prev">CITATION files</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Package-types-1"><span>1.10 Package types<a class="copiable-link" href="#Package-types-1"> &para;</a></span></h3>

<p>The <samp class="file">DESCRIPTION</samp> file has an optional field <code class="code">Type</code> which if
missing is assumed to be &lsquo;<samp class="samp">Package</samp>&rsquo;, the sort of extension discussed
so far in this chapter.  Currently one other type is recognized; there
used also to be a &lsquo;<samp class="samp">Translation</samp>&rsquo; type.
</p>

<ul class="mini-toc">
<li><a href="#Frontend" accesskey="1">Frontend</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Frontend">
<div class="nav-panel">
<p>
Previous: <a href="#Package-types" accesskey="p" rel="prev">Package types</a>, Up: <a href="#Package-types" accesskey="u" rel="up">Package types</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Frontend-1"><span>1.10.1 Frontend<a class="copiable-link" href="#Frontend-1"> &para;</a></span></h4>

<p>This is a rather general mechanism, designed for adding new front-ends
such as the former <strong class="strong">gnomeGUI</strong> package (see the <samp class="file">Archive</samp> area on
<abbr class="acronym">CRAN</abbr>).  If a <samp class="file">configure</samp> file is found in the top-level
directory of the package it is executed, and then if a <samp class="file">Makefile</samp>
is found (often generated by <samp class="file">configure</samp>), <code class="code">make</code> is called.
If <code class="code">R CMD INSTALL --clean</code> is used <code class="code">make clean</code> is called.  No
other action is taken.
</p>
<p><code class="code">R CMD build</code> can package up this type of extension, but <code class="code">R
CMD check</code> will check the type and skip it.
</p>
<p>Many packages of this type need write permission for the R
installation directory.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Services">
<div class="nav-panel">
<p>
Previous: <a href="#Package-types" accesskey="p" rel="prev">Package types</a>, Up: <a href="#Creating-R-packages" accesskey="u" rel="up">Creating R packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Services-1"><span>1.11 Services<a class="copiable-link" href="#Services-1"> &para;</a></span></h3>

<p>Several members of the R project have set up services to assist those
writing R packages, particularly those intended for public
distribution.
</p>
<p><a class="uref" href="https://win-builder.r-project.org">win-builder.r-project.org</a>
offers the automated preparation of (&lsquo;<samp class="samp">x86_64</samp>&rsquo;) Windows binaries from
well-tested source packages.
</p>
<p>R-Forge (<a class="uref" href="https://R-Forge.r-project.org">R-Forge.r-project.org</a>) and
RForge (<a class="uref" href="https://www.rforge.net">www.rforge.net</a>) are similar
services with similar names.  Both provide source-code management
through SVN, daily building and checking, mailing lists and a repository
that can be accessed <em class="emph">via</em> <code class="code">install.packages</code> (they can be
selected by <code class="code">setRepositories</code> and the GUI menus that use it).
Package developers have the opportunity to present their work on the
basis of project websites or news announcements.  Mailing lists, forums
or wikis provide useRs with convenient instruments for discussions and
for exchanging information between developers and/or interested useRs.
</p>

<hr>
</div>
</div>
<div class="chapter-level-extent" id="Writing-R-documentation-files">
<div class="nav-panel">
<p>
Next: <a href="#Tidying-and-profiling-R-code" accesskey="n" rel="next">Tidying and profiling R code</a>, Previous: <a href="#Creating-R-packages" accesskey="p" rel="prev">Creating R packages</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="chapter" id="Writing-R-documentation-files-1"><span>2 Writing R documentation files<a class="copiable-link" href="#Writing-R-documentation-files-1"> &para;</a></span></h2>
<a class="index-entry-id" id="index-Documentation_002c-writing"></a>


<ul class="mini-toc">
<li><a href="#Rd-format" accesskey="1">Rd format</a></li>
<li><a href="#Sectioning" accesskey="2">Sectioning</a></li>
<li><a href="#Marking-text" accesskey="3">Marking text</a></li>
<li><a href="#Lists-and-tables" accesskey="4">Lists and tables</a></li>
<li><a href="#Cross_002dreferences" accesskey="5">Cross-references</a></li>
<li><a href="#Mathematics" accesskey="6">Mathematics</a></li>
<li><a href="#Figures" accesskey="7">Figures</a></li>
<li><a href="#Insertions" accesskey="8">Insertions</a></li>
<li><a href="#Indices" accesskey="9">Indices</a></li>
<li><a href="#Platform_002dspecific-sections">Platform-specific documentation</a></li>
<li><a href="#Conditional-text">Conditional text</a></li>
<li><a href="#Dynamic-pages">Dynamic pages</a></li>
<li><a href="#User_002ddefined-macros">User-defined macros</a></li>
<li><a href="#Encoding">Encoding</a></li>
<li><a href="#Processing-documentation-files">Processing documentation files</a></li>
<li><a href="#Editing-Rd-files">Editing Rd files</a></li>
</ul>
<hr>
<div class="section-level-extent" id="Rd-format">
<div class="nav-panel">
<p>
Next: <a href="#Sectioning" accesskey="n" rel="next">Sectioning</a>, Previous: <a href="#Writing-R-documentation-files" accesskey="p" rel="prev">Writing R documentation files</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Rd-format-1"><span>2.1 Rd format<a class="copiable-link" href="#Rd-format-1"> &para;</a></span></h3>

<p>R objects are documented in files written in &ldquo;R documentation&rdquo;
(Rd) format, a simple markup language much of which closely resembles
(La)TeX, which can be processed into a variety of formats,
including LaTeX, <abbr class="acronym">HTML</abbr> and plain text.  The translation is
carried out by functions in the <strong class="strong">tools</strong> package called by the
script <code class="command">Rdconv</code> in <samp class="file"><var class="var">R_HOME</var>/bin</samp> and by the
installation scripts for packages.
</p>
<p>The R distribution contains more than 1400 such files which can be
found in the <samp class="file">src/library/<var class="var">pkg</var>/man</samp> directories of the R
source tree, where <var class="var">pkg</var> stands for one of the standard packages
which are included in the R distribution.
</p>
<p>As an example, let us look at a simplified version of
<samp class="file">src/library/base/man/load.Rd</samp> which documents the R function
<code class="code">load</code>.
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example smallexample">
<pre class="example-preformatted">% File src/library/base/man/load.Rd
\name{load}
\alias{load}
\title{Reload Saved Datasets}
\description{
  Reload datasets written with the function \code{save}.
}
\usage{
load(file, envir = parent.frame(), verbose = FALSE)
}
\arguments{
  \item{file}{a (readable binary-mode) \link{connection}
    or a character string giving the name of the file to load
    (when \link{tilde expansion} is done).}
  \item{envir}{the environment where the data should be loaded.}
  \item{verbose}{should item names be printed during loading?}
}
\value{
  A character vector of the names of objects created, invisibly.
}
\seealso{
  \code{\link{save}}.
}
\examples{
## save all data
save(list = ls(all.names = TRUE), file = &quot;all.RData&quot;)

## restore the saved values to the current environment
load(&quot;all.RData&quot;)
}
\keyword{file}
</pre></div>
</td></tr></table>
</blockquote>

<p>An <samp class="file">Rd</samp> file consists of three parts.  The header gives basic
information about the name of the file, the topics documented, a title,
a short textual description and R usage information for the objects
documented.  The body gives further information (for example, on the
function&rsquo;s arguments and return value, as in the above example).
Finally, there is an optional footer with keyword information.  The
header is mandatory.
</p>
<p>Information is given within a series of <em class="emph">sections</em> with standard
names (and user-defined sections are also allowed).  Unless otherwise
specified<a class="footnote" id="DOCF114" href="#FOOT114"><sup>114</sup></a> these should occur only once in an <samp class="file">Rd</samp>
file (in any order), and the processing software will retain only the
first occurrence of a standard section in the file, with a warning.
</p>
<p>See <a class="uref" href="https://developer.r-project.org/Rds.html">&ldquo;Guidelines for Rd
files&rdquo;</a> for guidelines for writing documentation in <samp class="file">Rd</samp> format
which should be useful for package writers.
<a class="index-entry-id" id="index-prompt"></a>
The R
generic function <code class="code">prompt</code> is used to construct a bare-bones <samp class="file">Rd</samp>
file ready for manual editing.  Methods are defined for documenting
functions (which fill in the proper function and argument names) and
data frames.  There are also functions <code class="code">promptData</code>,
<code class="code">promptPackage</code>, <code class="code">promptClass</code>, and <code class="code">promptMethods</code> for
other types of <samp class="file">Rd</samp> files.
</p>
<p>The general syntax of <samp class="file">Rd</samp> files is summarized below.  For a detailed
technical discussion of current <samp class="file">Rd</samp> syntax, see
<a class="uref" href="https://developer.r-project.org/parseRd.pdf">&ldquo;Parsing Rd files&rdquo;</a>.
</p>
<p><samp class="file">Rd</samp> files consist of four types of text input.  The most common
is LaTeX-like, with the backslash used as a prefix on markup
(e.g. <code class="code">\alias</code>), and braces used to indicate arguments
(e.g. <code class="code">{load}</code>).  The least common type of text is &lsquo;verbatim&rsquo;
text, where no markup other than the comment marker (<code class="code">%</code>) is
processed.  There is also a rare variant of &lsquo;verbatim&rsquo; text
(used in <code class="code">\eqn</code>, <code class="code">\deqn</code>, <code class="code">\figure</code>,
and <code class="code">\newcommand</code>) where comment markers need not be escaped.
The final type is R-like, intended for R code, but allowing some
embedded macros.  Quoted strings within R-like text are handled
specially: regular character escapes such as <code class="code">\n</code> may be entered
as-is.  Only markup starting with <code class="code">\l</code> (e.g. <code class="code">\link</code>) or
<code class="code">\v</code> (e.g. <code class="code">\var</code>) will be recognized within quoted strings.
The rarely used vertical tab <code class="code">\v</code> must be entered as <code class="code">\\v</code>.
</p>
<p>Each macro defines the input type for its argument.  For example, the
file initially uses LaTeX-like syntax, and this is also used in the
<code class="code">\description</code> section, but the <code class="code">\usage</code> section uses
R-like syntax, and the <code class="code">\alias</code> macro uses &lsquo;verbatim&rsquo; syntax.
Comments run from a percent symbol <code class="code">%</code> to the end of the line in
all types of text except the rare &lsquo;verbatim&rsquo; variant
(as on the first line of the <code class="code">load</code> example).
</p>
<p>Because backslashes, braces and percent symbols have special meaning, to
enter them into text sometimes requires escapes using a backslash.  In
general balanced braces do not need to be escaped, but percent symbols
always do, except in the &lsquo;verbatim&rsquo; variant.
For the complete list of macros and rules for escapes, see
<a class="uref" href="https://developer.r-project.org/parseRd.pdf">&ldquo;Parsing Rd files&rdquo;</a>.
</p>

<ul class="mini-toc">
<li><a href="#Documenting-functions" accesskey="1">Documenting functions</a></li>
<li><a href="#Documenting-data-sets" accesskey="2">Documenting data sets</a></li>
<li><a href="#Documenting-S4-classes-and-methods" accesskey="3">Documenting S4 classes and methods</a></li>
<li><a href="#Documenting-packages" accesskey="4">Documenting packages</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Documenting-functions">
<div class="nav-panel">
<p>
Next: <a href="#Documenting-data-sets" accesskey="n" rel="next">Documenting data sets</a>, Previous: <a href="#Rd-format" accesskey="p" rel="prev">Rd format</a>, Up: <a href="#Rd-format" accesskey="u" rel="up">Rd format</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Documenting-functions-1"><span>2.1.1 Documenting functions<a class="copiable-link" href="#Documenting-functions-1"> &para;</a></span></h4>

<p>The basic markup commands used for documenting R objects (in
particular, functions) are given in this subsection.
</p>
<dl class="table">
<dt><a id="index-_005cname"></a><span><code class="code">\name{<var class="var">name</var>}</code><a class="copiable-link" href="#index-_005cname"> &para;</a></span></dt>
<dd><p><var class="var">name</var> typically<a class="footnote" id="DOCF115" href="#FOOT115"><sup>115</sup></a> is the basename of
the <samp class="file">Rd</samp> file containing the documentation.  It is the &ldquo;name&rdquo; of
the <samp class="file">Rd</samp> object represented by the file and has to be unique in a
package.  To avoid problems with indexing the package manual, it may not
contain &lsquo;<samp class="samp">!</samp>&rsquo;  &lsquo;<samp class="samp">|</samp>&rsquo; nor &lsquo;<samp class="samp">@</samp>&rsquo;.
(LaTeX special characters are allowed, but may not be collated
correctly in the index.)  There can only be one <code class="code">\name</code> entry in a
file, and it must not contain any markup and should only contain
printable <abbr class="acronym">ASCII</abbr> characters.  Entries in the package manual
will be in alphabetic<a class="footnote" id="DOCF116" href="#FOOT116"><sup>116</sup></a> order
of the <code class="code">\name</code> entries.
</p>
</dd>
<dt><a id="index-_005calias"></a><span><code class="code">\alias{<var class="var">topic</var>}</code><a class="copiable-link" href="#index-_005calias"> &para;</a></span></dt>
<dd><p>The <code class="code">\alias</code> sections specify all &ldquo;topics&rdquo; the file documents.
This information is collected into index data bases for lookup by the
on-line (plain text and <abbr class="acronym">HTML</abbr>) help systems.  The <var class="var">topic</var> can
contain spaces, but (for historical reasons) leading and trailing spaces
will be stripped.  Percent and left brace need to be escaped by
a backslash.
</p>
<p>There may be several <code class="code">\alias</code> entries.  Quite often it is
convenient to document several R objects in one file.  For example,
file <samp class="file">Normal.Rd</samp> documents the density, distribution function,
quantile function and generation of random variates for the normal
distribution, and hence starts with
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">\name{Normal}
\alias{Normal}
\alias{dnorm}
\alias{pnorm}
\alias{qnorm}
\alias{rnorm}
</pre></div></div>

<p>Also, it is often convenient to have several different ways to refer to
an R object, and an <code class="code">\alias</code> does not need to be the name of an
object.
</p>
<p>Note that the <code class="code">\name</code> is not necessarily a topic documented, and if
so desired it needs to have an explicit <code class="code">\alias</code> entry (as in this
example).
</p>
</dd>
<dt><a id="index-_005ctitle"></a><span><code class="code">\title{<var class="var">Title</var>}</code><a class="copiable-link" href="#index-_005ctitle"> &para;</a></span></dt>
<dd><p>Title information for the <samp class="file">Rd</samp> file.  This should be capitalized
and not end in a period; try to limit its length to at most 65
characters for widest compatibility.
</p>
<p>Markup is supported in the text, but use of characters other than
English text and punctuation (e.g., &lsquo;<samp class="samp">&lt;</samp>&rsquo;) may limit portability.
</p>
<p>There must be one (and only one) <code class="code">\title</code> section in a help file.
</p>
</dd>
<dt><a id="index-_005cdescription"></a><span><code class="code">\description{&hellip;}</code><a class="copiable-link" href="#index-_005cdescription"> &para;</a></span></dt>
<dd><p>A short description of what the function(s) do(es) (one paragraph, a few
lines only).  (If a description is too long and cannot easily be
shortened, the file probably tries to document too much at once.)
This is mandatory except for package-overview files.
</p>
</dd>
<dt><a id="index-_005cusage"></a><span><code class="code">\usage{<var class="var">fun</var>(<var class="var">arg1</var>, <var class="var">arg2</var>, &hellip;)}</code><a class="copiable-link" href="#index-_005cusage"> &para;</a></span></dt>
<dd><p>One or more lines showing the synopsis of the function(s) and variables
documented in the file.  These are set in typewriter font.  This is an
R-like command.
</p>
<p>The usage information specified should match the function definition
<em class="emph">exactly</em> (such that automatic checking for consistency between
code and documentation is possible).
</p>
<p>To indicate that a function can be used in several different ways,
depending on the named arguments specified, use section <code class="code">\details</code>.
E.g., <samp class="file">abline.Rd</samp> contains
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">\details{
  Typical usages are
\preformatted{abline(a, b, ...)
......
}
</pre></div></div>

<a class="index-entry-id" id="index-_005cmethod"></a>
<p>Use <code class="code">\method{<var class="var">generic</var>}{<var class="var">class</var>}</code> to indicate the name
of an S3 method for the generic function <var class="var">generic</var> for objects
inheriting from class <code class="code">&quot;<var class="var">class</var>&quot;</code>.  In the printed versions,
this will come out as <var class="var">generic</var> (reflecting the understanding that
methods should not be invoked directly but <em class="emph">via</em> method dispatch), but
<code class="code">codoc()</code> and other QC tools always have access to the full name.
</p>
<p>For example, <samp class="file">print.ts.Rd</samp> contains
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">\usage{
\method{print}{ts}(x, calendar, \dots)
}
</pre></div></div>

<p>which will print as
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">Usage:

     ## S3 method for class ‘ts’:
     print(x, calendar, ...)
</pre></div></div>

<p>Usage for replacement functions should be given in the style of
<code class="code">dim(x) &lt;- value</code> rather than explicitly indicating the name of the
replacement function (<code class="code">&quot;dim&lt;-&quot;</code><!-- /@w --> in the above).  Similarly, one
can use <code class="code">\method{<var class="var">generic</var>}{<var class="var">class</var>}(<var class="var">arglist</var>) &lt;-
value</code> to indicate the usage of an S3 replacement method for the generic
replacement function <code class="code">&quot;<var class="var">generic</var>&lt;-&quot;</code> for objects inheriting
from class <code class="code">&quot;<var class="var">class</var>&quot;</code>.
</p>
<p>Usage for S3 methods for extracting or replacing parts of an object, S3
methods for members of the Ops group, and S3 methods for user-defined
(binary) infix operators (&lsquo;<samp class="samp">%<var class="var">xxx</var>%</samp>&rsquo;) follows the above rules,
using the appropriate function names.  E.g., <samp class="file">Extract.factor.Rd</samp>
contains
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">\usage{
\method{[}{factor}(x, \dots, drop = FALSE)
\method{[[}{factor}(x, \dots)
\method{[}{factor}(x, \dots) &lt;- value
}
</pre></div></div>

<p>which will print as
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">Usage:

     ## S3 method for class ‘factor’:
     x[..., drop = FALSE]
     ## S3 method for class ‘factor’:
     x[[...]]
     ## S3 replacement method for class ‘factor’:
     x[...] &lt;- value
</pre></div></div>

<a class="index-entry-id" id="index-_005cS3method"></a>
<p><code class="code">\S3method</code> is accepted as an alternative to <code class="code">\method</code>.
</p>
</dd>
<dt><a id="index-_005carguments"></a><span><code class="code">\arguments{&hellip;}</code><a class="copiable-link" href="#index-_005carguments"> &para;</a></span></dt>
<dd><p>Description of the function&rsquo;s arguments, using an entry of the form
</p>
<div class="example">
<pre class="example-preformatted">\item{<var class="var">arg_i</var>}{<var class="var">Description of arg_i</var>.}
</pre></div>

<p>for each element of the argument list.  (Note that there is
no whitespace between the three parts of the entry.)  Arguments can also
be described jointly by separating their names with commas (and optional
whitespace) in the <code class="code">\item</code> label.  There may be
optional text outside the <code class="code">\item</code> entries, for example to give
general information about groups of parameters.
</p>

</dd>
<dt><a id="index-_005cdetails"></a><span><code class="code">\details{&hellip;}</code><a class="copiable-link" href="#index-_005cdetails"> &para;</a></span></dt>
<dd><p>A detailed if possible precise description of the functionality
provided, extending the basic information in the <code class="code">\description</code>
slot.
</p>
</dd>
<dt><a id="index-_005cvalue"></a><span><code class="code">\value{&hellip;}</code><a class="copiable-link" href="#index-_005cvalue"> &para;</a></span></dt>
<dd><p>Description of the function&rsquo;s return value.
</p>
<p>If a list with multiple values is returned, you can use entries of the
form
</p>
<div class="example">
<pre class="example-preformatted">\item{<var class="var">comp_i</var>}{<var class="var">Description of comp_i</var>.}
</pre></div>

<p>for each component of the list returned.  There may be
optional text outside the <code class="code">\item</code> entries
(see for example the joint help for <code class="code">rle</code> and <code class="code">inverse.rle</code>,
or the sets of items in <code class="code">l10n_info</code>).  Note that <code class="code">\value</code>
is implicitly a <code class="code">\describe</code> environment, so that environment should
not be used for listing components, just individual <code class="code">\item{}{}</code>
entries.<a class="footnote" id="DOCF117" href="#FOOT117"><sup>117</sup></a>
</p>
</dd>
<dt><a id="index-_005creferences"></a><span><code class="code">\references{&hellip;}</code><a class="copiable-link" href="#index-_005creferences"> &para;</a></span></dt>
<dd><p>A section with references to the literature.  Use <code class="code">\url{}</code> or
<code class="code">\href{}{}</code> for web pointers, and <code class="code">\doi{}</code> for <abbr class="abbr">DOI</abbr>s
(this needs R &gt;= 3.3, see <a class="ref" href="#User_002ddefined-macros">User-defined macros</a> for more info).
</p>
</dd>
<dt><a id="index-_005cnote"></a><span><code class="code">\note{...}</code><a class="copiable-link" href="#index-_005cnote"> &para;</a></span></dt>
<dd><p>Use this for a special note you want to have pointed out.  Multiple
<code class="code">\note</code> sections are allowed, but might be confusing to the end users.
</p>
<p>For example, <samp class="file">pie.Rd</samp> contains
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">\note{
  Pie charts are a very bad way of displaying information.
  The eye is good at judging linear measures and bad at
  judging relative areas.
  ......
}
</pre></div></div>

</dd>
<dt><a id="index-_005cauthor"></a><span><code class="code">\author{&hellip;}</code><a class="copiable-link" href="#index-_005cauthor"> &para;</a></span></dt>
<dd><p>Information about the author(s) of the <samp class="file">Rd</samp> file.  Use
<code class="code">\email{}</code> without extra delimiters (such as &lsquo;<samp class="samp">( )</samp>&rsquo; or
&lsquo;<samp class="samp">&lt; &gt;</samp>&rsquo;) to specify email addresses, or <code class="code">\url{}</code> or
<code class="code">\href{}{}</code> for web pointers.
</p>
</dd>
<dt><a id="index-_005cseealso"></a><span><code class="code">\seealso{&hellip;}</code><a class="copiable-link" href="#index-_005cseealso"> &para;</a></span></dt>
<dd><p>Pointers to related R objects, using <code class="code">\code{\link{...}}</code> to
refer to them (<code class="code">\code</code> is the correct markup for R object names,
and <code class="code">\link</code> produces hyperlinks in output formats which support
this.  See <a class="xref" href="#Marking-text">Marking text</a>, and <a class="ref" href="#Cross_002dreferences">Cross-references</a>).
</p>
</dd>
<dt><a id="index-_005cexamples"></a><span><code class="code">\examples{&hellip;}</code><a class="copiable-link" href="#index-_005cexamples"> &para;</a></span></dt>
<dd><p>Examples of how to use the function.  Code in this section is set
in typewriter font without reformatting and is run by
<code class="code">example()</code> unless marked otherwise (see below).
</p>
<p>Examples are not only useful for documentation purposes, but also
provide test code used for diagnostic checking of R code.  By
default, text inside <code class="code">\examples{}</code> will be displayed in the
output of the help page and run by <code class="code">example()</code> and by <code class="code">R CMD
check</code>.  You can use <code class="code">\dontrun{}</code>
<a class="index-entry-id" id="index-_005cdontrun"></a>
for text that should only be shown, but not run, and
<code class="code">\dontshow{}</code>
<a class="index-entry-id" id="index-_005cdontshow"></a>
for extra commands for testing that should not be shown to users, but
will be run by <code class="code">example()</code>.  (Previously this was called
<code class="code">\testonly</code>, and that is still accepted.)
</p>
<p>Text inside <code class="code">\dontrun{}</code> is &lsquo;verbatim&rsquo;, but the other parts
of the <code class="code">\examples</code> section are R-like text.
</p>
<p>For example,
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">x &lt;- runif(10)       # <span class="r">Shown and run.</span>
\dontrun{plot(x)}    # <span class="r">Only shown.</span>
\dontshow{log(x)}    # <span class="r">Only run.</span>
</pre></div></div>

<p>Thus, example code not included in <code class="code">\dontrun</code> must be executable!
In addition, it should not use any system-specific features or require
special facilities (such as Internet access or write permission to
specific directories).  Text included in <code class="code">\dontrun</code> is indicated by
comments in the processed help files: it need not be valid R code but
the escapes must still be used for <code class="code">%</code>, <code class="code">\</code> and unpaired
braces as in other &lsquo;verbatim&rsquo; text.
</p>
<p>Example code must be capable of being run by <code class="code">example</code>, which uses
<code class="code">source</code>.  This means that it should not access <samp class="file">stdin</samp>,
e.g. to <code class="code">scan()</code> data from the example file.
</p>
<p>Data needed for making the examples executable can be obtained by random
number generation (for example, <code class="code">x &lt;- rnorm(100)</code>), or by using
standard data sets listed by <code class="code">data()</code> (see <code class="code">?data</code> for more
info).
</p>
<a class="index-entry-id" id="index-_005cdonttest"></a>
<p>Finally, there is <code class="code">\donttest</code>, used (at the beginning of a separate
line) to mark code that should be run by <code class="code">example()</code> but not by
<code class="code">R CMD check</code> (by default: the option <samp class="option">--run-donttest</samp> can
be used).  This should be needed only occasionally but can be used for
code which might fail in circumstances that are hard to test for, for
example in some locales.  (Use e.g. <code class="code">capabilities()</code> or
<code class="code">nzchar(Sys.which(&quot;someprogram&quot;))</code> to test for features needed in
the examples wherever possible, and you can also use <code class="code">try()</code> or
<code class="code">tryCatch()</code>.  Use <code class="code">interactive()</code> to condition examples which
need someone to interact with.)  Note that code included in
<code class="code">\donttest</code> must be correct R code, and any packages used should
be declared in the <samp class="file">DESCRIPTION</samp> file.  It is good practice to
include a comment in the <code class="code">\donttest</code> section explaining why it is
needed.
</p>
<a class="index-entry-id" id="index-_005cdontdiff"></a>
<p>Output from code marked with <code class="code">\dontdiff</code> (requires R &gt;= 4.4.0)
or between comment lines
</p><div class="example">
<pre class="example-preformatted">## IGNORE_RDIFF_BEGIN
## IGNORE_RDIFF_END
</pre></div>
<p>is ignored when comparing check output to reference output (a
<samp class="file"><var class="var">pkg</var>-Ex.Rout.save</samp> file).
The comment-based markup can also be used for scripts under <samp class="file">tests</samp>.
</p>
</dd>
<dt><a id="index-_005ckeyword"></a><span><code class="code">\keyword{<var class="var">key</var>}</code><a class="copiable-link" href="#index-_005ckeyword"> &para;</a></span></dt>
<dd><p>There can be zero or more <code class="code">\keyword</code> sections per file.
Each <code class="code">\keyword</code> section should specify a single keyword, preferably
one of the standard keywords as listed in file <samp class="file">KEYWORDS</samp> in the
R documentation directory (default <samp class="file"><var class="var">R_HOME</var>/doc</samp>).  Use
e.g. <code class="code">RShowDoc(&quot;KEYWORDS&quot;)</code> to inspect the standard keywords from
within R.  There can be more than one <code class="code">\keyword</code> entry if the R
object being documented falls into more than one category, or none.
</p>
<p>Do strongly consider using <code class="code">\concept</code> (see <a class="pxref" href="#Indices">Indices</a>) instead of
<code class="code">\keyword</code> if you are about to use more than very few non-standard
keywords.
</p>
<p>The special keyword &lsquo;<samp class="samp">internal</samp>&rsquo; marks a page of internal topics
(typically, objects that are not part of the package&rsquo;s API).
If the help page for topic
<code class="code">foo</code> has keyword &lsquo;<samp class="samp">internal</samp>&rsquo;, then <code class="code">help(foo)</code> gives this
help page, but <code class="code">foo</code> is excluded from several topic indices,
including the alphabetical list of topics in the <abbr class="acronym">HTML</abbr> help system.
</p>
<p><code class="code">help.search()</code> can search by keyword, including user-defined
values: however the &lsquo;Search Engine &amp; Keywords&rsquo; <abbr class="acronym">HTML</abbr> page accessed
<em class="emph">via</em> <code class="code">help.start()</code> provides single-click access only to a
pre-defined list of keywords.
</p></dd>
</dl>


<hr>
</div>
<div class="subsection-level-extent" id="Documenting-data-sets">
<div class="nav-panel">
<p>
Next: <a href="#Documenting-S4-classes-and-methods" accesskey="n" rel="next">Documenting S4 classes and methods</a>, Previous: <a href="#Documenting-functions" accesskey="p" rel="prev">Documenting functions</a>, Up: <a href="#Rd-format" accesskey="u" rel="up">Rd format</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Documenting-data-sets-1"><span>2.1.2 Documenting data sets<a class="copiable-link" href="#Documenting-data-sets-1"> &para;</a></span></h4>

<p>The structure of <samp class="file">Rd</samp> files which document R data sets is slightly
different.  Sections such as <code class="code">\arguments</code> and <code class="code">\value</code> are not
needed but the format and source of the data should be explained.
</p>
<p>As an example, let us look at <samp class="file">src/library/datasets/man/rivers.Rd</samp>
which documents the standard R data set <code class="code">rivers</code>.
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example smallexample">
<pre class="example-preformatted">\name{rivers}
\docType{data}
\alias{rivers}
\title{Lengths of Major North American Rivers}
\description{
  This data set gives the lengths (in miles) of 141 \dQuote{major}
  rivers in North America, as compiled by the US Geological
  Survey.
}
\usage{rivers}
\format{A vector containing 141 observations.}
\source{World Almanac and Book of Facts, 1975, page 406.}
\references{
  McNeil, D. R. (1977) \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\keyword{datasets}
</pre></div>
</td></tr></table>
</blockquote>

<p>This uses the following additional markup commands.
</p>
<dl class="table">
<dt><code class="code">\docType{&hellip;}</code></dt>
<dd><p>Indicates the &ldquo;type&rdquo; of the documentation object.  Always &lsquo;<samp class="samp">data</samp>&rsquo;
for data sets, and &lsquo;<samp class="samp">package</samp>&rsquo; for <samp class="file"><var class="var">pkg</var>-package.Rd</samp>
overview files.  Documentation for S4 methods and classes uses
&lsquo;<samp class="samp">methods</samp>&rsquo; (from <code class="code">promptMethods()</code>) and &lsquo;<samp class="samp">class</samp>&rsquo; (from
<code class="code">promptClass()</code>).
</p>
</dd>
<dt><a id="index-_005cformat"></a><span><code class="code">\format{&hellip;}</code><a class="copiable-link" href="#index-_005cformat"> &para;</a></span></dt>
<dd><p>A description of the format of the data set (as a vector, matrix, data
frame, time series, &hellip;).  For matrices and data frames this should
give a description of each column, preferably as a list or table.
See <a class="xref" href="#Lists-and-tables">Lists and tables</a>, for more information.
</p>
</dd>
<dt><a id="index-_005csource"></a><span><code class="code">\source{&hellip;}</code><a class="copiable-link" href="#index-_005csource"> &para;</a></span></dt>
<dd><p>Details of the original source (a reference or <abbr class="acronym">URL</abbr>,
see <a class="pxref" href="#Specifying-URLs">Specifying URLs</a>).  In addition, section <code class="code">\references</code> could
give secondary sources and usages.
</p></dd>
</dl>

<p>Note also that when documenting data set <var class="var">bar</var>,
</p>
<ul class="itemize mark-bullet">
<li>The <code class="code">\usage</code> entry is always <code class="code"><var class="var">bar</var></code> or (for packages
which do not use lazy-loading of data) <code class="code">data(<var class="var">bar</var>)</code>.  (In
particular, only document a <em class="emph">single</em> data object per <samp class="file">Rd</samp> file.)
</li><li>The <code class="code">\keyword</code> entry should always be &lsquo;<samp class="samp">datasets</samp>&rsquo;.
</li></ul>

<p>If <code class="code"><var class="var">bar</var></code> is a data frame, documenting it as a data set can
be initiated <em class="emph">via</em> <code class="code">prompt(<var class="var">bar</var>)</code>.  Otherwise, the <code class="code">promptData</code>
function may be used.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Documenting-S4-classes-and-methods">
<div class="nav-panel">
<p>
Next: <a href="#Documenting-packages" accesskey="n" rel="next">Documenting packages</a>, Previous: <a href="#Documenting-data-sets" accesskey="p" rel="prev">Documenting data sets</a>, Up: <a href="#Rd-format" accesskey="u" rel="up">Rd format</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Documenting-S4-classes-and-methods-1"><span>2.1.3 Documenting S4 classes and methods<a class="copiable-link" href="#Documenting-S4-classes-and-methods-1"> &para;</a></span></h4>

<p>There are special ways to use the &lsquo;<samp class="samp">?</samp>&rsquo;  operator, namely
&lsquo;<samp class="samp">class?<var class="var">topic</var></samp>&rsquo; and &lsquo;<samp class="samp">methods?<var class="var">topic</var></samp>&rsquo;, to access
documentation for S4 classes and methods, respectively.  This mechanism
depends on conventions for the topic names used in <code class="code">\alias</code>
entries.  The topic names for S4 classes and methods respectively are of
the form
</p>
<div class="example">
<pre class="example-preformatted"><var class="var">class</var>-class
<var class="var">generic</var>,<var class="var">signature_list</var>-method
</pre></div>

<p>where <var class="var">signature_list</var> contains the names of the classes in the
signature of the method (without quotes) separated by &lsquo;<samp class="samp">,</samp>&rsquo; (without
whitespace), with &lsquo;<samp class="samp">ANY</samp>&rsquo; used for arguments without an explicit
specification.  E.g., &lsquo;<samp class="samp">genericFunction-class</samp>&rsquo; is the topic name for
documentation for the S4 class <code class="code">&quot;genericFunction&quot;</code>, and
&lsquo;<samp class="samp">coerce,ANY,NULL-method</samp>&rsquo; is the topic name for documentation for
the S4 method for <code class="code">coerce</code> for signature <code class="code">c(&quot;ANY&quot;, &quot;NULL&quot;)</code>.
</p>
<p>Skeletons of documentation for S4 classes and methods can be generated
by using the functions <code class="code">promptClass()</code> and <code class="code">promptMethods()</code>
from package <strong class="strong">methods</strong>.  If it is necessary or desired to provide an
explicit function declaration (in a <code class="code">\usage</code> section) for an S4
method (e.g., if it has &ldquo;surprising arguments&rdquo; to be mentioned
explicitly), one can use the special markup
</p>
<div class="example">
<pre class="example-preformatted">\S4method{<var class="var">generic</var>}{<var class="var">signature_list</var>}(<var class="var">argument_list</var>)
</pre></div>

<p>(e.g., &lsquo;<samp class="samp">\S4method{coerce}{ANY,NULL}(from, to)</samp>&rsquo;).
</p>
<p>To make full use of the potential of the on-line documentation system,
all user-visible S4 classes and methods in a package should at least
have a suitable <code class="code">\alias</code> entry in one of the package&rsquo;s <samp class="file">Rd</samp> files.
If a package has methods for a function defined originally somewhere
else, and does not change the underlying default method for the
function, the package is responsible for documenting the methods it
creates, but not for the function itself or the default method.
</p>
<p>An S4 replacement method is documented in the same way as an S3 one: see
the description of  <code class="code">\method</code> in <a class="ref" href="#Documenting-functions">Documenting functions</a>.
</p>

<p>See <code class="code">help(&quot;Documentation&quot;, package = &quot;methods&quot;)</code> for more
information on using and creating on-line documentation for S4 classes and
methods.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Documenting-packages">
<div class="nav-panel">
<p>
Previous: <a href="#Documenting-S4-classes-and-methods" accesskey="p" rel="prev">Documenting S4 classes and methods</a>, Up: <a href="#Rd-format" accesskey="u" rel="up">Rd format</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Documenting-packages-1"><span>2.1.4 Documenting packages<a class="copiable-link" href="#Documenting-packages-1"> &para;</a></span></h4>

<p>Packages may have an overview help page with an <code class="code">\alias</code>
<code class="code"><var class="var">pkgname</var>-package</code>, e.g. &lsquo;<samp class="samp">utils-package</samp>&rsquo; for the
<strong class="strong">utils</strong> package, when <code class="code">package?<var class="var">pkgname</var></code> will open that
help page.  If a topic named <code class="code"><var class="var">pkgname</var></code> does not exist in
another <samp class="file">Rd</samp> file, it is helpful to use this as an additional
<code class="code">\alias</code>.
</p>
<p>Skeletons of documentation for a package can be generated using the
function <code class="code">promptPackage()</code>.  If the <code class="code">final = TRUE</code> argument
is used, then the <samp class="file">Rd</samp> file will be generated in final form, containing
only basic information from the <samp class="file">DESCRIPTION</samp> file. Otherwise (the
default) comments will be inserted giving suggestions for content.
</p>
<p>Apart from the mandatory <code class="code">\name</code> and <code class="code">\title</code> and the
<code class="code"><var class="var">pkgname</var>-package</code> alias, the only requirement for the package
overview page is that it include a <code class="code">\docType{package}</code> statement.
All other content is optional.  We suggest that it should be a short
overview, to give a reader unfamiliar with the package enough
information to get started.  More extensive documentation is better
placed into a package vignette (see <a class="pxref" href="#Writing-package-vignettes">Writing package vignettes</a>) and
referenced from this page, or into individual man pages for the
functions, datasets, or classes.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Sectioning">
<div class="nav-panel">
<p>
Next: <a href="#Marking-text" accesskey="n" rel="next">Marking text</a>, Previous: <a href="#Rd-format" accesskey="p" rel="prev">Rd format</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Sectioning-1"><span>2.2 Sectioning<a class="copiable-link" href="#Sectioning-1"> &para;</a></span></h3>

<p>To begin a new paragraph or leave a blank line in an example, just
insert an empty line (as in (La)TeX).  To break a line, use
<code class="code">\cr</code>.
<a class="index-entry-id" id="index-_005ccr"></a>
</p>
<p>In addition to the predefined sections (such as <code class="code">\description{}</code>,
<code class="code">\value{}</code>, etc.), you can &ldquo;define&rdquo; arbitrary ones by
<code class="code">\section{<var class="var">section_title</var>}{&hellip;}</code>.
<a class="index-entry-id" id="index-_005csection"></a>
For example
</p>
<div class="example">
<pre class="example-preformatted">\section{Warning}{
  You must not call this function unless ...
}
</pre></div>

<p>For consistency with the pre-assigned sections, the section name (the
first argument to <code class="code">\section</code>) should be capitalized (but not all
upper case) and not end in a period.
Whitespace between the first and second braced expressions
is not allowed.  Markup (e.g. <code class="code">\code</code>) within the section title
may cause problems with the latex conversion (depending on the version
of macro packages such as &lsquo;<samp class="samp">hyperref</samp>&rsquo;) and so should be avoided.
</p>
<p>The <code class="code">\subsection</code> macro takes arguments in the same format as
<code class="code">\section</code>, but is used within a section, so it may be used to
nest subsections within sections or other subsections.  There is no
predefined limit on the nesting level, but formatting is not designed
for more than 3 levels (i.e. subsections within subsections within
sections).
</p>
<p>Note that additional named sections are always inserted at a fixed
position in the output (before <code class="code">\note</code>, <code class="code">\seealso</code> and the
examples), no matter where they appear in the input (but in the same
order amongst themselves as in the input).
</p>

<hr>
</div>
<div class="section-level-extent" id="Marking-text">
<div class="nav-panel">
<p>
Next: <a href="#Lists-and-tables" accesskey="n" rel="next">Lists and tables</a>, Previous: <a href="#Sectioning" accesskey="p" rel="prev">Sectioning</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Marking-text-1"><span>2.3 Marking text<a class="copiable-link" href="#Marking-text-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Marking-text-in-documentation"></a>

<p>The following logical markup commands are available for emphasizing or
quoting text.
</p>
<dl class="table">
<dt><a id="index-_005cstrong"></a><span><code class="code">\emph{<var class="var">text</var>}</code><a class="copiable-link" href="#index-_005cstrong"> &para;</a></span></dt>
<dd><a class="index-entry-id" id="index-_005cemph"></a>
</dd>
<dt><code class="code">\strong{<var class="var">text</var>}</code></dt>
<dd><p>Emphasize <var class="var">text</var> using <em class="emph">italic</em> and <strong class="strong">bold</strong> font if
possible; <code class="code">\strong</code> is regarded as stronger (more emphatic).
</p>
</dd>
<dt><a id="index-_005cbold"></a><span><code class="code">\bold{<var class="var">text</var>}</code><a class="copiable-link" href="#index-_005cbold"> &para;</a></span></dt>
<dd><p>Set <var class="var">text</var> in <b class="b">bold</b> font where possible.
</p>
</dd>
<dt><a id="index-_005cdQuote"></a><span><code class="code">\sQuote{<var class="var">text</var>}</code><a class="copiable-link" href="#index-_005cdQuote"> &para;</a></span></dt>
<dd><a class="index-entry-id" id="index-_005csQuote"></a>
</dd>
<dt><code class="code">\dQuote{<var class="var">text</var>}</code></dt>
<dd><p>Portably single or double quote <var class="var">text</var> (without hard-wiring the
characters used for quotation marks).
</p></dd>
</dl>

<p>Each of the above commands takes LaTeX-like input, so other macros
may be used within <var class="var">text</var>.
</p>
<p>The following logical markup commands are available for indicating
specific kinds of text.  Except as noted, these take &lsquo;verbatim&rsquo; text
input, and so other macros may not be used within them.  Some characters
will need to be escaped (see <a class="pxref" href="#Insertions">Insertions</a>).
</p>
<dl class="table">
<dt><a id="index-_005ccode"></a><span><code class="code">\code{<var class="var">text</var>}</code><a class="copiable-link" href="#index-_005ccode"> &para;</a></span></dt>
<dd><p>Indicate text that is a literal example of a piece of an R program,
e.g., a fragment of R code or the name of an R object.  Text is
entered in R-like syntax, and displayed using <code class="code">typewriter</code> font
where possible.  Macros <code class="code">\var</code> and <code class="code">\link</code> are interpreted within
<var class="var">text</var>.
</p>
</dd>
<dt><a id="index-_005cpreformatted"></a><span><code class="code">\preformatted{<var class="var">text</var>}</code><a class="copiable-link" href="#index-_005cpreformatted"> &para;</a></span></dt>
<dd><p>Indicate text that is a literal example of a piece of a program.  Text
is displayed using <code class="code">typewriter</code> font where possible.  Formatting,
e.g. line breaks, is preserved.  (Note that this includes a line break
after the initial {, so typically text should start on the same line as
the command.)
</p>
<p>Due to limitations in LaTeX as of this writing, this macro may not be
nested within other markup macros other than <code class="code">\dQuote</code> and
<code class="code">\sQuote</code>, as errors or bad formatting may result.
</p>
</dd>
<dt><a id="index-_005ckbd"></a><span><code class="code">\kbd{<var class="var">keyboard-characters</var>}</code><a class="copiable-link" href="#index-_005ckbd"> &para;</a></span></dt>
<dd><p>Indicate keyboard input, using <kbd class="kbd">slanted typewriter</kbd> font if
possible, so users can distinguish the characters they are supposed to
type from computer output.  Text is entered &lsquo;verbatim&rsquo;.
</p>
</dd>
<dt><a id="index-_005csamp"></a><span><code class="code">\samp{<var class="var">text</var>}</code><a class="copiable-link" href="#index-_005csamp"> &para;</a></span></dt>
<dd><p>Indicate text that is a literal example of a sequence of characters,
entered &lsquo;verbatim&rsquo;, to be included within word-wrapped text.  Displayed
within single quotation marks and
using <code class="code">typewriter</code> font where possible.
</p>
</dd>
<dt><a id="index-_005cverb"></a><span><code class="code">\verb{<var class="var">text</var>}</code><a class="copiable-link" href="#index-_005cverb"> &para;</a></span></dt>
<dd><p>Indicate text that is a literal example of a sequence of characters,
entered &lsquo;verbatim&rsquo;.  No wrapping or reformatting will occur.  Displayed
using <code class="code">typewriter</code> font where possible.
</p>
</dd>
<dt><a id="index-_005cpkg"></a><span><code class="code">\pkg{<var class="var">package_name</var>}</code><a class="copiable-link" href="#index-_005cpkg"> &para;</a></span></dt>
<dd><p>Indicate the name of an R package.  LaTeX-like.
</p>
</dd>
<dt><a id="index-_005cfile"></a><span><code class="code">\file{<var class="var">file_name</var>}</code><a class="copiable-link" href="#index-_005cfile"> &para;</a></span></dt>
<dd><p>Indicate the name of a file.  Text is LaTeX-like, so backslash needs
to be escaped.  Displayed using a distinct font where possible.
</p>
</dd>
<dt><a id="index-_005cemail"></a><span><code class="code">\email{<var class="var">email_address</var>}</code><a class="copiable-link" href="#index-_005cemail"> &para;</a></span></dt>
<dd><p>Indicate an electronic mail address.  LaTeX-like, will be rendered as
a hyperlink in <abbr class="acronym">HTML</abbr> and PDF conversion.  Displayed using
<code class="code">typewriter</code> font where possible.
</p>
</dd>
<dt><a id="index-_005curl"></a><span><code class="code">\url{<var class="var">uniform_resource_locator</var>}</code><a class="copiable-link" href="#index-_005curl"> &para;</a></span></dt>
<dd><p>Indicate a uniform resource locator (<abbr class="acronym">URL</abbr>) for the World Wide
Web.  The argument is handled as &lsquo;verbatim&rsquo; text (with percent and
braces escaped by backslash), and rendered as a hyperlink in <abbr class="acronym">HTML</abbr> and
PDF conversion.  Line feeds are removed, and leading and trailing
whitespace<a class="footnote" id="DOCF118" href="#FOOT118"><sup>118</sup></a> is
removed. See <a class="xref" href="#Specifying-URLs">Specifying URLs</a>.
</p>
<p>Displayed using <code class="code">typewriter</code> font where possible.
</p>
</dd>
<dt><a id="index-_005chref"></a><span><code class="code">\href{<var class="var">uniform_resource_locator</var>}{<var class="var">text</var>}</code><a class="copiable-link" href="#index-_005chref"> &para;</a></span></dt>
<dd><p>Indicate a hyperlink to the World Wide Web. The first argument is
handled as &lsquo;verbatim&rsquo; text (with percent and braces escaped by
backslash) and is used as the <abbr class="acronym">URL</abbr> in the hyperlink, with the
second argument of LaTeX-like text displayed to the user.  Line feeds
are removed from the first argument, and leading and trailing whitespace
is removed.
</p>
<p>Note that RFC3986-encoded URLs (e.g. using &lsquo;<samp class="samp">%28VS.85%29</samp>&rsquo; in
place of &lsquo;<samp class="samp">(VS.85)</samp>&rsquo;) may not work correctly in versions of R
before 3.1.3 and are best avoided&mdash;use <code class="code">URLdecode()</code> to decode
them.
</p>
</dd>
<dt><a id="index-_005cvar"></a><span><code class="code">\var{<var class="var">metasyntactic_variable</var>}</code><a class="copiable-link" href="#index-_005cvar"> &para;</a></span></dt>
<dd><p>Indicate a metasyntactic variable.  In most cases this will be rendered
distinctly, e.g. in italic (PDF/<abbr class="acronym">HTML</abbr>) or wrapped in &lsquo;<samp class="samp">&lt;&hellip;&gt;</samp>&rsquo; (text),
but not in all<a class="footnote" id="DOCF119" href="#FOOT119"><sup>119</sup></a>. LaTeX-like.
</p></dd>
<dt><a id="index-_005cenv"></a><span><code class="code">\env{<var class="var">environment_variable</var>}</code><a class="copiable-link" href="#index-_005cenv"> &para;</a></span></dt>
<dd><p>Indicate an environment variable. &lsquo;Verbatim&rsquo;.
Displayed using <code class="code">typewriter</code> font where possible
</p></dd>
<dt><a id="index-_005coption"></a><span><code class="code">\option{<var class="var">option</var>}</code><a class="copiable-link" href="#index-_005coption"> &para;</a></span></dt>
<dd><p>Indicate a command-line option.  &lsquo;Verbatim&rsquo;.
Displayed using <code class="code">typewriter</code> font where possible.
</p></dd>
<dt><a id="index-_005ccommand"></a><span><code class="code">\command{<var class="var">command_name</var>}</code><a class="copiable-link" href="#index-_005ccommand"> &para;</a></span></dt>
<dd><p>Indicate the name of a command. LaTeX-like, so <code class="code">\var</code> is
interpreted.  Displayed using <code class="code">typewriter</code> font where possible.
</p></dd>
<dt><a id="index-_005cdfn"></a><span><code class="code">\dfn{<var class="var">term</var>}</code><a class="copiable-link" href="#index-_005cdfn"> &para;</a></span></dt>
<dd><p>Indicate the introductory or defining use of a term. LaTeX-like.
</p></dd>
<dt><a id="index-_005ccite"></a><span><code class="code">\cite{<var class="var">reference</var>}</code><a class="copiable-link" href="#index-_005ccite"> &para;</a></span></dt>
<dd><p>Indicate a reference without a direct cross-reference <em class="emph">via</em> <code class="code">\link</code>
(see <a class="pxref" href="#Cross_002dreferences">Cross-references</a>), such as the name of a book. LaTeX-like.
</p></dd>
<dt><a id="index-_005cacronym"></a><span><code class="code">\acronym{<var class="var">acronym</var>}</code><a class="copiable-link" href="#index-_005cacronym"> &para;</a></span></dt>
<dd><p>Indicate an acronym (an abbreviation written in all capital letters),
such as <abbr class="acronym">GNU</abbr>.  LaTeX-like.
</p></dd>
<dt><a id="index-_005cabbr"></a><span><code class="code">\abbr{<var class="var">abbr</var>}</code><a class="copiable-link" href="#index-_005cabbr"> &para;</a></span></dt>
<dd><p>Indicates an abbreviation.  LaTeX-like.
</p></dd>
</dl>


<hr>
</div>
<div class="section-level-extent" id="Lists-and-tables">
<div class="nav-panel">
<p>
Next: <a href="#Cross_002dreferences" accesskey="n" rel="next">Cross-references</a>, Previous: <a href="#Marking-text" accesskey="p" rel="prev">Marking text</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Lists-and-tables-1"><span>2.4 Lists and tables<a class="copiable-link" href="#Lists-and-tables-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Lists-and-tables-in-documentation"></a>

<a class="index-entry-id" id="index-_005citemize"></a>
<a class="index-entry-id" id="index-_005cenumerate"></a>
<p>The <code class="code">\itemize</code> and <code class="code">\enumerate</code> commands take a single
argument, within which there may be one or more <code class="code">\item</code> commands.
The text following each <code class="code">\item</code> is formatted as one or more
paragraphs, suitably indented and with the first paragraph marked with a
bullet point (<code class="code">\itemize</code>) or a number (<code class="code">\enumerate</code>).
</p>
<p>Note that unlike argument lists, <code class="code">\item</code> in these formats is
followed by a space and the text (not enclosed in braces).  For example
</p>
<div class="example">
<pre class="example-preformatted">  \enumerate{
    \item A database consists of one or more records, each with one or
    more named fields.
    \item Regular lines start with a non-whitespace character.
    \item Records are separated by one or more empty lines.
  }
</pre></div>

<p><code class="code">\itemize</code> and <code class="code">\enumerate</code> commands may be nested.
</p>
<a class="index-entry-id" id="index-_005cdescribe"></a>
<p>The <code class="code">\describe</code> command is similar to <code class="code">\itemize</code> but allows
initial labels to be specified.  Each <code class="code">\item</code> takes two arguments,
the label and the body of the item, in exactly the same way as an
argument or value <code class="code">\item</code>.  <code class="code">\describe</code> commands are mapped to
<code class="code">&lt;DL&gt;</code> lists in <abbr class="acronym">HTML</abbr> and <code class="code">\description</code> lists in LaTeX.
</p>
<p>Using these without any <code class="code">\item</code>s may cause problems with some
conversions and makes little sense.
</p>
<a class="index-entry-id" id="index-_005ctabular"></a>
<p>The <code class="code">\tabular</code> command takes two arguments.  The first gives for
each of the columns the required alignment (&lsquo;<samp class="samp">l</samp>&rsquo; for
left-justification, &lsquo;<samp class="samp">r</samp>&rsquo; for right-justification or &lsquo;<samp class="samp">c</samp>&rsquo; for
centring.)  The second argument consists of an arbitrary number of
lines separated by <code class="code">\cr</code>, and with fields separated by <code class="code">\tab</code>.
For example:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">  \tabular{rlll}{
    [,1] \tab Ozone   \tab numeric \tab Ozone (ppb)\cr
    [,2] \tab Solar.R \tab numeric \tab Solar R (lang)\cr
    [,3] \tab Wind    \tab numeric \tab Wind (mph)\cr
    [,4] \tab Temp    \tab numeric \tab Temperature (degrees F)\cr
    [,5] \tab Month   \tab numeric \tab Month (1--12)\cr
    [,6] \tab Day     \tab numeric \tab Day of month (1--31)
  }
</pre></div></div>

<p>There must be the same number of fields on each line as there are
alignments in the first argument, and they must be non-empty (but can
contain only spaces).  (There is no whitespace between <code class="code">\tabular</code>
and the first argument, nor between the two arguments.)
</p>
<hr>
</div>
<div class="section-level-extent" id="Cross_002dreferences">
<div class="nav-panel">
<p>
Next: <a href="#Mathematics" accesskey="n" rel="next">Mathematics</a>, Previous: <a href="#Lists-and-tables" accesskey="p" rel="prev">Lists and tables</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Cross_002dreferences-1"><span>2.5 Cross-references<a class="copiable-link" href="#Cross_002dreferences-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Cross_002dreferences-in-documentation"></a>

<a class="index-entry-id" id="index-_005clink"></a>
<p>The markup <code class="code">\link{<var class="var">foo</var>}</code> (usually in the combination
<code class="code">\code{\link{<var class="var">foo</var>}}</code>) produces a hyperlink to the help for
<var class="var">foo</var>.  Here <var class="var">foo</var> is a <em class="emph">topic</em>, that is the argument of
<code class="code">\alias</code> markup in another <samp class="file">Rd</samp> file (possibly in another package).
Hyperlinks are supported in some of the formats to which <samp class="file">Rd</samp> files are
converted, for example <abbr class="acronym">HTML</abbr> and PDF, but ignored in others, e.g.
the text format.
</p>
<p>One main usage of <code class="code">\link</code> is in the <code class="code">\seealso</code> section of the
help page, see <a class="pxref" href="#Rd-format">Rd format</a>.
</p>
<p>Note that whereas leading and trailing spaces are stripped when
extracting a topic from a <code class="code">\alias</code>, they are not stripped when
looking up the topic of a <code class="code">\link</code>.
</p>
<a class="index-entry-id" id="index-_005clinkS4class"></a>
<p>You can specify a link to a different topic than its name by
<code class="code">\link[=<var class="var">dest</var>]{<var class="var">name</var>}</code> which links to topic <var class="var">dest</var>
with name <var class="var">name</var>.  This can be used to refer to the documentation
for S3/4 classes, for example <code class="code">\code{&quot;\link[=abc-class]{abc}&quot;}</code>
would be a way to refer to the documentation of an S4 class <code class="code">&quot;abc&quot;</code>
defined in your package, and
<code class="code">\code{&quot;\link[=terms.object]{terms}&quot;}</code> to the S3 <code class="code">&quot;terms&quot;</code>
class (in package <strong class="strong">stats</strong>).  To make these easy to read in the
source file, <code class="code">\code{&quot;\linkS4class{abc}&quot;}</code> expands to the form
given above.
</p>
<p>There are two other forms with an optional argument, specified as
<code class="code">\link[<var class="var">pkg</var>]{<var class="var">foo</var>}</code> and
<code class="code">\link[<var class="var">pkg:bar</var>]{<var class="var">foo</var>}</code>, to link to topics
<code class="code"><var class="var">foo</var></code> and <code class="code"><var class="var">bar</var></code> respectively in the package
<strong class="strong"><var class="var">pkg</var></strong>. They are currently only used in <abbr class="acronym">HTML</abbr> help (and
ignored for hyperlinks in LaTeX conversions of help pages). One
should be careful about topics containing special characters (such as
arithmetic operators) as they may result in unresolvable links, and
preferably use a safer alias in the same help page.
</p>
<p>Historically (before R version 4.1.0), links of the form
<code class="code">\link[<var class="var">pkg</var>]{<var class="var">foo</var>}</code> and
<code class="code">\link[<var class="var">pkg:bar</var>]{<var class="var">foo</var>}</code> used to be interpreted as links
to <em class="emph">files</em> <samp class="file"><var class="var">foo</var>.html</samp> and <samp class="file"><var class="var">bar</var>.html</samp> in
package <strong class="strong"><var class="var">pkg</var></strong>, respectively. For this reason, the <abbr class="acronym">HTML</abbr> help
system looks for file <samp class="file"><var class="var">foo</var>.html</samp> in package <strong class="strong"><var class="var">pkg</var></strong>
if it does not find topic <code class="code"><var class="var">foo</var></code>, and then searches for the
topic in other installed packages. To test that links work both with
both old and new systems, the pre-4.1.0 behaviour can be restored by
setting the environment variable <code class="env">_R_HELP_LINKS_TO_TOPICS_=false</code>.
</p>
<p>Packages referred to by these &lsquo;other forms&rsquo; should be declared in the
<samp class="file">DESCRIPTION</samp> file, in the &lsquo;<samp class="samp">Depends</samp>&rsquo;, &lsquo;<samp class="samp">Imports</samp>&rsquo;,
&lsquo;<samp class="samp">Suggests</samp>&rsquo; or &lsquo;<samp class="samp">Enhances</samp>&rsquo; fields.
</p>
<hr>
</div>
<div class="section-level-extent" id="Mathematics">
<div class="nav-panel">
<p>
Next: <a href="#Figures" accesskey="n" rel="next">Figures</a>, Previous: <a href="#Cross_002dreferences" accesskey="p" rel="prev">Cross-references</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Mathematics-1"><span>2.6 Mathematics<a class="copiable-link" href="#Mathematics-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Mathematics-in-documentation"></a>
<a class="index-entry-id" id="index-_005ceqn"></a>
<a class="index-entry-id" id="index-_005cdeqn"></a>

<p>Mathematical formulae should be set beautifully for printed
documentation and in KaTeX/MathJax-enhanced <abbr class="acronym">HTML</abbr> help (as from
R 4.2.0) yet we still want something useful for plain-text (and
legacy <abbr class="acronym">HTML</abbr>) help.  To this end, the two commands
<code class="code">\eqn{<var class="var">latex</var>}{<var class="var">ascii</var>}</code> and
<code class="code">\deqn{<var class="var">latex</var>}{<var class="var">ascii</var>}</code> are used.  Whereas <code class="code">\eqn</code>
is used for &ldquo;inline&rdquo; formulae (corresponding to TeX&rsquo;s
<code class="code">$&hellip;$</code>), <code class="code">\deqn</code> gives &ldquo;displayed equations&rdquo; (as in
LaTeX&rsquo;s <code class="code">displaymath</code> environment, or TeX&rsquo;s
<code class="code">$$&hellip;$$</code>).  Both arguments are treated as &lsquo;verbatim&rsquo; text.
</p>
<p>Both commands can also be used as <code class="code">\eqn{<var class="var">latexascii</var>}</code> (only
<em class="emph">one</em> argument) which then is used for both <var class="var">latex</var> and
<var class="var">ascii</var>.  No whitespace is allowed between command and the first
argument, nor between the first and second arguments.
</p>
<p>The following example is from <samp class="file">Poisson.Rd</samp>:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">  \deqn{p(x) = \frac{\lambda^x e^{-\lambda}}{x!}}{%
        p(x) = \lambda^x exp(-\lambda)/x!}
  for \eqn{x = 0, 1, 2, \ldots}.
</pre></div></div>


<p>In plain-text help we get
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">    p(x) = lambda^x exp(-lambda)/x!

for x = 0, 1, 2, ....
</pre></div>
</td></tr></table>
</blockquote>

<p>In legacy <abbr class="acronym">HTML</abbr> help, Greek letters (both cases) will be rendered if preceded by a
backslash, <code class="code">\dots</code> and <code class="code">\ldots</code> will be rendered as ellipses
and <code class="code">\sqrt</code>, <code class="code">\ge</code> and <code class="code">\le</code> as mathematical symbols.
</p>
<p>Note that only basic LaTeX can be used, there being no provision to
specify LaTeX style files, but <abbr class="abbr">AMS</abbr> extensions are supported
as from R 4.2.2.
</p>
<hr>
</div>
<div class="section-level-extent" id="Figures">
<div class="nav-panel">
<p>
Next: <a href="#Insertions" accesskey="n" rel="next">Insertions</a>, Previous: <a href="#Mathematics" accesskey="p" rel="prev">Mathematics</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Figures-1"><span>2.7 Figures<a class="copiable-link" href="#Figures-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Figures-in-documentation"></a>
<a class="index-entry-id" id="index-_005cfigure"></a>

<p>To include figures in help pages, use the <code class="code">\figure</code> markup.  There
are three forms.
</p>
<p>The two commonly used simple forms are <code class="code">\figure{<var class="var">filename</var>}</code>
and <code class="code">\figure{<var class="var">filename</var>}{<var class="var">alternate text</var>}</code>.  This will
include a copy of the figure in either <abbr class="acronym">HTML</abbr> or LaTeX output.  In text
output, the alternate text will be displayed instead.  (When the second
argument is omitted, the filename will be used.)  Both the filename and
the alternate text will be parsed verbatim, and should not include
special characters that are significant in <abbr class="acronym">HTML</abbr> or LaTeX.
</p>
<p>The expert form is <code class="code">\figure{<var class="var">filename</var>}{options:
<var class="var">string</var>}</code>.  (The word &lsquo;<samp class="samp">options:</samp>&rsquo; must be typed exactly as
shown and followed by at least one space.)  In this form, the
<var class="var">string</var> is copied into the <abbr class="acronym">HTML</abbr> <code class="code">img</code> tag as attributes
following the <code class="code">src</code> attribute, or into the second argument of the
<code class="code">\Figure</code> macro in LaTeX, which by default is used as options to
an <code class="code">\includegraphics</code> call.  As it is unlikely that any single
string would suffice for both display modes, the expert form would
normally be wrapped in conditionals.  It is up to the author to make
sure that legal <abbr class="acronym">HTML</abbr>/LaTeX is used.  For example, to include a
logo in both <abbr class="acronym">HTML</abbr> (using the simple form) and LaTeX (using the
expert form), the following could be used:
</p>
<div class="example">
<pre class="example-preformatted">\if{html}{\figure{Rlogo.svg}{options: width=100 alt=&quot;R logo&quot;}}
\if{latex}{\figure{Rlogo.pdf}{options: width=0.5in}}
</pre></div>

<p>The files containing the figures should be stored in the directory
<samp class="file">man/figures</samp>.  Files with extensions <samp class="file">.jpg</samp>, <samp class="file">.jpeg</samp>,
<samp class="file">.pdf</samp>, <samp class="file">.png</samp> and <samp class="file">.svg</samp> from that directory will be
copied to the <samp class="file">help/figures</samp> directory at install time. (Figures in
PDF format will not display in most <abbr class="acronym">HTML</abbr> browsers, but might be the
best choice in reference manuals.)  Specify the filename relative to
<samp class="file">man/figures</samp> in the <code class="code">\figure</code> directive.
</p>
<hr>
</div>
<div class="section-level-extent" id="Insertions">
<div class="nav-panel">
<p>
Next: <a href="#Indices" accesskey="n" rel="next">Indices</a>, Previous: <a href="#Figures" accesskey="p" rel="prev">Figures</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Insertions-1"><span>2.8 Insertions<a class="copiable-link" href="#Insertions-1"> &para;</a></span></h3>

<a class="index-entry-id" id="index-_005cR"></a>
<p>Use <code class="code">\R</code> for the R system itself.  The <code class="code">\dots</code>
<a class="index-entry-id" id="index-_005cdots"></a>
macro is a historical alternative to using literal &lsquo;<samp class="samp">...</samp>&rsquo;
for the dots in function argument lists; use
<code class="code">\ldots</code>
<a class="index-entry-id" id="index-_005cldots"></a>
for ellipsis dots in ordinary text.<a class="footnote" id="DOCF120" href="#FOOT120"><sup>120</sup></a>  These macros can be followed by
<code class="code">{}</code>, and should be unless followed by whitespace.
</p>
<p>After an unescaped &lsquo;<samp class="samp">%</samp>&rsquo;, you can put your own comments regarding the
help text.  The rest of the line (but not the newline at the end) will
be completely disregarded.  Therefore, you can also use it to make part
of the &ldquo;help&rdquo; invisible.
</p>
<p>You can produce a backslash (&lsquo;<samp class="samp">\</samp>&rsquo;) by escaping it by another
backslash.  (Note that <code class="code">\cr</code> is used for generating line breaks.)
</p>
<p>The &ldquo;comment&rdquo; character &lsquo;<samp class="samp">%</samp>&rsquo; and unpaired braces<a class="footnote" id="DOCF121" href="#FOOT121"><sup>121</sup></a>
<em class="emph">almost always</em> need to be escaped by &lsquo;<samp class="samp">\</samp>&rsquo;, and &lsquo;<samp class="samp">\\</samp>&rsquo; can
be used for backslash and needs to be when there are two or more adjacent
backslashes.  In R-like code quoted strings are handled slightly
differently; see <a class="uref" href="https://developer.r-project.org/parseRd.pdf">&ldquo;Parsing Rd files&rdquo;</a> for details &ndash; in particular braces should not be
escaped in quoted strings.
</p>
<p>All of &lsquo;<samp class="samp">% { } \</samp>&rsquo; should be escaped in LaTeX-like text.
</p>
<a class="index-entry-id" id="index-_005cenc"></a>
<p>Text which might need to be represented differently in different
encodings should be marked by <code class="code">\enc</code>, e.g.
<code class="code">\enc{J&ouml;reskog}{Joreskog}</code> (with no whitespace between the
braces) where the first argument will be used where encodings are
allowed and the second should be <abbr class="acronym">ASCII</abbr> (and is used for e.g.
the text conversion in locales that cannot represent the encoded form).
(This is intended to be used for individual words, not whole sentences
or paragraphs.)
</p>
<hr>
</div>
<div class="section-level-extent" id="Indices">
<div class="nav-panel">
<p>
Next: <a href="#Platform_002dspecific-sections" accesskey="n" rel="next">Platform-specific documentation</a>, Previous: <a href="#Insertions" accesskey="p" rel="prev">Insertions</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Indices-1"><span>2.9 Indices<a class="copiable-link" href="#Indices-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Indices"></a>

<p>The <code class="code">\alias</code> command (see <a class="pxref" href="#Documenting-functions">Documenting functions</a>) is used to
specify the &ldquo;topics&rdquo; documented, which should include <em class="emph">all</em> R
objects in a package such as functions and variables, data sets, and S4
classes and methods (see <a class="pxref" href="#Documenting-S4-classes-and-methods">Documenting S4 classes and methods</a>).  The
on-line help system searches the index data base consisting of all
alias topics.
</p>
<a class="index-entry-id" id="index-_005cconcept"></a>
<p>In addition, it is possible to provide &ldquo;concept index entries&rdquo; using
<code class="code">\concept</code>, which can be used for <code class="code">help.search()</code> lookups.
E.g., file <samp class="file">cor.test.Rd</samp> in the standard package <strong class="strong">stats</strong>
contains
</p>
<div class="example">
<pre class="example-preformatted">\concept{Kendall correlation coefficient}
\concept{Pearson correlation coefficient}
\concept{Spearman correlation coefficient}
</pre></div>

<p>so that e.g. <kbd class="kbd">??Spearman</kbd> will succeed in finding the
help page for the test for association between paired samples using
Spearman&rsquo;s rho.
</p>
<p>(Note that <code class="code">help.search()</code> only uses &ldquo;sections&rdquo; of documentation
objects with no additional markup.)
</p>
<p>Each <code class="code">\concept</code> entry should give a <em class="emph">single</em> index term (word
or phrase), and not use any Rd markup.
</p>
<p>If you want to cross reference such items from other help files <em class="emph">via</em>
<code class="code">\link</code>, you need to use <code class="code">\alias</code> and not <code class="code">\concept</code>.
</p>

<hr>
</div>
<div class="section-level-extent" id="Platform_002dspecific-sections">
<div class="nav-panel">
<p>
Next: <a href="#Conditional-text" accesskey="n" rel="next">Conditional text</a>, Previous: <a href="#Indices" accesskey="p" rel="prev">Indices</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Platform_002dspecific-documentation"><span>2.10 Platform-specific documentation<a class="copiable-link" href="#Platform_002dspecific-documentation"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Platform_002dspecific-documentation"></a>

<p>Sometimes the documentation needs to differ by platform.  Currently two
OS-specific options are available, &lsquo;<samp class="samp">unix</samp>&rsquo; and &lsquo;<samp class="samp">windows</samp>&rsquo;, and
lines in the help source file can be enclosed in
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#ifdef <var class="var">OS</var>
   ...
#endif
</pre></div></div>

<p>or
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#ifndef <var class="var">OS</var>
   ...
#endif
</pre></div></div>

<p>for OS-specific inclusion or exclusion.  Such blocks should not be
nested, and should be entirely within a block (that, is between the
opening and closing brace of a section or item), or at top-level contain
one or more complete sections.
</p>
<p>If the differences between platforms are extensive or the R objects
documented are only relevant to one platform, platform-specific <samp class="file">Rd</samp> files
can be put in a <samp class="file">unix</samp> or <samp class="file">windows</samp> subdirectory.
</p>
<hr>
</div>
<div class="section-level-extent" id="Conditional-text">
<div class="nav-panel">
<p>
Next: <a href="#Dynamic-pages" accesskey="n" rel="next">Dynamic pages</a>, Previous: <a href="#Platform_002dspecific-sections" accesskey="p" rel="prev">Platform-specific documentation</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Conditional-text-1"><span>2.11 Conditional text<a class="copiable-link" href="#Conditional-text-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-conditionals"></a>
<a class="index-entry-id" id="index-_005cif"></a>
<a class="index-entry-id" id="index-_005cifelse"></a>
<a class="index-entry-id" id="index-_005cout"></a>

<p>Occasionally the best content for one output format is different from
the best content for another.  For this situation, the
<code class="code">\if{<var class="var">format</var>}{<var class="var">text</var>}</code> or
<code class="code">\ifelse{<var class="var">format</var>}{<var class="var">text</var>}{<var class="var">alternate</var>}</code> markup
is used.  Here <var class="var">format</var> is a comma separated list of formats in
which the <var class="var">text</var> should be rendered.  The <var class="var">alternate</var> will be
rendered if the format does not match.  Both <var class="var">text</var> and
<var class="var">alternate</var> may be any sequence of text and markup.
</p>
<p>Currently the following formats are recognized:  <code class="code">example</code>,
<code class="code">html</code>, <code class="code">latex</code> and <code class="code">text</code>.  These select output for
the corresponding targets. (Note that <code class="code">example</code> refers to
extracted example code rather than the displayed example in some other
format.)  Also accepted are <code class="code">TRUE</code> (matching all formats) and
<code class="code">FALSE</code> (matching no formats).  These could be the output
of the <code class="code">\Sexpr</code> macro (see <a class="pxref" href="#Dynamic-pages">Dynamic pages</a>).
</p>
<p>The <code class="code">\out{<var class="var">literal</var>}</code> macro would usually be used within
the <var class="var">text</var> part of <code class="code">\if{<var class="var">format</var>}{<var class="var">text</var>}</code>.  It
causes the renderer to output the literal text exactly, with no
attempt to escape special characters.  For example, use
the following to output the markup necessary to display the Greek letter in
LaTeX or <abbr class="acronym">HTML</abbr>, and the text string <code class="code">alpha</code> in other formats:
</p><div class="example">
<pre class="example-preformatted">\ifelse{latex}{\out{$\alpha$}}{\ifelse{html}{\out{&amp;alpha;}}{alpha}}
</pre></div>

<hr>
</div>
<div class="section-level-extent" id="Dynamic-pages">
<div class="nav-panel">
<p>
Next: <a href="#User_002ddefined-macros" accesskey="n" rel="next">User-defined macros</a>, Previous: <a href="#Conditional-text" accesskey="p" rel="prev">Conditional text</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Dynamic-pages-1"><span>2.12 Dynamic pages<a class="copiable-link" href="#Dynamic-pages-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-dynamic-pages"></a>
<a class="index-entry-id" id="index-_005cSexpr"></a>
<a class="index-entry-id" id="index-_005cRdOpts"></a>

<p>Two macros supporting dynamically generated man pages are <code class="code">\Sexpr</code>
and <code class="code">\RdOpts</code>.  These are modelled after Sweave, and are intended
to contain executable R expressions in the <samp class="file">Rd</samp> file.
</p>
<p>The main argument to <code class="code">\Sexpr</code> must be valid R code that can be
executed. It may also take options in square brackets before the main
argument. Depending on the options, the code may be executed at
package build time, package install time, or man page rendering time.
</p>
<p>The options follow the same format as in Sweave, but different options
are supported.  Currently the allowed options and their defaults are:
</p>
<ul class="itemize mark-bullet">
<li><code class="code">eval=TRUE</code>
Whether the R code should be evaluated.

</li><li><code class="code">echo=FALSE</code>
Whether the R code should be echoed.  If <code class="code">TRUE</code>
<em class="emph">and</em> <code class="code">results=verbatim</code>, a display will
be given in a preformatted block.  For example,
<code class="code">\Sexpr[echo=TRUE,results=verbatim]{ x &lt;- 1 }</code> will be displayed as
<div class="example">
<pre class="example-preformatted">&gt; x &lt;- 1
</pre></div>

</li><li><code class="code">keep.source=TRUE</code>
Whether to keep the author&rsquo;s formatting when displaying the
code, or throw it away and use a deparsed version.

</li><li><code class="code">results=text</code>
How should the results be displayed?  The possibilities
are:

<ul class="itemize mark-minus">
<li><code class="code">results=text</code>
Apply <code class="code">as.character()</code> to the result of the code, and insert it
as a text element.

</li><li><code class="code">results=verbatim</code>
Print the results of the code just as if it was executed at the console,
and include the printed results verbatim.  (Invisible results will not print.)

</li><li><code class="code">results=rd</code>
The result is assumed to be a character vector containing markup to be
passed to <code class="code">parse_Rd()</code>, with the result inserted in place.  This
could be used to insert computed aliases, for instance.
<code class="code">parse_Rd()</code> is called first with <code class="code">fragment = FALSE</code> to allow
a single Rd section macro to be inserted.  If that fails, it is called
again with <code class="code">fragment = TRUE</code>, the older behavior.

</li><li><code class="code">results=hide</code>
Insert no output.
</li></ul>

</li><li><code class="code">strip.white=true</code>
Remove leading and trailing blank lines in verbatim
output if <code class="code">strip.white=true</code> (or <code class="code">TRUE</code>).  With
<code class="code">strip.white=all</code>, remove all blank lines.

</li><li><code class="code">stage=install</code>
Control when this macro is run.  Possible values are
<ul class="itemize mark-minus">
<li><code class="code">stage=build</code>
The macro is run when building a source tarball.

</li><li><code class="code">stage=install</code>
The macro is run when installing from source.

</li><li><code class="code">stage=render</code>
The macro is run when displaying the help page.
</li></ul>

<p>Conditionals such as <code class="code">#ifdef</code>
(see <a class="pxref" href="#Platform_002dspecific-sections">Platform-specific documentation</a>) are applied after the
<code class="code">build</code> macros but before the <code class="code">install</code> macros.  In some
situations (e.g. installing directly from a source directory without a
tarball, or building a binary package) the above description is not
literally accurate, but authors can rely on the sequence being
<code class="code">build</code>, <code class="code">#ifdef</code>, <code class="code">install</code>, <code class="code">render</code>, with all
stages executed.
</p>
<p>Code is only run once in each stage, so a <code class="code">\Sexpr[results=rd]</code>
macro can output an <code class="code">\Sexpr</code> macro designed for a later stage,
but not for the current one or any earlier stage.
</p>
</li><li><code class="code">width, height, fig</code>
These options are currently allowed but ignored.
</li></ul>

<p>The <code class="code">\RdOpts</code> macro is used to set new defaults for options to apply
to following uses of <code class="code">\Sexpr</code>.
</p>
<p>For more details, see the online document
<a class="uref" href="https://developer.r-project.org/parseRd.pdf">&ldquo;Parsing Rd files&rdquo;</a>.
</p>
<hr>
</div>
<div class="section-level-extent" id="User_002ddefined-macros">
<div class="nav-panel">
<p>
Next: <a href="#Encoding" accesskey="n" rel="next">Encoding</a>, Previous: <a href="#Dynamic-pages" accesskey="p" rel="prev">Dynamic pages</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="User_002ddefined-macros-1"><span>2.13 User-defined macros<a class="copiable-link" href="#User_002ddefined-macros-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-user_002ddefined-macros"></a>
<a class="index-entry-id" id="index-_005cnewcommand"></a>
<a class="index-entry-id" id="index-_005crenewcommand"></a>

<p>The <code class="code">\newcommand</code> and <code class="code">\renewcommand</code> macros allow new macros
to be defined within an Rd file.  These are similar but not identical to
the same-named LaTeX macros.
</p>
<p>They each take two arguments which are parsed verbatim.  The first is
the name of the new macro including the initial backslash, and the
second is the macro definition.  As in LaTeX, <code class="code">\newcommand</code>
requires that the new macro not have been previously defined, whereas
<code class="code">\renewcommand</code> allows existing macros (including all built-in
ones) to be replaced.  (This test is disabled by default, but may be
enabled by setting the environment variable
<code class="env">_R_WARN_DUPLICATE_RD_MACROS_</code> to a true value.)
</p>
<p>Also as in LaTeX, the new macro may be defined to take arguments,
and numeric placeholders such as <code class="code">#1</code> are used in the macro
definition. However, unlike LaTeX, the number of arguments is
determined automatically from the highest placeholder number seen in
the macro definition.  For example, a macro definition containing
<code class="code">#1</code> and <code class="code">#3</code> (but no other placeholders) will define a
three argument macro (whose second argument will be ignored). As in
LaTeX, at most 9 arguments may be defined. If the <code class="code">#</code>
character is followed by a non-digit it will have no special
significance.  All arguments to user-defined macros will be parsed as
verbatim text, and simple text-substitution will be used to replace
the place-holders, after which the replacement text will be parsed.
</p>
<p>A number of macros are defined in the file
<samp class="file">share/Rd/macros/system.Rd</samp> of the R source or home directory,
and these will normally be available in all <samp class="file">.Rd</samp> files.  For
example, that file contains the definition
</p><div class="example">
<pre class="example-preformatted">\newcommand{\PR}{\Sexpr[results=rd]{tools:::Rd_expr_PR(#1)}}
</pre></div>
<p>which defines <code class="code">\PR</code> to be a single argument macro; then code
(typically used in the <samp class="file">NEWS.Rd</samp> file) like
</p><div class="example">
<pre class="example-preformatted">\PR{1234}
</pre></div>
<p>will expand to
</p><div class="example">
<pre class="example-preformatted">\Sexpr[results=rd]{tools:::Rd_expr_PR(1234)}
</pre></div>
<p>when parsed.  
</p>
<p>Some macros that might be of general use are:
</p><dl class="ftable">
<dt><a id="index-_005cCRANpkg_007bpkg_007d"></a><span><code class="code">\CRANpkg{<var class="var">pkg</var>}</code><a class="copiable-link" href="#index-_005cCRANpkg_007bpkg_007d"> &para;</a></span></dt>
<dd><p>A package on CRAN
</p>
</dd>
<dt><a id="index-_005csspace"></a><span><code class="code">\sspace</code><a class="copiable-link" href="#index-_005csspace"> &para;</a></span></dt>
<dd><p>A single space (used after a period that does not end a sentence).
</p>
</dd>
<dt><a id="index-_005cdoi_007bnumbers_007d"></a><span><code class="code">\doi{<var class="var">numbers</var>}</code><a class="copiable-link" href="#index-_005cdoi_007bnumbers_007d"> &para;</a></span></dt>
<dd><p>A digital object identifier (<abbr class="abbr">DOI</abbr>).
</p></dd>
</dl>
<p>See the <samp class="file">system.Rd</samp> file in <samp class="file">share/Rd/macros</samp> for more details
and macro definitions, including macros <code class="code">\packageTitle</code>,
<code class="code">\packageDescription</code>, <code class="code">\packageAuthor</code>, <code class="code">\packageMaintainer</code>,
<code class="code">\packageDESCRIPTION</code> and <code class="code">\packageIndices</code>.
<a class="index-entry-id" id="index-_005cpackageTitle"></a>
<a class="index-entry-id" id="index-_005cpackageDescription"></a>
<a class="index-entry-id" id="index-_005cpackageAuthor"></a>
<a class="index-entry-id" id="index-_005cpackageMaintainer"></a>
<a class="index-entry-id" id="index-_005cpackageDESCRIPTION"></a>
<a class="index-entry-id" id="index-_005cpackageIndices"></a>
</p>

<p>Packages may also define their own common macros; these would be stored
in an <samp class="file">.Rd</samp> file in <samp class="file">man/macros</samp> in the package source and
will be installed into <samp class="file">help/macros</samp> when the package is installed.
A package may also use the macros from a different package by listing
the other package in the &lsquo;<samp class="samp">RdMacros</samp>&rsquo; field in the <samp class="file">DESCRIPTION</samp>
file.
</p>


<hr>
</div>
<div class="section-level-extent" id="Encoding">
<div class="nav-panel">
<p>
Next: <a href="#Processing-documentation-files" accesskey="n" rel="next">Processing documentation files</a>, Previous: <a href="#User_002ddefined-macros" accesskey="p" rel="prev">User-defined macros</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Encoding-1"><span>2.14 Encoding<a class="copiable-link" href="#Encoding-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-encoding"></a>

<p>Rd files are text files and so it is impossible to deduce the encoding
they are written in unless <abbr class="acronym">ASCII</abbr>: files with 8-bit characters
could be UTF-8, Latin-1, Latin-9, KOI8-R, EUC-JP, <em class="emph">etc</em>.  So an
<code class="code">\encoding{}</code> section must be used to specify the encoding if it
is not <abbr class="acronym">ASCII</abbr>.  (The <code class="code">\encoding{}</code> section must be on a
line by itself, and in particular one containing no non-<abbr class="acronym">ASCII</abbr>
characters.  The encoding declared in the <samp class="file">DESCRIPTION</samp> file will
be used if none is declared in the file.)  The <samp class="file">Rd</samp> files are
converted to UTF-8 before parsing and so the preferred encoding for the
files themselves is now UTF-8.
</p>
<p>Wherever possible, avoid non-<abbr class="acronym">ASCII</abbr> chars in <samp class="file">Rd</samp> files, and
even symbols such as &lsquo;<samp class="samp">&lt;</samp>&rsquo;, &lsquo;<samp class="samp">&gt;</samp>&rsquo;, &lsquo;<samp class="samp">$</samp>&rsquo;, &lsquo;<samp class="samp">^</samp>&rsquo;, &lsquo;<samp class="samp">&amp;</samp>&rsquo;,
&lsquo;<samp class="samp">|</samp>&rsquo;, &lsquo;<samp class="samp">@</samp>&rsquo;, &lsquo;<samp class="samp">~</samp>&rsquo;, and &lsquo;<samp class="samp">*</samp>&rsquo; outside &lsquo;verbatim&rsquo;
environments (since they may disappear in fonts designed to render
text).  (Function <code class="code">showNonASCIIfile</code> in package <strong class="strong">tools</strong> can help
in finding non-<abbr class="acronym">ASCII</abbr> bytes in the files.)
</p>
<p>For convenience, encoding names &lsquo;<samp class="samp">latin1</samp>&rsquo; and &lsquo;<samp class="samp">latin2</samp>&rsquo; are
always recognized: these and &lsquo;<samp class="samp">UTF-8</samp>&rsquo; are likely to work fairly
widely.  However, this does not mean that all characters in UTF-8 will
be recognized, and the coverage of non-Latin characters<a class="footnote" id="DOCF122" href="#FOOT122"><sup>122</sup></a> is fairly low.  Using LaTeX
<code class="code">inputenx</code> (see <code class="code">?Rd2pdf</code> in R) will give greater coverage
of UTF-8.
</p>
<p>The <code class="code">\enc</code> command (see <a class="pxref" href="#Insertions">Insertions</a>) can be used to provide
transliterations which will be used in conversions that do not support
the declared encoding.
</p>
<p>The LaTeX conversion converts the file to UTF-8 from the declared
encoding, and includes a
</p>
<div class="example">
<pre class="example-preformatted">\inputencoding{utf8}
</pre></div>

<p>command, and this needs to be matched by a suitable invocation of the
<code class="command">\usepackage{inputenc}</code> command.  The R utility <code class="command">R
CMD Rd2pdf</code> looks at the converted code and includes the encodings used:
it might for example use
</p>
<div class="example">
<pre class="example-preformatted">\usepackage[utf8]{inputenc}
</pre></div>

<p>(Use of <code class="code">utf8</code> as an encoding requires LaTeX dated 2003/12/01 or
later.  Also, the use of Cyrillic characters in &lsquo;<samp class="samp">UTF-8</samp>&rsquo; appears to
also need &lsquo;<samp class="samp">\usepackage[T2A]{fontenc}</samp>&rsquo;, and <code class="command">R CMD Rd2pdf</code>
includes this conditionally on the file <samp class="file">t2aenc.def</samp> being present
and environment variable <code class="env">_R_CYRILLIC_TEX_</code> being set.)
</p>
<p>Note that this mechanism works best with Latin letters: the coverage of
UTF-8 in LaTeX is quite low.
</p>


<hr>
</div>
<div class="section-level-extent" id="Processing-documentation-files">
<div class="nav-panel">
<p>
Next: <a href="#Editing-Rd-files" accesskey="n" rel="next">Editing Rd files</a>, Previous: <a href="#Encoding" accesskey="p" rel="prev">Encoding</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Processing-documentation-files-1"><span>2.15 Processing documentation files<a class="copiable-link" href="#Processing-documentation-files-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Processing-Rd-format"></a>

<p>There are several commands to process Rd files from the system command
line.
</p>
<a class="index-entry-id" id="index-R-CMD-Rdconv"></a>
<p>Using <code class="code">R CMD Rdconv</code> one can convert R documentation format to
other formats, or extract the executable examples for run-time testing.
The currently supported conversions are to plain text, <abbr class="acronym">HTML</abbr> and
LaTeX as well as extraction of the examples.
</p>
<a class="index-entry-id" id="index-R-CMD-Rd2pdf"></a>
<p><code class="code">R CMD Rd2pdf</code> generates PDF output from documentation in <samp class="file">Rd</samp>
files, which can be specified either explicitly or by the path to a
directory with the sources of a package.  In the latter case, a
reference manual for all documented objects in the package is created,
including the information in the <samp class="file">DESCRIPTION</samp> files.
</p>
<a class="index-entry-id" id="index-R-CMD-Sweave"></a>
<a class="index-entry-id" id="index-R-CMD-Stangle"></a>
<p><code class="code">R CMD Sweave</code> and <code class="code">R CMD Stangle</code> process vignette-like
documentation files (e.g. Sweave vignettes with extension
&lsquo;<samp class="samp">.Snw</samp>&rsquo; or &lsquo;<samp class="samp">.Rnw</samp>&rsquo;, or other non-Sweave vignettes).
<code class="code">R CMD Stangle</code> is used to extract the R code fragments.
</p>
<p>The exact usage and a detailed list of available options for all of
these commands can be obtained by running <code class="code">R CMD <var class="var">command</var>
--help</code>, e.g., <kbd class="kbd">R CMD Rdconv --help</kbd>.  All available commands can be
listed using <kbd class="kbd">R --help</kbd> (or <kbd class="kbd">Rcmd --help</kbd> under Windows).
</p>
<p>All of these work under Windows.  You may need to have installed the
the tools to build packages from source as described in the &ldquo;R
Installation and Administration&rdquo; manual, although typically all that is
needed is a LaTeX installation.
</p>
<hr>
</div>
<div class="section-level-extent" id="Editing-Rd-files">
<div class="nav-panel">
<p>
Previous: <a href="#Processing-documentation-files" accesskey="p" rel="prev">Processing documentation files</a>, Up: <a href="#Writing-R-documentation-files" accesskey="u" rel="up">Writing R documentation files</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Editing-Rd-files-1"><span>2.16 Editing Rd files<a class="copiable-link" href="#Editing-Rd-files-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Editing-Rd-files"></a>

<p>It can be very helpful to prepare <samp class="file">.Rd</samp> files using a editor which
knows about their syntax and will highlight commands, indent to show the
structure and detect mis-matched braces, and so on.
</p>
<p>The system most commonly used for this is some version of
<code class="command">Emacs</code> (including <code class="command">XEmacs</code>) with the <abbr class="acronym">ESS</abbr>
package (<a class="uref" href="https://ESS.R-project.org/">https://ESS.R-project.org/</a>: it is often is installed with
<code class="command">Emacs</code> but may need to be loaded, or even installed,
separately).
</p>
<p>Another is the Eclipse IDE with the Stat-ET plugin
(<a class="uref" href="https://projects.eclipse.org/projects/science.statet">https://projects.eclipse.org/projects/science.statet</a>), and (on
Windows only) Tinn-R
(<a class="uref" href="https://sourceforge.net/projects/tinn-r/">https://sourceforge.net/projects/tinn-r/</a>).
</p>
<p>People have also used LaTeX mode in a editor, as <samp class="file">.Rd</samp> files are
rather similar to LaTeX files.
</p>
<p>Some R front-ends provide editing support for  <samp class="file">.Rd</samp> files, for
example RStudio (<a class="uref" href="https://posit.co/">https://posit.co/</a>).
</p>
<hr>
</div>
</div>
<div class="chapter-level-extent" id="Tidying-and-profiling-R-code">
<div class="nav-panel">
<p>
Next: <a href="#Debugging" accesskey="n" rel="next">Debugging</a>, Previous: <a href="#Writing-R-documentation-files" accesskey="p" rel="prev">Writing R documentation files</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="chapter" id="Tidying-and-profiling-R-code-1"><span>3 Tidying and profiling R code<a class="copiable-link" href="#Tidying-and-profiling-R-code-1"> &para;</a></span></h2>


<p>R code which is worth preserving in a package and perhaps making
available for others to use is worth documenting, tidying up and perhaps
optimizing. The last two of these activities are the subject of this
chapter.
</p>
<ul class="mini-toc">
<li><a href="#Tidying-R-code" accesskey="1">Tidying R code</a></li>
<li><a href="#Profiling-R-code-for-speed" accesskey="2">Profiling R code for speed</a></li>
<li><a href="#Profiling-R-code-for-memory-use" accesskey="3">Profiling R code for memory use</a></li>
<li><a href="#Profiling-compiled-code" accesskey="4">Profiling compiled code</a></li>
</ul>
<hr>
<div class="section-level-extent" id="Tidying-R-code">
<div class="nav-panel">
<p>
Next: <a href="#Profiling-R-code-for-speed" accesskey="n" rel="next">Profiling R code for speed</a>, Previous: <a href="#Tidying-and-profiling-R-code" accesskey="p" rel="prev">Tidying and profiling R code</a>, Up: <a href="#Tidying-and-profiling-R-code" accesskey="u" rel="up">Tidying and profiling R code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Tidying-R-code-1"><span>3.1 Tidying R code<a class="copiable-link" href="#Tidying-R-code-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Tidying-R-code"></a>

<p>R treats function code loaded from packages and code entered by users
differently.  By default code entered by users has the source code stored
internally, and when the function is listed, the original source is
reproduced.  Loading code from a package (by default) discards the
source code, and the function listing is re-created from the parse tree
of the function.
</p>
<p>Normally keeping the source code is a good idea, and in particular it
avoids comments being removed from the source.  However, we can make
use of the ability to re-create a function listing from its parse tree
to produce a tidy version of the function, for example with consistent
indentation and spaces around operators.  If the original source
does not follow the standard format this tidied version can be much
easier to read.
</p>
<p>We can subvert the keeping of source in two ways.
</p>
<ol class="enumerate">
<li> The option <code class="code">keep.source</code> can be set to <code class="code">FALSE</code> before the code
is loaded into R.
</li><li> The stored source code can be removed by calling the <code class="code">removeSource()</code>
function, for example by

<div class="example">
<pre class="example-preformatted">myfun &lt;- removeSource(myfun)
</pre></div>

</li></ol>

<p>In each case if we then list the function we will get the standard
layout.
</p>
<p>Suppose we have a file of functions <samp class="file">myfuns.R</samp> that we want to
tidy up.  Create a file <samp class="file">tidy.R</samp> containing
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">source(&quot;myfuns.R&quot;, keep.source = FALSE)
dump(ls(all.names = TRUE), file = &quot;new.myfuns.R&quot;)
</pre></div></div>

<p>and run R with this as the source file, for example by <kbd class="kbd">R
--vanilla &lt; tidy.R</kbd> or by pasting into an R session.  Then the file
<samp class="file">new.myfuns.R</samp> will contain the functions in alphabetical order in
the standard layout.  Warning:  comments in your functions will be lost.
</p>
<p>The standard format provides a good starting point for further tidying.
Although the deparsing cannot do so, we recommend the consistent use of
the preferred assignment operator &lsquo;<samp class="samp">&lt;-</samp>&rsquo; (rather than &lsquo;<samp class="samp">=</samp>&rsquo;) for
assignment.  Many package authors use a version of Emacs (on a
Unix-alike or Windows) to edit R code, using the ESS[S] mode of the
<abbr class="acronym">ESS</abbr> Emacs package.  See 
<a data-manual="R-ints" href="https://cran.r-project.org/doc/manuals/R-ints.html#R-coding-standards">R coding standards</a> in <cite class="cite">R Internals</cite>
for style options within the ESS[S] mode recommended for the source code
of R itself.
</p>


<hr>
</div>
<div class="section-level-extent" id="Profiling-R-code-for-speed">
<div class="nav-panel">
<p>
Next: <a href="#Profiling-R-code-for-memory-use" accesskey="n" rel="next">Profiling R code for memory use</a>, Previous: <a href="#Tidying-R-code" accesskey="p" rel="prev">Tidying R code</a>, Up: <a href="#Tidying-and-profiling-R-code" accesskey="u" rel="up">Tidying and profiling R code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Profiling-R-code-for-speed-1"><span>3.2 Profiling R code for speed<a class="copiable-link" href="#Profiling-R-code-for-speed-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Profiling"></a>
<a class="index-entry-id" id="index-Rprof"></a>

<p>It is possible to profile R code on Windows and most<a class="footnote" id="DOCF123" href="#FOOT123"><sup>123</sup></a> Unix-alike versions of
R.
</p>
<p>The command <code class="command">Rprof</code> is used to control profiling, and its help
page can be consulted for full details.  Profiling works by recording at
fixed intervals<a class="footnote" id="DOCF124" href="#FOOT124"><sup>124</sup></a> (by default every
20 <abbr class="abbr">msec</abbr>s) which line in which R function is being used, and recording
the results in a file (default <samp class="file">Rprof.out</samp> in the working
directory).  Then the function <code class="code">summaryRprof</code> or the command-line
utility <code class="code">R CMD Rprof <var class="var">Rprof.out</var></code> can be used to summarize the
activity.
</p>
<p>As an example, consider the following code (from Venables &amp; Ripley,
2002, pp. 225&ndash;6).
</p>
<div class="example smallexample">
<div class="group"><pre class="example-preformatted">library(MASS); library(boot)
storm.fm &lt;- nls(Time ~ b*Viscosity/(Wt - c), stormer,
                start = c(b=30.401, c=2.2183))
st &lt;- cbind(stormer, fit=fitted(storm.fm))
storm.bf &lt;- function(rs, i) {
    st$Time &lt;-  st$fit + rs[i]
    tmp &lt;- nls(Time ~ (b * Viscosity)/(Wt - c), st,
               start = coef(storm.fm))
    tmp$m$getAllPars()
}
rs &lt;- scale(resid(storm.fm), scale = FALSE) # remove the mean
Rprof(&quot;boot.out&quot;)
storm.boot &lt;- boot(rs, storm.bf, R = 4999) # slow enough to profile
Rprof(NULL)
</pre></div></div>

<p>Having run this we can summarize the results by
</p>
<div class="example smallexample">
<div class="group"><pre class="example-preformatted">R CMD Rprof boot.out

Each sample represents 0.02 seconds.
Total run time: 22.52 seconds.

Total seconds: time spent in function and callees.
Self seconds: time spent in function alone.
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">   %       total       %        self
 total    seconds     self    seconds    name
 100.0     25.22       0.2      0.04     &quot;boot&quot;
  99.8     25.18       0.6      0.16     &quot;statistic&quot;
  96.3     24.30       4.0      1.02     &quot;nls&quot;
  33.9      8.56       2.2      0.56     &quot;&lt;Anonymous&gt;&quot;
  32.4      8.18       1.4      0.36     &quot;eval&quot;
  31.8      8.02       1.4      0.34     &quot;.Call&quot;
  28.6      7.22       0.0      0.00     &quot;eval.parent&quot;
  28.5      7.18       0.3      0.08     &quot;model.frame&quot;
  28.1      7.10       3.5      0.88     &quot;model.frame.default&quot;
  17.4      4.38       0.7      0.18     &quot;sapply&quot;
  15.0      3.78       3.2      0.80     &quot;nlsModel&quot;
  12.5      3.16       1.8      0.46     &quot;lapply&quot;
  12.3      3.10       2.7      0.68     &quot;assign&quot;
 ...
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">   %        self        %      total
  self    seconds     total   seconds    name
   5.7      1.44       7.5      1.88     &quot;inherits&quot;
   4.0      1.02      96.3     24.30     &quot;nls&quot;
   3.6      0.92       3.6      0.92     &quot;$&quot;
   3.5      0.88      28.1      7.10     &quot;model.frame.default&quot;
   3.2      0.80      15.0      3.78     &quot;nlsModel&quot;
   2.8      0.70       9.8      2.46     &quot;qr.coef&quot;
   2.7      0.68      12.3      3.10     &quot;assign&quot;
   2.5      0.64       2.5      0.64     &quot;.Fortran&quot;
   2.5      0.62       7.1      1.80     &quot;qr.default&quot;
   2.2      0.56      33.9      8.56     &quot;&lt;Anonymous&gt;&quot;
   2.1      0.54       5.9      1.48     &quot;unlist&quot;
   2.1      0.52       7.9      2.00     &quot;FUN&quot;
  ...
</pre></div></div>

<p>This often produces
surprising results and can be used to identify bottlenecks or pieces of
R code that could benefit from being replaced by compiled code.
</p>
<p>Two warnings: profiling does impose a small performance penalty, and the
output files can be very large if long runs are profiled at the default
sampling interval.
</p>
<p>Profiling short runs can sometimes give misleading results.  R from
time to time performs <em class="emph">garbage collection</em> to reclaim unused
memory, and this takes an appreciable amount of time which profiling
will charge to whichever function happens to provoke it.  It may be
useful to compare profiling code immediately after a call to <code class="code">gc()</code>
with a profiling run without a preceding call to <code class="code">gc</code>.
</p>
<p>More detailed analysis of the output can be achieved by the tools in the
<abbr class="acronym">CRAN</abbr> packages <a class="url" href="https://CRAN.R-project.org/package=proftools"><strong class="strong">proftools</strong></a> and <a class="url" href="https://CRAN.R-project.org/package=profr"><strong class="strong">profr</strong></a>: in
particular these allow call graphs to be studied.
</p>
<hr>
</div>
<div class="section-level-extent" id="Profiling-R-code-for-memory-use">
<div class="nav-panel">
<p>
Next: <a href="#Profiling-compiled-code" accesskey="n" rel="next">Profiling compiled code</a>, Previous: <a href="#Profiling-R-code-for-speed" accesskey="p" rel="prev">Profiling R code for speed</a>, Up: <a href="#Tidying-and-profiling-R-code" accesskey="u" rel="up">Tidying and profiling R code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Profiling-R-code-for-memory-use-1"><span>3.3 Profiling R code for memory use<a class="copiable-link" href="#Profiling-R-code-for-memory-use-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Profiling-1"></a>
<a class="index-entry-id" id="index-Memory-use"></a>

<p>Measuring memory use in R code is useful either when the code takes
more memory than is conveniently available or when memory allocation and
copying of objects is responsible for slow code. There are three ways to
profile memory use over time in R code. The second and third require
R to have been compiled with <samp class="option">--enable-memory-profiling</samp>,
which is not the default, but is currently used for the macOS and
Windows binary distributions. All can be misleading, for different
reasons.
</p>
<p>In understanding the memory profiles it is useful to know a little more
about R&rsquo;s memory allocation. Looking at the results of <code class="code">gc()</code>
shows a division of memory into <code class="code">Vcells</code> used to store the contents
of vectors and <code class="code">Ncells</code> used to store everything else, including
all the administrative overhead for vectors such as type and length
information.  In fact the vector contents are divided into two
pools. Memory for small vectors (by default 128 bytes or less) is
obtained in large chunks and then parcelled out by R; memory for
larger vectors is obtained directly from the operating system.
</p>
<p>Some memory allocation is obvious in interpreted code, for example,
</p>
<div class="example smallexample">
<pre class="example-preformatted">y &lt;- x + 1
</pre></div>

<p>allocates memory for a new vector <code class="code">y</code>. Other memory allocation is
less obvious and occurs because <code class="code">R</code> is forced to make good on its
promise of &lsquo;call-by-value&rsquo; argument passing.  When an argument is
passed to a function it is not immediately copied. Copying occurs (if
necessary) only when the argument is modified.  This can lead to
surprising memory use. For example, in the &lsquo;survey&rsquo; package we have
</p>
<div class="example smallexample">
<pre class="example-preformatted">print.svycoxph &lt;- function (x, ...)
{
    print(x$survey.design, varnames = FALSE, design.summaries = FALSE, ...)
    x$call &lt;- x$printcall
    NextMethod()
}
</pre></div>

<p>It may not be obvious that the assignment to <code class="code">x$call</code> will cause
the entire object <code class="code">x</code> to be copied.  This copying to preserve the
call-by-value illusion is usually done by the internal C function
<code class="code">duplicate</code>.
</p>
<p>The main reason that memory-use profiling is difficult is garbage
collection. Memory is allocated at well-defined times in an R
program, but is freed whenever the garbage collector happens to run.
</p>

<ul class="mini-toc">
<li><a href="#Memory-statistics-from-Rprof" accesskey="1">Memory statistics from <code class="code">Rprof</code></a></li>
<li><a href="#Tracking-memory-allocations" accesskey="2">Tracking memory allocations</a></li>
<li><a href="#Tracing-copies-of-an-object" accesskey="3">Tracing copies of an object</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Memory-statistics-from-Rprof">
<div class="nav-panel">
<p>
Next: <a href="#Tracking-memory-allocations" accesskey="n" rel="next">Tracking memory allocations</a>, Previous: <a href="#Profiling-R-code-for-memory-use" accesskey="p" rel="prev">Profiling R code for memory use</a>, Up: <a href="#Profiling-R-code-for-memory-use" accesskey="u" rel="up">Profiling R code for memory use</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Memory-statistics-from-Rprof-1"><span>3.3.1 Memory statistics from <code class="code">Rprof</code><a class="copiable-link" href="#Memory-statistics-from-Rprof-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Rprof-1"></a>
<a class="index-entry-id" id="index-summaryRprof"></a>

<p>The sampling profiler <code class="code">Rprof</code> described in the previous section can
be given the option <code class="code">memory.profiling=TRUE</code>. It then writes out the
total R memory allocation in small vectors, large vectors, and cons
cells or nodes at each sampling interval. It also writes out the number
of calls to the internal function <code class="code">duplicate</code>, which is called to
copy R objects. <code class="code">summaryRprof</code> provides summaries of this
information.  The main reason that this can be misleading is that the
memory use is attributed to the function running at the end of the
sampling interval. A second reason is that garbage collection can make
the amount of memory in use decrease, so a function appears to use
little memory.  Running under <code class="code">gctorture</code> helps with both problems:
it slows down the code to effectively increase the sampling frequency
and it makes each garbage collection release a smaller amount of memory.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Tracking-memory-allocations">
<div class="nav-panel">
<p>
Next: <a href="#Tracing-copies-of-an-object" accesskey="n" rel="next">Tracing copies of an object</a>, Previous: <a href="#Memory-statistics-from-Rprof" accesskey="p" rel="prev">Memory statistics from <code class="code">Rprof</code></a>, Up: <a href="#Profiling-R-code-for-memory-use" accesskey="u" rel="up">Profiling R code for memory use</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Tracking-memory-allocations-1"><span>3.3.2 Tracking memory allocations<a class="copiable-link" href="#Tracking-memory-allocations-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Rprofmem"></a>

<p>The second method of memory profiling uses a memory-allocation
profiler, <code class="code">Rprofmem()</code>, which writes out a stack trace to an
output file every time a large vector is allocated (with a
user-specified threshold for &lsquo;large&rsquo;) or a new page of memory is
allocated for the R heap. Summary functions for this output are still
being designed.
</p>
<p>Running the example from the previous section with
</p>
<div class="example smallexample">
<pre class="example-preformatted">&gt; Rprofmem(&quot;boot.memprof&quot;,threshold=1000)
&gt; storm.boot &lt;- boot(rs, storm.bf, R = 4999)
&gt; Rprofmem(NULL)
</pre></div>

<p>shows that apart from some initial and final work in <code class="code">boot</code> there
are no vector allocations over 1000 bytes.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Tracing-copies-of-an-object">
<div class="nav-panel">
<p>
Previous: <a href="#Tracking-memory-allocations" accesskey="p" rel="prev">Tracking memory allocations</a>, Up: <a href="#Profiling-R-code-for-memory-use" accesskey="u" rel="up">Profiling R code for memory use</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Tracing-copies-of-an-object-1"><span>3.3.3 Tracing copies of an object<a class="copiable-link" href="#Tracing-copies-of-an-object-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-tracemem"></a>
<a class="index-entry-id" id="index-untracemem"></a>

<p>The third method of memory profiling involves tracing copies made of a
specific (presumably large) R object. Calling <code class="code">tracemem</code> on an
object marks it so that a message is printed to standard output when
the object is copied <em class="emph">via</em> <code class="code">duplicate</code> or coercion to another type,
or when a new object of the same size is created in arithmetic
operations. The main reason that this can be misleading is that
copying of subsets or components of an object is not tracked. It may
be helpful to use <code class="code">tracemem</code> on these components.
</p>

<p>In the example above we can run <code class="code">tracemem</code> on the data frame
<code class="code">st</code>
</p>
<div class="example smallexample">
<pre class="example-preformatted">&gt; tracemem(st)
[1] &quot;&lt;0x9abd5e0&gt;&quot;
&gt; storm.boot &lt;- boot(rs, storm.bf, R = 4)
memtrace[0x9abd5e0-&gt;0x92a6d08]: statistic boot
memtrace[0x92a6d08-&gt;0x92a6d80]: $&lt;-.data.frame $&lt;- statistic boot
memtrace[0x92a6d80-&gt;0x92a6df8]: $&lt;-.data.frame $&lt;- statistic boot
memtrace[0x9abd5e0-&gt;0x9271318]: statistic boot
memtrace[0x9271318-&gt;0x9271390]: $&lt;-.data.frame $&lt;- statistic boot
memtrace[0x9271390-&gt;0x9271408]: $&lt;-.data.frame $&lt;- statistic boot
memtrace[0x9abd5e0-&gt;0x914f558]: statistic boot
memtrace[0x914f558-&gt;0x914f5f8]: $&lt;-.data.frame $&lt;- statistic boot
memtrace[0x914f5f8-&gt;0x914f670]: $&lt;-.data.frame $&lt;- statistic boot
memtrace[0x9abd5e0-&gt;0x972cbf0]: statistic boot
memtrace[0x972cbf0-&gt;0x972cc68]: $&lt;-.data.frame $&lt;- statistic boot
memtrace[0x972cc68-&gt;0x972cd08]: $&lt;-.data.frame $&lt;- statistic boot
memtrace[0x9abd5e0-&gt;0x98ead98]: statistic boot
memtrace[0x98ead98-&gt;0x98eae10]: $&lt;-.data.frame $&lt;- statistic boot
memtrace[0x98eae10-&gt;0x98eae88]: $&lt;-.data.frame $&lt;- statistic boot
</pre></div>

<p>The object is duplicated fifteen times, three times for each of the
<code class="code">R+1</code> calls to <code class="code">storm.bf</code>.  This is surprising, since none of the duplications happen inside <code class="code">nls</code>. Stepping through <code class="code">storm.bf</code> in the debugger shows that all three happen in the line
</p>
<div class="example smallexample">
<pre class="example-preformatted">st$Time &lt;- st$fit + rs[i]
</pre></div>

<p>Data frames are slower than matrices and this is an example of why.
Using <code class="code">tracemem(st$Viscosity)</code> does not reveal any additional
copying.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Profiling-compiled-code">
<div class="nav-panel">
<p>
Previous: <a href="#Profiling-R-code-for-memory-use" accesskey="p" rel="prev">Profiling R code for memory use</a>, Up: <a href="#Tidying-and-profiling-R-code" accesskey="u" rel="up">Tidying and profiling R code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Profiling-compiled-code-1"><span>3.4 Profiling compiled code<a class="copiable-link" href="#Profiling-compiled-code-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Profiling-2"></a>

<p>Profiling compiled code is highly system-specific, but this section
contains some hints gleaned from various R users.  Some methods need
to be different for a compiled executable and for dynamic/shared
libraries/objects as used by R packages.
</p>
<p>This chapter is based on reports from users and the information may not
be current.
</p>

<ul class="mini-toc">
<li><a href="#Profilong-on-Linux" accesskey="1">Profiling on Linux</a></li>
<li><a href="#Profiling-on-macOS" accesskey="2">Profiling on macOS</a></li>
<li><a href="#Profiling-on-Windows" accesskey="3">Profiling on Windows</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Profilong-on-Linux">
<div class="nav-panel">
<p>
Next: <a href="#Profiling-on-macOS" accesskey="n" rel="next">Profiling on macOS</a>, Previous: <a href="#Profiling-compiled-code" accesskey="p" rel="prev">Profiling compiled code</a>, Up: <a href="#Profiling-compiled-code" accesskey="u" rel="up">Profiling compiled code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Profiling-on-Linux"><span>3.4.1 Profiling on Linux<a class="copiable-link" href="#Profiling-on-Linux"> &para;</a></span></h4>

<p>Options include using <code class="command">sprof</code> for a shared object, and
<code class="command">oprofile</code> (see <a class="uref" href="https://oprofile.sourceforge.io/news/">https://oprofile.sourceforge.io/news/</a>)
and <code class="command">perf</code> (see
<a class="uref" href="https://perf.wiki.kernel.org/index.php/Tutorial">https://perf.wiki.kernel.org/index.php/Tutorial</a>) for any
executable or shared object.  These seem less widely supplied than they
used to be.  There is also &lsquo;Google Performance Tools&rsquo;, also known as
<strong class="strong">gperftools</strong> or <strong class="strong">google-perftools</strong>.
</p>
<p>All of these work best when R and any packages have been built with
debugging symbols.
</p>
<ul class="mini-toc">
<li><a href="#perf" accesskey="1"><code class="command">perf</code></a></li>
<li><a href="#oprofile-and-operf" accesskey="2"><code class="command">oprofile</code> and <code class="command">operf</code></a></li>
<li><a href="#sprof" accesskey="3"><code class="command">sprof</code></a></li>
</ul>
<div class="subsubsection-level-extent" id="perf">
<h4 class="subsubsection"><span>3.4.1.1 <code class="command">perf</code><a class="copiable-link" href="#perf"> &para;</a></span></h4>

<p>This seems the most widely distributed tool.
Here is an example on <code class="code">x86_64</code> Linux using R 4.3.1 built with <abbr class="abbr">LTO</abbr>.
</p>
<p>At its simplest
</p><div class="example">
<pre class="example-preformatted">perf record R -f tests/Examples/stats-Ex.R
perf report --sort=dso
perf report --sort=srcfile
rm perf.data*
</pre></div>

<p>The first report is
</p><div class="example">
<pre class="example-preformatted">  75.67%  R
   9.25%  libc.so.6
   4.87%  [unknown]
   3.75%  libz.so.1.2.11
   3.37%  stats.so
   1.17%  libm.so.6
   0.63%  libtirpc.so.3.0.0
   0.41%  graphics.so
   0.30%  grDevices.so
   0.20%  libRblas.so
   0.09%  libpcre2-8.so.0.11.0
   0.07%  methods.so
   ...
</pre></div>
<p>which shows which shared libraries (<abbr class="abbr">DSO</abbr>s) the time was spent in.
</p>
<p><code class="command">perf annotate</code> can be used on an application built with GCC and
<samp class="option">-ggdb</samp>: it interleaves disassembled and source code.
</p>
</div>
<div class="subsubsection-level-extent" id="oprofile-and-operf">
<h4 class="subsubsection"><span>3.4.1.2 <code class="command">oprofile</code> and <code class="command">operf</code><a class="copiable-link" href="#oprofile-and-operf"> &para;</a></span></h4>

<p>The <code class="command">oprofile</code> project has two modes of operation.  Since
version 0.9.8 (August 2012), the preferred mode is to use
<code class="command">operf</code>, so we discuss only that.
</p>
<p>Let us look at the <strong class="strong">boot</strong> example from §3.2 on <code class="code">x86_64</code> Linux
using R 4.3.1.
</p>
<p>This can be run under <code class="command">operf</code> and analysed by commands like
</p><div class="example">
<pre class="example-preformatted">operf R -f boot.R
opreport
opreport -l /path/to/R_HOME/bin/exec/R
opreport -l /path/to/R_HOME/library/stats/src/stats.so
opannotate --source /path/to/R_HOME/bin/exec/R
</pre></div>
<p>The first line had to be done as root.
</p>
<p>The first report shows in which library (etc) the time was spent:
</p><div class="example">
<pre class="example-preformatted">	CPU_CLK_UNHALT...|
	  samples|      %|
	------------------
	   278341 91.9947 R
	    18290  6.0450 libc.so.6
	     2277  0.7526 kallsyms
	     1426  0.4713 stats.so
	      739  0.2442 libRblas.so
	      554  0.1831 libz.so.1.2.11
	      373  0.1233 libm.so.6
	      352  0.1163 libtirpc.so.3.0.0
	      153  0.0506 ld-linux-x86-64.so.2
	       12  0.0040 methods.so
</pre></div>
<p>(<code class="code">kallsyms</code> is the kernel.)
</p>
<p>The rest of the output is voluminous, and only extracts are shown.
</p>
<p>Most of the time within R is spent in
</p><div class="example">
<pre class="example-preformatted">samples  %        image name symbol name
52955    19.0574  R                        bcEval.lto_priv.0
16484     5.9322  R                        Rf_allocVector3
14224     5.1189  R                        Rf_findVarInFrame3
12581     4.5276  R                        CONS_NR
8289      2.9830  R                        Rf_matchArgs_NR
8034      2.8913  R                        Rf_cons
7114      2.5602  R                        R_gc_internal.lto_priv.0
6552      2.3579  R                        Rf_eval
5969      2.1481  R                        VECTOR_ELT
5684      2.0456  R                        Rf_applyClosure
5497      1.9783  R                        findVarLocInFrame.part.0.lto_priv.0
4827      1.7371  R                        Rf_mkPROMISE
4609      1.6587  R                        Rf_install
4317      1.5536  R                        Rf_findFun3
4035      1.4521  R                        getvar.lto_priv.0
3491      1.2563  R                        SETCAR
3179      1.1441  R                        Rf_defineVar
2892      1.0408  R                        duplicate1.lto_priv.0
</pre></div>

<p>and in <code class="code">stats.so</code>
</p><div class="example">
<pre class="example-preformatted">samples  %        image name               symbol name
285      24.4845  stats.so                 termsform
284      24.3986  stats.so                 numeric_deriv
213      18.2990  stats.so                 modelframe
114       9.7938  stats.so                 nls_iter
55        4.7251  stats.so                 ExtractVars
47        4.0378  stats.so                 EncodeVars
37        3.1787  stats.so                 getListElement
32        2.7491  stats.so                 TrimRepeats
25        2.1478  stats.so                 InstallVar
20        1.7182  stats.so                 MatchVar
20        1.7182  stats.so                 isZeroOne
15        1.2887  stats.so                 ConvInfoMsg.isra.0
</pre></div>

<p>The profiling data is by default stored in sub-directory
<samp class="file">oprofile_data</samp> of the current directory, which can be removed at
the end of the session.
</p>

</div>
<div class="subsubsection-level-extent" id="sprof">
<h4 class="subsubsection"><span>3.4.1.3 <code class="command">sprof</code><a class="copiable-link" href="#sprof"> &para;</a></span></h4>

<p>You can select shared objects to be profiled with <code class="command">sprof</code> by
setting the environment variable <code class="env">LD_PROFILE</code>.  For example
</p>
<div class="example">
<pre class="example-preformatted">% setenv LD_PROFILE /path/to/R_HOME/library/stats/libs/stats.so
% R -f boot.R
% sprof /path/to/R_HOME/library/stats/libs/stats.so \
  /var/tmp/path/to/R_HOME/library/stats/libs/stats.so.profile

Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  us/call  us/call  name
 76.19      0.32     0.32        0     0.00           numeric_deriv
 16.67      0.39     0.07        0     0.00           nls_iter
  7.14      0.42     0.03        0     0.00           getListElement

... to clean up ...
rm /var/tmp/path/to/R_HOME/library/stats/libs/stats.so.profile
</pre></div>

<p>It is possible that root access will be needed to create the directories
used for the profile data.
</p>
<hr>
</div>
</div>
<div class="subsection-level-extent" id="Profiling-on-macOS">
<div class="nav-panel">
<p>
Next: <a href="#Profiling-on-Windows" accesskey="n" rel="next">Profiling on Windows</a>, Previous: <a href="#Profilong-on-Linux" accesskey="p" rel="prev">Profiling on Linux</a>, Up: <a href="#Profiling-compiled-code" accesskey="u" rel="up">Profiling compiled code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Profiling-on-macOS-1"><span>3.4.2 Profiling on macOS<a class="copiable-link" href="#Profiling-on-macOS-1"> &para;</a></span></h4>

<p>Developers have recommended <code class="command">Instruments</code> (part of <code class="code">Xcode</code>,
see <a class="uref" href="https://help.apple.com/instruments/mac/current/">https://help.apple.com/instruments/mac/current/</a>), This had a
command-line version prior to macOS 12.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Profiling-on-Windows">
<div class="nav-panel">
<p>
Previous: <a href="#Profiling-on-macOS" accesskey="p" rel="prev">Profiling on macOS</a>, Up: <a href="#Profiling-compiled-code" accesskey="u" rel="up">Profiling compiled code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Profiling-on-Windows-1"><span>3.4.3 Profiling on Windows<a class="copiable-link" href="#Profiling-on-Windows-1"> &para;</a></span></h4>

<p><code class="command">Very Sleepy</code>
(<a class="uref" href="https://github.com/VerySleepy/verysleepy">https://github.com/VerySleepy/verysleepy</a>) has been used on
&lsquo;<samp class="samp">x86_64</samp>&rsquo; Windows.  There were
problems with accessing the debug information, but the best results which
included function names were obtained by attaching the profiler to an
existing <code class="command">Rterm</code> process, either via GUI or using <samp class="option">/a:</samp>
(<abbr class="abbr">PID</abbr> obtained via <code class="command">Sys.getpid()</code>).
</p>
<hr>
</div>
</div>
</div>
<div class="chapter-level-extent" id="Debugging">
<div class="nav-panel">
<p>
Next: <a href="#System-and-foreign-language-interfaces" accesskey="n" rel="next">System and foreign language interfaces</a>, Previous: <a href="#Tidying-and-profiling-R-code" accesskey="p" rel="prev">Tidying and profiling R code</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="chapter" id="Debugging-1"><span>4 Debugging<a class="copiable-link" href="#Debugging-1"> &para;</a></span></h2>

<p>This chapter covers the debugging of R extensions, starting with the
ways to get useful error information and moving on to how to deal with
errors that crash R.
</p>


<ul class="mini-toc">
<li><a href="#Browsing" accesskey="1">Browsing</a></li>
<li><a href="#Debugging-R-code" accesskey="2">Debugging R code</a></li>
<li><a href="#Checking-memory-access" accesskey="3">Checking memory access</a></li>
<li><a href="#Debugging-compiled-code" accesskey="4">Debugging compiled code</a></li>
<li><a href="#Using-Link_002dtime-Optimization" accesskey="5">Using Link-time Optimization</a></li>
</ul>
<hr>
<div class="section-level-extent" id="Browsing">
<div class="nav-panel">
<p>
Next: <a href="#Debugging-R-code" accesskey="n" rel="next">Debugging R code</a>, Previous: <a href="#Debugging" accesskey="p" rel="prev">Debugging</a>, Up: <a href="#Debugging" accesskey="u" rel="up">Debugging</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Browsing-1"><span>4.1 Browsing<a class="copiable-link" href="#Browsing-1"> &para;</a></span></h3>

<a class="index-entry-id" id="index-browser"></a>
<p>Most of the R-level debugging facilities are based around the
built-in browser.  This can be used directly by inserting a call to
<code class="code">browser()</code> into the code of a function (for example, using
<code class="code">fix(my_function)</code> ).  When code execution reaches that point in
the function, control returns to the R console with a special prompt.
For example
</p>
<div class="example">
<pre class="example-preformatted">&gt; fix(summary.data.frame) ## insert browser() call after for() loop
&gt; summary(women)
Called from: summary.data.frame(women)
Browse[1]&gt; ls()
 [1] &quot;digits&quot; &quot;i&quot;      &quot;lbs&quot;    &quot;lw&quot;     &quot;maxsum&quot; &quot;ncw&quot;    &quot;nm&quot;     &quot;nr&quot;    
 [9] &quot;nv&quot;     &quot;object&quot; &quot;sms&quot;    &quot;z&quot;     
Browse[1]&gt; maxsum
[1] 7
Browse[1]&gt; c
     height         weight
 Min.   :58.0   Min.   :115.0
 1st Qu.:61.5   1st Qu.:124.5
 Median :65.0   Median :135.0
 Mean   :65.0   Mean   :136.7
 3rd Qu.:68.5   3rd Qu.:148.0
 Max.   :72.0   Max.   :164.0
&gt; rm(summary.data.frame)
</pre></div>

<p>At the browser prompt one can enter any R expression, so for example
<code class="code">ls()</code> lists the objects in the current frame, and entering the
name of an object will<a class="footnote" id="DOCF125" href="#FOOT125"><sup>125</sup></a> print it.  The following commands are
also accepted
</p>
<ul class="itemize mark-bullet">
<li><code class="code">n</code>

<p>Enter &lsquo;step-through&rsquo; mode.  In this mode, hitting return executes the
next line of code (more precisely one line and any continuation lines).
Typing <code class="code">c</code> will continue to the end of the current context, e.g.
to the end of the current loop or function.
</p>
</li><li><code class="code">c</code>

<p>In normal mode, this quits the browser and continues execution, and just
return works in the same way.  <code class="code">cont</code> is a synonym.
</p>
</li><li><code class="code">where</code>

<p>This prints the call stack.  For example
</p>
<div class="example">
<pre class="example-preformatted">&gt; summary(women)
Called from: summary.data.frame(women)
Browse[1]&gt; where
where 1: summary.data.frame(women)
where 2: summary(women)

Browse[1]&gt;
</pre></div>

</li><li><code class="code">Q</code>

<p>Quit both the browser and the current expression, and return to the
top-level prompt.
</p></li></ul>

<p>Errors in code executed at the browser prompt will normally return
control to the browser prompt.  Objects can be altered by assignment,
and will keep their changed values when the browser is exited.  If
really necessary, objects can be assigned to the workspace from the
browser prompt (by using <code class="code">&lt;&lt;-</code> if the name is not already in
scope).
</p>
<hr>
</div>
<div class="section-level-extent" id="Debugging-R-code">
<div class="nav-panel">
<p>
Next: <a href="#Checking-memory-access" accesskey="n" rel="next">Checking memory access</a>, Previous: <a href="#Browsing" accesskey="p" rel="prev">Browsing</a>, Up: <a href="#Debugging" accesskey="u" rel="up">Debugging</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Debugging-R-code-1"><span>4.2 Debugging R code<a class="copiable-link" href="#Debugging-R-code-1"> &para;</a></span></h3>

<a class="index-entry-id" id="index-traceback"></a>
<p>Suppose your R program gives an error message.  The first thing to
find out is what R was doing at the time of the error, and the most
useful tool is <code class="code">traceback()</code>.  We suggest that this is run whenever
the cause of the error is not immediately obvious.  Errors are often
reported to the R mailing lists as being in some package when
<code class="code">traceback()</code> would show that the error was being reported by some
other package or base R.  Here is an example from the regression
suite.
</p>
<div class="example smallexample">
<pre class="example-preformatted">&gt; success &lt;- c(13,12,11,14,14,11,13,11,12)
&gt; failure &lt;- c(0,0,0,0,0,0,0,2,2)
&gt; resp &lt;- cbind(success, failure)
&gt; predictor &lt;- c(0, 5^(0:7))
&gt; glm(resp ~ 0+predictor, family = binomial(link=&quot;log&quot;))
Error: no valid set of coefficients has been found: please supply starting values
&gt; traceback()
3: stop(&quot;no valid set of coefficients has been found: please supply
         starting values&quot;, call. = FALSE)
2: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastart,
       mustart = mustart, offset = offset, family = family, control = control,
       intercept = attr(mt, &quot;intercept&quot;) &gt; 0)
1: glm(resp ~ 0 + predictor, family = binomial(link =&quot;log&quot;))
</pre></div>

<p>The calls to the active frames are given in reverse order (starting with
the innermost).  So we see the error message comes from an explicit
check in <code class="code">glm.fit</code>.  (<code class="code">traceback()</code> shows you all the lines of
the function calls, which can be limited by setting <code class="code">option</code>
<samp class="option">&quot;deparse.max.lines&quot;</samp>.)
</p>
<p>Sometimes the traceback will indicate that the error was detected inside
compiled code, for example (from <code class="code">?nls</code>)
</p>
<div class="example smallexample">
<pre class="example-preformatted">Error in nls(y ~ a + b * x, start = list(a = 0.12345, b = 0.54321), trace = TRUE) :
        step factor 0.000488281 reduced below ‘minFactor’ of 0.000976563
&gt;  traceback()
2: .Call(R_nls_iter, m, ctrl, trace)
1: nls(y ~ a + b * x, start = list(a = 0.12345, b = 0.54321), trace = TRUE)
</pre></div>

<p>This will be the case if the innermost call is to <code class="code">.C</code>,
<code class="code">.Fortran</code>, <code class="code">.Call</code>, <code class="code">.External</code> or <code class="code">.Internal</code>, but
as it is also possible for such code to evaluate R expressions, this
need not be the innermost call, as in
</p>
<div class="example smallexample">
<pre class="example-preformatted">&gt; traceback()
9: gm(a, b, x)
8: .Call(R_numeric_deriv, expr, theta, rho, dir)
7: numericDeriv(form[[3]], names(ind), env)
6: getRHS()
5: assign(&quot;rhs&quot;, getRHS(), envir = thisEnv)
4: assign(&quot;resid&quot;, .swts * (lhs - assign(&quot;rhs&quot;, getRHS(), envir = thisEnv)),
       envir = thisEnv)
3: function (newPars)
   {
       setPars(newPars)
       assign(&quot;resid&quot;, .swts * (lhs - assign(&quot;rhs&quot;, getRHS(), envir = thisEnv)),
           envir = thisEnv)
       assign(&quot;dev&quot;, sum(resid^2), envir = thisEnv)
       assign(&quot;QR&quot;, qr(.swts * attr(rhs, &quot;gradient&quot;)), envir = thisEnv)
       return(QR$rank &lt; min(dim(QR$qr)))
   }(c(-0.00760232418963883, 1.00119632515036))
2: .Call(R_nls_iter, m, ctrl, trace)
1: nls(yeps ~ gm(a, b, x), start = list(a = 0.12345, b = 0.54321))
</pre></div>

<p>Occasionally <code class="code">traceback()</code> does not help, and this can be the case
if S4 method dispatch is involved.  Consider the following example
</p>
<div class="example">
<pre class="example-preformatted">&gt; xyd &lt;- new(&quot;xyloc&quot;, x=runif(20), y=runif(20))
Error in as.environment(pkg) : no item called &quot;package:S4nswv&quot;
on the search list
Error in initialize(value, ...) : S language method selection got
an error when called from internal dispatch for function ‘initialize’
&gt; traceback()
2: initialize(value, ...)
1: new(&quot;xyloc&quot;, x = runif(20), y = runif(20))
</pre></div>

<p>which does not help much, as there is no call to <code class="code">as.environment</code>
in <code class="code">initialize</code> (and the note &ldquo;called from internal dispatch&rdquo;
tells us so).  In this case we searched the R sources for the quoted
call, which occurred in only one place,
<code class="code">methods:::.asEnvironmentPackage</code>.  So now we knew where the
error was occurring.  (This was an unusually opaque example.)
</p>
<p>The error message
</p>
<div class="example">
<pre class="example-preformatted">evaluation nested too deeply: infinite recursion / options(expressions=)?
</pre></div>

<p>can be hard to handle with the default value (5000).  Unless you know
that there actually is deep recursion going on, it can help to set
something like
</p>
<div class="example">
<pre class="example-preformatted">options(expressions=500)
</pre></div>

<p>and re-run the example showing the error.
</p>
<p>Sometimes there is warning that clearly is the precursor to some later
error, but it is not obvious where it is coming from.  Setting
<code class="command">options(warn = 2)</code> (which turns warnings into errors) can help here.
</p>
<p>Once we have located the error, we have some choices.  One way to proceed
is to find out more about what was happening at the time of the crash by
looking a <em class="emph">post-mortem</em> dump.  To do so, set
<a class="index-entry-id" id="index-dump_002eframes"></a>
<code class="command">options(error=dump.frames)</code> and run the code again.  Then invoke
<code class="command">debugger()</code> and explore the dump.  Continuing our example:
</p>
<div class="example smallexample">
<pre class="example-preformatted">&gt; options(error = dump.frames)
&gt; glm(resp ~ 0 + predictor, family = binomial(link =&quot;log&quot;))
Error: no valid set of coefficients has been found: please supply starting values
</pre></div>

<p>which is the same as before, but an object called <code class="code">last.dump</code> has
appeared in the workspace.  (Such objects can be large, so remove it
when it is no longer needed.)  We can examine this at a later time by
calling the function <code class="code">debugger</code>.
<a class="index-entry-id" id="index-debugger"></a>
</p>
<div class="example smallexample">
<pre class="example-preformatted">&gt; debugger()
Message:  Error: no valid set of coefficients has been found: please supply starting values
Available environments had calls:
1: glm(resp ~ 0 + predictor, family = binomial(link = &quot;log&quot;))
2: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastart, mus
3: stop(&quot;no valid set of coefficients has been found: please supply starting values
Enter an environment number, or 0 to exit  Selection:
</pre></div>

<p>which gives the same sequence of calls as <code class="code">traceback</code>, but in
outer-first order and with only the first line of the call, truncated to
the current width.  However, we can now examine in more detail what was
happening at the time of the error.  Selecting an environment opens the
browser in that frame.  So we select the function call which spawned the
error message, and explore some of the variables (and execute two
function calls).
</p>
<div class="example smallexample">
<pre class="example-preformatted">Enter an environment number, or 0 to exit  Selection: 2
Browsing in the environment with call:
   glm.fit(x = X, y = Y, weights = weights, start = start, etas
Called from: debugger.look(ind)
Browse[1]&gt; ls()
 [1] &quot;aic&quot;        &quot;boundary&quot;   &quot;coefold&quot;    &quot;control&quot;    &quot;conv&quot;
 [6] &quot;dev&quot;        &quot;dev.resids&quot; &quot;devold&quot;     &quot;EMPTY&quot;      &quot;eta&quot;
[11] &quot;etastart&quot;   &quot;family&quot;     &quot;fit&quot;        &quot;good&quot;       &quot;intercept&quot;
[16] &quot;iter&quot;       &quot;linkinv&quot;    &quot;mu&quot;         &quot;mu.eta&quot;     &quot;mu.eta.val&quot;
[21] &quot;mustart&quot;    &quot;n&quot;          &quot;ngoodobs&quot;   &quot;nobs&quot;       &quot;nvars&quot;
[26] &quot;offset&quot;     &quot;start&quot;      &quot;valideta&quot;   &quot;validmu&quot;    &quot;variance&quot;
[31] &quot;varmu&quot;      &quot;w&quot;          &quot;weights&quot;    &quot;x&quot;          &quot;xnames&quot;
[36] &quot;y&quot;          &quot;ynames&quot;     &quot;z&quot;
Browse[1]&gt; eta
            1             2             3             4             5
 0.000000e+00 -2.235357e-06 -1.117679e-05 -5.588393e-05 -2.794197e-04
            6             7             8             9
-1.397098e-03 -6.985492e-03 -3.492746e-02 -1.746373e-01
Browse[1]&gt; valideta(eta)
[1] TRUE
Browse[1]&gt; mu
        1         2         3         4         5         6         7         8
1.0000000 0.9999978 0.9999888 0.9999441 0.9997206 0.9986039 0.9930389 0.9656755
        9
0.8397616
Browse[1]&gt; validmu(mu)
[1] FALSE
Browse[1]&gt; c
Available environments had calls:
1: glm(resp ~ 0 + predictor, family = binomial(link = &quot;log&quot;))
2: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastart
3: stop(&quot;no valid set of coefficients has been found: please supply starting v

Enter an environment number, or 0 to exit  Selection: 0
&gt; rm(last.dump)
</pre></div>

<p>Because <code class="code">last.dump</code> can be looked at later or even in another R
session, post-mortem debugging is possible even for batch usage of R.
We do need to arrange for the dump to be saved: this can be done either
using the command-line flag <samp class="option">--save</samp> to save the workspace at the
end of the run, or <em class="emph">via</em> a setting such as
</p>
<div class="example">
<pre class="example-preformatted">&gt; options(error = quote({dump.frames(to.file=TRUE); q()}))
</pre></div>

<p>See the help on <code class="code">dump.frames</code> for further options and a worked
example.
</p>
<a class="index-entry-id" id="index-recover"></a>
<p>An alternative error action is to use the function <code class="command">recover()</code>:
</p>
<div class="example smallexample">
<pre class="example-preformatted">&gt; options(error = recover)
&gt; glm(resp ~ 0 + predictor, family = binomial(link = &quot;log&quot;))
Error: no valid set of coefficients has been found: please supply starting values

Enter a frame number, or 0 to exit

1: glm(resp ~ 0 + predictor, family = binomial(link = &quot;log&quot;))
2: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastart

Selection:
</pre></div>

<p>which is very similar to <code class="code">dump.frames</code>.  However, we can examine
the state of the program directly, without dumping and re-loading the
dump.  As its help page says, <code class="code">recover</code> can be routinely used as
the error action in place of <code class="code">dump.calls</code> and <code class="code">dump.frames</code>,
since it behaves like <code class="code">dump.frames</code> in non-interactive use.
</p>

<a class="index-entry-id" id="index-debug"></a>
<p>Post-mortem debugging is good for finding out exactly what went wrong,
but not necessarily why.  An alternative approach is to take a closer
look at what was happening just before the error, and a good way to do
that is to use <code class="command">debug</code>.  This inserts a call to the browser
at the beginning of the function, starting in step-through mode.  So in
our example we could use
</p>
<div class="example smallexample">
<pre class="example-preformatted">&gt; debug(glm.fit)
&gt; glm(resp ~ 0 + predictor, family = binomial(link =&quot;log&quot;))
debugging in: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastart,
    mustart = mustart, offset = offset, family = family, control = control,
    intercept = attr(mt, &quot;intercept&quot;) &gt; 0)
debug: {
## lists the whole function
Browse[1]&gt;
debug: x &lt;- as.matrix(x)
...
Browse[1]&gt; start
[1] -2.235357e-06
debug: eta &lt;- drop(x %*% start)
Browse[1]&gt; eta
            1             2             3             4             5
 0.000000e+00 -2.235357e-06 -1.117679e-05 -5.588393e-05 -2.794197e-04
            6             7             8             9
-1.397098e-03 -6.985492e-03 -3.492746e-02 -1.746373e-01
Browse[1]&gt;
debug: mu &lt;- linkinv(eta &lt;- eta + offset)
Browse[1]&gt; mu
        1         2         3         4         5         6         7         8
1.0000000 0.9999978 0.9999888 0.9999441 0.9997206 0.9986039 0.9930389 0.9656755
        9
0.8397616
</pre></div>

<p>(The prompt <code class="code">Browse[1]&gt;</code> indicates that this is the first level of
browsing: it is possible to step into another function that is itself
being debugged or contains a call to <code class="code">browser()</code>.)
</p>
<p><code class="code">debug</code> can be used for hidden functions and S3 methods by
e.g. <code class="code">debug(stats:::predict.Arima)</code>.  (It cannot be used for S4
methods, but an alternative is given on the help page for <code class="code">debug</code>.)
Sometimes you want to debug a function defined inside another function,
e.g. the function <code class="code">arimafn</code> defined inside <code class="code">arima</code>.  To do so,
set <code class="code">debug</code> on the outer function (here <code class="code">arima</code>) and
step through it until the inner function has been defined.  Then
call <code class="code">debug</code> on the inner function (and use <code class="code">c</code> to get out of
step-through mode in the outer function).
</p>
<a class="index-entry-id" id="index-undebug"></a>
<p>To remove debugging of a function, call <code class="code">undebug</code> with the argument
previously given to <code class="code">debug</code>; debugging otherwise lasts for the rest
of the R session (or until the function is edited or otherwise
replaced).
</p>
<a class="index-entry-id" id="index-trace"></a>
<p><code class="code">trace</code> can be used to temporarily insert debugging code into a
function, for example to insert a call to <code class="code">browser()</code> just before
the point of the error.  To return to our running example
</p>
<div class="example">
<pre class="example-preformatted">## first get a numbered listing of the expressions of the function
&gt; page(as.list(body(glm.fit)), method=&quot;print&quot;)
&gt; trace(glm.fit, browser, at=22)
Tracing function &quot;glm.fit&quot; in package &quot;stats&quot;
[1] &quot;glm.fit&quot;
&gt; glm(resp ~ 0 + predictor, family = binomial(link =&quot;log&quot;))
Tracing glm.fit(x = X, y = Y, weights = weights, start = start,
   etastart = etastart,  .... step 22
Called from: eval(expr, envir, enclos)
Browse[1]&gt; n
## and single-step from here.
&gt; untrace(glm.fit)
</pre></div>
<p>For your own functions, it may be as easy to use <code class="code">fix</code> to insert
temporary code, but <code class="code">trace</code> can help with functions in a namespace
(as can <code class="code">fixInNamespace</code>).  Alternatively, use
<code class="code">trace(,edit=TRUE)</code> to insert code visually.
</p>

<hr>
</div>
<div class="section-level-extent" id="Checking-memory-access">
<div class="nav-panel">
<p>
Next: <a href="#Debugging-compiled-code" accesskey="n" rel="next">Debugging compiled code</a>, Previous: <a href="#Debugging-R-code" accesskey="p" rel="prev">Debugging R code</a>, Up: <a href="#Debugging" accesskey="u" rel="up">Debugging</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Checking-memory-access-1"><span>4.3 Checking memory access<a class="copiable-link" href="#Checking-memory-access-1"> &para;</a></span></h3>

<p>Errors in memory allocation and reading/writing outside arrays are very
common causes of crashes (e.g., segfaults) on some machines.  Often
the crash appears long after the invalid memory access: in particular
damage to the structures which R itself has allocated may only become
apparent at the next garbage collection (or even at later garbage
collections after objects have been deleted).
</p>
<p>Note that memory access errors may be seen with LAPACK, BLAS, <abbr class="abbr">OpenMP</abbr> and
Java-using packages: some at least of these seem to be intentional, and
some are related to passing characters to Fortran.
</p>
<p>Some of these tools can detect mismatched allocation and deallocation.
C++ programmers should note that memory allocated by <code class="code">new []</code> must
be freed by <code class="code">delete []</code>, other uses of <code class="code">new</code> by <code class="code">delete</code>,
and memory allocated by <code class="code">malloc</code>, <code class="code">calloc</code> and <code class="code">realloc</code>
by <code class="code">free</code>.  Some platforms will tolerate mismatches (perhaps with
memory leaks) but others will segfault.
</p>

<ul class="mini-toc">
<li><a href="#Using-gctorture" accesskey="1">Using <code class="code">gctorture</code></a></li>
<li><a href="#Using-valgrind" accesskey="2">Using Valgrind</a></li>
<li><a href="#Using-Address-Sanitizer" accesskey="3">Using the Address Sanitizer</a></li>
<li><a href="#Using-Undefined-Behaviour-Sanitizer" accesskey="4">Using the Undefined Behaviour Sanitizer</a></li>
<li><a href="#Other-analyses-with-_0060clang_0027" accesskey="5">Other analyses with &lsquo;clang&rsquo;</a></li>
<li><a href="#Other-analyses-with-_0060gcc_0027" accesskey="6">Other analyses with &lsquo;gcc&rsquo;</a></li>
<li><a href="#Using-_0060Dr_002e-Memory_0027" accesskey="7">Using &lsquo;Dr. Memory&rsquo;</a></li>
<li><a href="#Fortran-array-bounds-checking" accesskey="8">Fortran array bounds checking</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Using-gctorture">
<div class="nav-panel">
<p>
Next: <a href="#Using-valgrind" accesskey="n" rel="next">Using Valgrind</a>, Previous: <a href="#Checking-memory-access" accesskey="p" rel="prev">Checking memory access</a>, Up: <a href="#Checking-memory-access" accesskey="u" rel="up">Checking memory access</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-gctorture-1"><span>4.3.1 Using <code class="code">gctorture</code><a class="copiable-link" href="#Using-gctorture-1"> &para;</a></span></h4>

<a class="index-entry-id" id="index-gctorture"></a>
<p>We can help to detect memory problems in R objects earlier by running
garbage collection as often as possible.  This is achieved by
<code class="code">gctorture(TRUE)</code>, which as described on its help page
</p>
<blockquote class="quotation">
<p>Provokes garbage collection on (nearly) every memory allocation.
Intended to ferret out memory protection bugs.  Also makes R run
<em class="emph">very</em> slowly, unfortunately.
</p></blockquote>

<p>The reference to &lsquo;memory protection&rsquo; is to missing C-level calls to
<code class="code">PROTECT</code>/<code class="code">UNPROTECT</code> (see <a class="pxref" href="#Garbage-Collection">Handling the effects of garbage collection</a>) which if
missing allow R objects to be garbage-collected when they are still
in use.  But it can also help with other memory-related errors.
</p>
<p>Normally running under <code class="code">gctorture(TRUE)</code> will just produce a crash
earlier in the R program, hopefully close to the actual cause. See
the next section for how to decipher such crashes.
</p>
<p>It is possible to run all the examples, tests and vignettes covered by
<code class="code">R CMD check</code> under <code class="code">gctorture(TRUE)</code> by using the option
<samp class="option">--use-gct</samp>.
</p>
<p>The function <code class="code">gctorture2</code> provides more refined control over the <abbr class="abbr">GC</abbr>
torture process.  Its arguments <code class="code">step</code>, <code class="code">wait</code> and
<code class="code">inhibit_release</code> are documented on its help page.  Environment
variables can also be used at the start of the R session to turn on
<abbr class="abbr">GC</abbr> torture: <code class="env">R_GCTORTURE</code> corresponds to the <code class="code">step</code> argument to
<code class="code">gctorture2</code>, <code class="env">R_GCTORTURE_WAIT</code> to <code class="code">wait</code>, and
<code class="env">R_GCTORTURE_INHIBIT_RELEASE</code> to <code class="code">inhibit_release</code>.
</p>
<p>If R is configured with <samp class="option">--enable-strict-barrier</samp> then a
variety of tests for the integrity of the write barrier are enabled.  In
addition tests to help detect protect issues are enabled:
</p>
<ul class="itemize mark-bullet">
<li>All <abbr class="abbr">GC</abbr>s are full <abbr class="abbr">GC</abbr>s.

</li><li>New nodes in small node pages are marked as <code class="code">NEWSXP</code> on creation.

</li><li>After a <abbr class="abbr">GC</abbr> all free nodes that are not of type <code class="code">NEWSXP</code> are marked
as type <code class="code">FREESXP</code> and their previous type is recorded.

</li><li>Most calls to accessor functions check their <code class="code">SEXP</code> inputs and
<code class="code">SEXP</code> outputs and signal an error if a <code class="code">FREESXP</code> is found.
The address of the node and the old type are included in the error
message.

</li></ul>

<p><code class="code">R CMD check --use-gct</code> can be set to use
<code class="code">gctorture2(<var class="var">n</var>)</code> rather than <code class="code">gctorture(TRUE)</code> by setting
environment variable <code class="env">_R_CHECK_GCT_N_</code> to a positive integer value
to be used as <code class="code"><var class="var">n</var></code>.
</p>
<p>Used with a debugger and with <code class="code">gctorture</code> or <code class="code">gctorture2</code> this
mechanism can be helpful in isolating memory protect problems.
</p>

<hr>
</div>
<div class="subsection-level-extent" id="Using-valgrind">
<div class="nav-panel">
<p>
Next: <a href="#Using-Address-Sanitizer" accesskey="n" rel="next">Using the Address Sanitizer</a>, Previous: <a href="#Using-gctorture" accesskey="p" rel="prev">Using <code class="code">gctorture</code></a>, Up: <a href="#Checking-memory-access" accesskey="u" rel="up">Checking memory access</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-Valgrind"><span>4.3.2 Using Valgrind<a class="copiable-link" href="#Using-Valgrind"> &para;</a></span></h4>

<p>If you have access to Linux on a common CPU type or supported versions
of FreeBSD or Solaris<a class="footnote" id="DOCF126" href="#FOOT126"><sup>126</sup></a> you can use <code class="code">valgrind</code>
(<a class="uref" href="https://valgrind.org/">https://valgrind.org/</a>, pronounced to rhyme with &lsquo;tinned&rsquo;) to
check for possible problems.  To run some examples under <code class="code">valgrind</code>
use something like
</p>
<div class="example">
<pre class="example-preformatted">R -d valgrind --vanilla &lt; mypkg-Ex.R
R -d &quot;valgrind --tool=memcheck --leak-check=full&quot; --vanilla &lt; mypkg-Ex.R
</pre></div>

<p>where <samp class="file">mypkg-Ex.R</samp> is a set of examples, e.g. the file created in
<samp class="file">mypkg.Rcheck</samp> by <code class="code">R CMD check</code>.  Occasionally this reports
memory reads of &lsquo;uninitialised values&rsquo; that are the result of compiler
optimization, so can be worth checking under an unoptimized compile: for
maximal information use a build with debugging symbols.  We know there
will be some small memory leaks from <code class="code">readline</code> and R itself &mdash;
these are memory areas that are in use right up to the end of the R
session.  Expect this to run around 20x slower than without
<code class="code">valgrind</code>, and in some cases much slower than that.  Several
versions of <code class="code">valgrind</code> were not happy with some optimized BLAS libraries
that use <abbr class="acronym">CPU</abbr>-specific instructions so you may need to build a
version of R specifically to use with <code class="code">valgrind</code>.
</p>
<p>On platforms where <code class="code">valgrind</code> and its headers<a class="footnote" id="DOCF127" href="#FOOT127"><sup>127</sup></a>
are installed you can build a version of R with extra instrumentation
to help <code class="code">valgrind</code> detect errors in the use of memory allocated
from the R heap.  The <code class="command">configure</code> option is
<samp class="option">--with-valgrind-instrumentation=<var class="var">level</var></samp>, where <var class="var">level</var>
is 0, 1 or 2.  Level 0 is the default and does not add anything.  Level
1 will detect some uses<a class="footnote" id="DOCF128" href="#FOOT128"><sup>128</sup></a> of uninitialised memory and has little impact on speed
(compared to level 0). Level 2 will detect many other memory-use
bugs<a class="footnote" id="DOCF129" href="#FOOT129"><sup>129</sup></a>  but make R much slower when running under
<code class="code">valgrind</code>.  Using this in conjunction with <code class="code">gctorture</code> can be
even more effective (and even slower).
</p>
<p>An example of <code class="code">valgrind</code> output is
</p><div class="example smallexample">
<pre class="example-preformatted">==12539== Invalid read of size 4
==12539==    at 0x1CDF6CBE: csc_compTr (Mutils.c:273)
==12539==    by 0x1CE07E1E: tsc_transpose (dtCMatrix.c:25)
==12539==    by 0x80A67A7: do_dotcall (dotcode.c:858)
==12539==    by 0x80CACE2: Rf_eval (eval.c:400)
==12539==    by 0x80CB5AF: R_execClosure (eval.c:658)
==12539==    by 0x80CB98E: R_execMethod (eval.c:760)
==12539==    by 0x1B93DEFA: R_standardGeneric (methods_list_dispatch.c:624)
==12539==    by 0x810262E: do_standardGeneric (objects.c:1012)
==12539==    by 0x80CAD23: Rf_eval (eval.c:403)
==12539==    by 0x80CB2F0: Rf_applyClosure (eval.c:573)
==12539==    by 0x80CADCC: Rf_eval (eval.c:414)
==12539==    by 0x80CAA03: Rf_eval (eval.c:362)
==12539==  Address 0x1C0D2EA8 is 280 bytes inside a block of size 1996 alloc'd
==12539==    at 0x1B9008D1: malloc (vg_replace_malloc.c:149)
==12539==    by 0x80F1B34: GetNewPage (memory.c:610)
==12539==    by 0x80F7515: Rf_allocVector (memory.c:1915)
...
</pre></div>
<p>This example is from an instrumented version of R, while tracking
down a bug in the <a class="url" href="https://CRAN.R-project.org/package=Matrix"><strong class="strong">Matrix</strong></a> package in 2006.  The first line
indicates that R has tried to read 4 bytes from a memory address that
it does not have access to. This is followed by a C stack trace showing
where the error occurred. Next is a description of the memory that was
accessed. It is inside a block allocated by <code class="code">malloc</code>, called from
<code class="code">GetNewPage</code>, that is, in the internal R heap.  Since this
memory all belongs to R, <code class="code">valgrind</code> would not (and did not)
detect the problem in an uninstrumented build of R.  In this example
the stack trace was enough to isolate and fix the bug, which was in
<code class="code">tsc_transpose</code>, and in this example running under
<code class="code">gctorture()</code> did not provide any additional information.
</p>
<p><code class="command">valgrind</code> is good at spotting the use of uninitialized values:
use option <samp class="option">--track-origins=yes</samp> to show where these originated
from.  What it cannot detect is the misuse of arrays allocated on the
stack: this includes C automatic variables and some<a class="footnote" id="DOCF130" href="#FOOT130"><sup>130</sup></a>
Fortran arrays.
</p>
<p>It is possible to run all the examples, tests and vignettes covered by
<code class="code">R CMD check</code> under <code class="code">valgrind</code> by using the option
<samp class="option">--use-valgrind</samp>.  If you do this you will need to select the
<code class="code">valgrind</code> options some other way, for example by having a
<samp class="file">~/.valgrindrc</samp> file containing
</p>
<div class="example">
<pre class="example-preformatted">--leak-check=full
--track-origins=yes
</pre></div>

<p>or setting the environment variable <code class="env">VALGRIND_OPTS</code>.  As from R
4.2.0, <samp class="option">--use-valgrind</samp> also uses <code class="command">valgrind</code> when
re-building the vignettes.
</p>

<p>This section has described the use of <code class="command">memtest</code>, the default
(and most useful) of <code class="code">valgrind</code>&rsquo;s tools.  There are others
described in its documentation: <code class="command">helgrind</code> can be useful for
threaded programs.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Using-Address-Sanitizer">
<div class="nav-panel">
<p>
Next: <a href="#Using-Undefined-Behaviour-Sanitizer" accesskey="n" rel="next">Using the Undefined Behaviour Sanitizer</a>, Previous: <a href="#Using-valgrind" accesskey="p" rel="prev">Using Valgrind</a>, Up: <a href="#Checking-memory-access" accesskey="u" rel="up">Checking memory access</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-the-Address-Sanitizer"><span>4.3.3 Using the Address Sanitizer<a class="copiable-link" href="#Using-the-Address-Sanitizer"> &para;</a></span></h4>

<p><code class="command">AddressSanitizer</code> (&lsquo;<abbr class="abbr">ASan</abbr>&rsquo;) is a tool with similar aims to the
memory checker in <code class="command">valgrind</code>.  It is available with suitable
builds<a class="footnote" id="DOCF131" href="#FOOT131"><sup>131</sup></a> of <code class="command">gcc</code> and
<code class="command">clang</code> on common Linux and macOS platforms.  See
<a class="uref" href="https://clang.llvm.org/docs/UsersManual.html#controlling-code-generation">https://clang.llvm.org/docs/UsersManual.html#controlling-code-generation</a>,
<a class="uref" href="https://clang.llvm.org/docs/AddressSanitizer.html">https://clang.llvm.org/docs/AddressSanitizer.html</a> and
<a class="uref" href="https://github.com/google/sanitizers">https://github.com/google/sanitizers</a>.
</p>
<p>More thorough checks of C++ code are done if the C++ library has been
&lsquo;annotated&rsquo;: at the time of writing this applied to <code class="code">std::vector</code>
in <code class="code">libc++</code> for use with <code class="command">clang</code> and gives rise to
&lsquo;<samp class="samp">container-overflow</samp>&rsquo;<a class="footnote" id="DOCF132" href="#FOOT132"><sup>132</sup></a>
reports.
</p>
<p>It requires code to have been compiled <em class="emph">and linked</em> with
<samp class="option">-fsanitize=address</samp> and compiling with <code class="code">-fno-omit-frame-pointer</code>
will give more legible reports.  It has a runtime penalty of 2&ndash;3x,
extended compilation times and uses substantially more memory, often
1&ndash;2GB, at run time.  On 64-bit platforms it reserves (but does not
allocate) 16&ndash;20TB of virtual memory: restrictive shell settings can
cause problems.  It can be helpful to increase the stack size, for
example to 40MB.
</p>
<p>By comparison with <code class="command">valgrind</code>, <abbr class="abbr">ASan</abbr> can
detect misuse of stack and global variables but not the use of
uninitialized memory.
</p>
<p>Recent versions return symbolic addresses for the location of the error
provided <code class="command">llvm-symbolizer</code><a class="footnote" id="DOCF133" href="#FOOT133"><sup>133</sup></a> is on the path: if it is available but not
on the path or has been renamed<a class="footnote" id="DOCF134" href="#FOOT134"><sup>134</sup></a>, one can use an environment variable, e.g.
</p>
<div class="example">
<pre class="example-preformatted">ASAN_SYMBOLIZER_PATH=/path/to/llvm-symbolizer
</pre></div>

<p>An alternative is to pipe the output through
<code class="command">asan_symbolize.py</code><a class="footnote" id="DOCF135" href="#FOOT135"><sup>135</sup></a> and perhaps
then (for compiled C++ code) <code class="command">c++filt</code>.  (On macOS, you may need
to run <code class="command">dsymutil</code> to get line-number reports.)
</p>
<p>The simplest way to make use of this is to build a version of R with
something like
</p>
<div class="example">
<pre class="example-preformatted">CC=&quot;gcc -std=gnu99 -fsanitize=address&quot;
CFLAGS=&quot;-fno-omit-frame-pointer -g -O2 -Wall -pedantic -mtune=native&quot;
</pre></div>

<p>which will ensure that the <code class="code">libasan</code> run-time library is compiled
into the R executable.  However this check can be enabled on a
per-package basis by using a <samp class="file">~/.R/Makevars</samp> file like
</p><div class="example">
<pre class="example-preformatted">CC = gcc -std=gnu99 -fsanitize=address -fno-omit-frame-pointer
CXX = g++ -fsanitize=address -fno-omit-frame-pointer
FC = gfortran -fsanitize=address
</pre></div>
<p>(Note that <code class="code">-fsanitize=address</code> has to be part of the compiler
specification to ensure it is used for linking.  These settings will not
be honoured by packages which ignore <samp class="file">~/.R/Makevars</samp>.)  It will
be necessary to build R with
</p>
<div class="example">
<pre class="example-preformatted">MAIN_LDFLAGS = -fsanitize=address
</pre></div>

<p>to link the runtime libraries into the R executable if it was not
specified as part of &lsquo;<samp class="samp">CC</samp>&rsquo; when R was built.  (For some builds
without <abbr class="abbr">OpenMP</abbr>, <samp class="option">-pthread</samp> is also required.)
</p>
<p>For options available <em class="emph">via</em> the environment variable
<code class="env">ASAN_OPTIONS</code> see
<a class="uref" href="https://github.com/google/sanitizers/wiki/AddressSanitizerFlags">https://github.com/google/sanitizers/wiki/AddressSanitizerFlags</a>.
With <code class="command">gcc</code> additional control is available <em class="emph">via</em> the
<samp class="option">--param</samp> flag: see its <code class="command">man</code> page.
</p>
<p>For more detailed information on an error, R can be run under a
debugger with a breakpoint set before the address sanitizer report is
produced: for <code class="command">gdb</code> or <code class="command">lldb</code> you could use
</p><div class="example">
<pre class="example-preformatted">break __asan_report_error
</pre></div>
<p>(See
<a class="uref" href="https://github.com/google/sanitizers/wiki/AddressSanitizerAndDebugger">https://github.com/google/sanitizers/wiki/AddressSanitizerAndDebugger</a>.)
</p>
<p>More recent versions<a class="footnote" id="DOCF136" href="#FOOT136"><sup>136</sup></a>  added the flag
<samp class="option">-fsanitize-address-use-after-scope</samp>: see
<a class="uref" href="https://github.com/google/sanitizers/wiki/AddressSanitizerUseAfterScope">https://github.com/google/sanitizers/wiki/AddressSanitizerUseAfterScope</a>.
</p>
<p>One of the checks done by <abbr class="abbr">ASan</abbr> is that <code class="code">malloc/free</code> and in C++
<code class="code">new/delete</code> and <code class="code">new[]/delete[]</code> are used consistently
(rather than say <code class="code">free</code> being used to deallocate memory allocated by
<code class="code">new[]</code>).  This matters on some systems but not all: unfortunately
on some of those where it does not matter, system libraries<a class="footnote" id="DOCF137" href="#FOOT137"><sup>137</sup></a> are not consistent.  The
check can be suppressed by including &lsquo;<samp class="samp">alloc_dealloc_mismatch=0</samp>&rsquo; in
<code class="env">ASAN_OPTIONS</code>.
</p>
<p><abbr class="abbr">ASan</abbr> also checks system calls and sometimes reports can refer to
problems in the system software and not the package nor R.  A couple
of reports have been of &lsquo;heap-use-after-free&rsquo; errors in the X11
libraries called from Tcl/Tk.
</p>

<ul class="mini-toc">
<li><a href="#Using-Leak-Sanitizer" accesskey="1">Using the Leak Sanitizer</a></li>
</ul>
<hr>
<div class="subsubsection-level-extent" id="Using-Leak-Sanitizer">
<div class="nav-panel">
<p>
Previous: <a href="#Using-Address-Sanitizer" accesskey="p" rel="prev">Using the Address Sanitizer</a>, Up: <a href="#Using-Address-Sanitizer" accesskey="u" rel="up">Using the Address Sanitizer</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsubsection" id="Using-the-Leak-Sanitizer"><span>4.3.3.1 Using the Leak Sanitizer<a class="copiable-link" href="#Using-the-Leak-Sanitizer"> &para;</a></span></h4>

<p>For <code class="code">x86_64</code> Linux there is a leak sanitizer, &lsquo;<abbr class="abbr">LSan</abbr>&rsquo;: see
<a class="uref" href="https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer">https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer</a>.
This is available on recent versions of <code class="code">gcc</code> and <code class="code">clang</code>, and
where available is compiled in as part of <abbr class="abbr">ASan</abbr>.
</p>
<p>One way to invoke this from an <abbr class="abbr">ASan</abbr>-enabled build is by the environment
variable
</p>
<div class="example">
<pre class="example-preformatted">ASAN_OPTIONS='detect_leaks=1'
</pre></div>
<p>However, this was made the default as from <code class="command">clang</code> 3.5 and
<code class="command">gcc</code> 5.1.0.
</p>
<p>When <abbr class="abbr">LSan</abbr> is enabled, leaks give the process a failure error status (by
default <code class="code">23</code>).  For an R package this means the R process,
and as the parser retains some memory to the end of the process, if R
itself was built against <abbr class="abbr">ASan</abbr> all runs will have a failure error status
(which may include running R as part of building R itself).
</p>
<p>To disable this, allocation-mismatch checking and some strict C++
checking use
</p>
<div class="example">
<pre class="example-preformatted">setenv ASAN_OPTIONS ‘alloc_dealloc_mismatch=0:detect_leaks=0:detect_odr_violation=0’
</pre></div>

<p><abbr class="abbr">LSan</abbr> also has a &lsquo;stand-alone&rsquo; mode where it is compiled in using
<samp class="option">-fsanitize=leak</samp> and avoids the run-time overhead of <abbr class="abbr">ASan</abbr>.
</p>
<hr>
</div>
</div>
<div class="subsection-level-extent" id="Using-Undefined-Behaviour-Sanitizer">
<div class="nav-panel">
<p>
Next: <a href="#Other-analyses-with-_0060clang_0027" accesskey="n" rel="next">Other analyses with &lsquo;clang&rsquo;</a>, Previous: <a href="#Using-Address-Sanitizer" accesskey="p" rel="prev">Using the Address Sanitizer</a>, Up: <a href="#Checking-memory-access" accesskey="u" rel="up">Checking memory access</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-the-Undefined-Behaviour-Sanitizer"><span>4.3.4 Using the Undefined Behaviour Sanitizer<a class="copiable-link" href="#Using-the-Undefined-Behaviour-Sanitizer"> &para;</a></span></h4>

<p>&lsquo;Undefined behaviour&rsquo; is where the language standard does not require
particular behaviour from the compiler.  Examples include division by
zero (where for doubles R requires the
<abbr class="acronym">ISO</abbr>/<abbr class="acronym">IEC</abbr>&nbsp;60559 behaviour but C/C++ do not), use
of zero-length arrays, shifts too far for signed types (e.g. <code class="code">int
x, y; y = x &lt;&lt; 31;</code>), out-of-range coercion, invalid C++ casts and
mis-alignment.  Not uncommon examples of out-of-range coercion in R
packages are attempts to coerce a <code class="code">NaN</code> or infinity to type
<code class="code">int</code> or <code class="code">NA_INTEGER</code> to an unsigned type such as
<code class="code">size_t</code>.  Also common is <code class="code">y[x - 1]</code> forgetting that <code class="code">x</code>
might be <code class="code">NA_INTEGER</code>.
</p>
<p>&lsquo;UBSanitizer&rsquo; is a tool for C/C++ source code selected by
<samp class="option">-fsanitize=undefined</samp> in suitable builds<a class="footnote" id="DOCF138" href="#FOOT138"><sup>138</sup></a> of <code class="command">clang</code> and GCC.  Its (main) runtime library is
linked into each package&rsquo;s DLL, so it is less often needed to be
included in <code class="env">MAIN_LDFLAGS</code>.  Platforms supported by <code class="command">clang</code>
are listed at
<a class="uref" href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#supported-platforms">https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#supported-platforms</a>:
<abbr class="acronym">CRAN</abbr> uses it for C/C++ with both GCC and <code class="command">clang</code> on
&lsquo;<samp class="samp">x86_64</samp>&rsquo; Linux: the two toolchains often highlight different
things with more reports from <code class="command">clang</code> than GCC.
</p>
<p>This sanitizer may be combined with the Address Sanitizer by
<samp class="option">-fsanitize=undefined,address</samp> (where both are supported, and we
have seen library conflicts for <code class="command">clang</code> 17 and later).
</p>
<p>Finer control of what is checked can be achieved by other options.
</p>
<p>For <code class="command">clang</code> see
<a class="uref" href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#ubsan-checks">https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#ubsan-checks</a>.
The current set is (on a single line):
</p><div class="example">
<pre class="example-preformatted">-fsanitize=alignment,bool,bounds,builtin,enum,float-cast-overflow,
float-divide-by-zero,function,implicit-unsigned-integer-truncation,
implicit-signed-integer-truncation,implicit-integer-sign-change,
integer-divide-by-zero,nonnull-attribute,null,nullability-arg,
nullability-assign,nullability-return,object-size,
pointer-overflow,return,returns-nonnull-attribute,shift,
signed-integer-overflow,unreachable,unsigned-integer-overflow,
unsigned-shift-base,vla-bound,vptr
</pre></div>

<p>(plus the more specific versions <code class="code">array-bounsds</code>,
<code class="code">local-bounds</code>, <code class="code">shift-base</code> and <code class="code">shift-exponent</code>), or
use something like
</p>
<div class="example">
<pre class="example-preformatted">-fsanitize=undefined -fno-sanitize=float-divide-by-zero
</pre></div>

<p>where in recent versions <code class="code">-fno-sanitize=float-divide-by-zero</code> is the
default.
</p>
<p>Options <code class="code">return</code> and <code class="code">vptr</code> apply only to C++: to
use <code class="code">vptr</code> its run-time library needs to be linked into the main
R executable by building the latter with something like
</p><div class="example">
<pre class="example-preformatted">MAIN_LD=&quot;clang++ -fsanitize=undefined&quot;
</pre></div>
<p>Option <code class="code">float-divide-by-zero</code> is undesirable for use with R
which allow such divisions as part of <abbr class="acronym">IEC</abbr>&nbsp;60559
arithmetic, and in versions of <code class="command">clang</code> since June 2019 it is no
longer part of <samp class="option">-fsanitize=undefined</samp>.
</p>
<p>There are also groups of options <code class="code">implicit-integer-truncation</code>,
<code class="code">mplicit-integer-arithmetic-value-change</code>,
<code class="code">implicit-conversion</code>, <code class="code">integer</code> and <code class="code">nullability</code>.
</p>
<p>For GCC see
<a class="uref" href="https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html">https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html</a>
(or the manual for your version of GCC, installed or <em class="emph">via</em>
<a class="uref" href="https://gcc.gnu.org/onlinedocs/">https://gcc.gnu.org/onlinedocs/</a>: look for &lsquo;Program
Instrumentation Options&rsquo;) for the options supported by GCC: versions 13.x
supported
</p><div class="example">
<pre class="example-preformatted">-fsanitize=alignment,bool,bounds,builtin,enum,integer-divide-by-zero,
nonnull-attribute,null,object-size,pointer-overflow,return,
returns-nonnull-attribute,shift,signed-integer-overflow,
unreachable,vla-bound,vptr
</pre></div>
<p>plus the more specific versions <code class="code">shift-base</code> and
<code class="code">shift-exponent</code> and non-default options
</p><div class="example">
<pre class="example-preformatted">bounds-strict,float-cast-overflow,float-divide-by-zero
</pre></div>
<p>where <code class="code">float-divide-by-zero</code> is not desirable for R uses and
<code class="code">bounds-strict</code> is an extension of <code class="code">bounds</code>.
</p>
<p>Other useful flags include
</p><div class="example">
<pre class="example-preformatted">-no-fsanitize-recover
</pre></div>

<p>which causes the first report to be fatal (it always is for the
<code class="code">unreachable</code> and <code class="code">return</code> suboptions).  For more detailed
information on where the runtime error occurs, using 
</p>
<div class="example">
<pre class="example-preformatted">setenv UBSAN_OPTIONS ‘print_stacktrace=1’ 
</pre></div>
<p>will include a traceback in the report.  Beyond that, R can
be run under a debugger with a breakpoint set before the sanitizer
report is produced: for <code class="command">gdb</code> or <code class="command">lldb</code> you could use
</p><div class="example">
<pre class="example-preformatted">break __ubsan_handle_float_cast_overflow
break __ubsan_handle_float_cast_overflow_abort
</pre></div>
<p>or similar (there are handlers for each type of undefined behaviour).
</p>
<p>There are also the compiler flags <samp class="option">-fcatch-undefined-behavior</samp>
and <samp class="option">-ftrapv</samp>, said to be more reliable in <code class="command">clang</code> than
<code class="command">gcc</code>.
</p>
<p>For more details on the topic see
<a class="uref" href="https://blog.regehr.org/archives/213">https://blog.regehr.org/archives/213</a> and
<a class="uref" href="https://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html">https://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html</a>
(which has 3 parts).
</p>
<p>It may or may not be possible to build R itself with
<samp class="option">-fsanitize=undefined</samp>: problems have in the past been seen with
<abbr class="abbr">OpenMP</abbr>-using code with <code class="command">gcc</code> but there has been success
with <code class="command">clang</code> up to version 16..  However, problems have been
seen with <code class="command">clang</code> 17 and later, including missing entry points
and R builds hanging.  What has succeeded is to use <abbr class="abbr">UBSAN</abbr> just for
the package under test (and not in combination with <abbr class="abbr">ASAN</abbr>).  To do so,
check with an unaltered R, using a custom <samp class="file">Makevars</samp> file
something like
</p>
<div class="example">
<pre class="example-preformatted">CC = clang -fsanitize=undefined -fno-sanitize=float-divide-by-zero -fno-omit-frame-pointer
CXX = clang++ -fsanitize=undefined -fno-sanitize=float-divide-by-zero -fno-omit-frame-pointer -frtti

UBSAN_DIR = /path/to/LLVM18/lib/clang/18/lib/x86_64-unknown-linux-gnu
SAN_LIBS = $(UBSAN_DIR)/libclang_rt.ubsan_standalone.a $(UBSAN_DIR)/libclang_rt.ubsan_standalone_cxx.a
</pre></div>

<p>which links the <abbr class="abbr">UBSAN</abbr> libraries statically into the package-under-test&rsquo;s <abbr class="abbr">DSO</abbr>.
It is also possible to use the dynamic library <em class="emph">via</em>
</p>
<div class="example">
<pre class="example-preformatted">SAN_LIBS = -L$(UBSAN_DIR) -Wl,-rpath,$(UBSAN_DIR) -lclang_rt.ubsan_standalone
</pre></div>
<p>provided <code class="code">UBSAN_DIR</code> is added to the runtime library path (as shown
or using  <code class="env">LD_LIBRARY_PATH</code>). <strong class="strong">N.B.</strong>: The details, especially
the paths used, have changed several times recently.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Other-analyses-with-_0060clang_0027">
<div class="nav-panel">
<p>
Next: <a href="#Other-analyses-with-_0060gcc_0027" accesskey="n" rel="next">Other analyses with &lsquo;gcc&rsquo;</a>, Previous: <a href="#Using-Undefined-Behaviour-Sanitizer" accesskey="p" rel="prev">Using the Undefined Behaviour Sanitizer</a>, Up: <a href="#Checking-memory-access" accesskey="u" rel="up">Checking memory access</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Other-analyses-with-_0060clang_0027-1"><span>4.3.5 Other analyses with &lsquo;clang&rsquo;<a class="copiable-link" href="#Other-analyses-with-_0060clang_0027-1"> &para;</a></span></h4>

<p>Recent versions of <code class="command">clang</code> on &lsquo;<samp class="samp">x86_64</samp>&rsquo; Linux have
&lsquo;ThreadSanitizer&rsquo; (<a class="uref" href="https://github.com/google/sanitizers/wiki#threadsanitizer">https://github.com/google/sanitizers/wiki#threadsanitizer</a>),
a &lsquo;data race detector for C/C++ programs&rsquo;, and &lsquo;MemorySanitizer&rsquo;
(<a class="uref" href="https://clang.llvm.org/docs/MemorySanitizer.html">https://clang.llvm.org/docs/MemorySanitizer.html</a>,
<a class="uref" href="https://github.com/google/sanitizers">https://github.com/google/sanitizers</a>)
for the detection of uninitialized memory.  Both are based on and
provide similar functionality to tools in <code class="command">valgrind</code>.
</p>
<p><code class="command">clang</code> has a &lsquo;Static Analyzer&rsquo; which can be run on the source
files during compilation: see <a class="uref" href="https://clang-analyzer.llvm.org/">https://clang-analyzer.llvm.org/</a>.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Other-analyses-with-_0060gcc_0027">
<div class="nav-panel">
<p>
Next: <a href="#Using-_0060Dr_002e-Memory_0027" accesskey="n" rel="next">Using &lsquo;Dr. Memory&rsquo;</a>, Previous: <a href="#Other-analyses-with-_0060clang_0027" accesskey="p" rel="prev">Other analyses with &lsquo;clang&rsquo;</a>, Up: <a href="#Checking-memory-access" accesskey="u" rel="up">Checking memory access</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Other-analyses-with-_0060gcc_0027-1"><span>4.3.6 Other analyses with &lsquo;gcc&rsquo;<a class="copiable-link" href="#Other-analyses-with-_0060gcc_0027-1"> &para;</a></span></h4>

<p>GCC 10 introduced a new flag <samp class="option">-fanalyzer</samp> which does static
analysis during compilation, currently for C code.  It is regarded as
<em class="emph">experimental</em> and it may slow down computation considerably when
problems are found (and use many GB of resident memory).  There is some
overlap with problems detected by the Undefined Behaviour sanitizer, but
some issues are only reported by this tool and as it is a static
analysis, it does not rely on code paths being exercised.
</p>
<p>See
<a class="uref" href="https://gcc.gnu.org/onlinedocs/gcc-10.1.0/gcc/Static-Analyzer-Options.html">https://gcc.gnu.org/onlinedocs/gcc-10.1.0/gcc/Static-Analyzer-Options.html</a>
(or the documentation for your version of <code class="command">gcc</code> if later) and
<a class="uref" href="https://developers.redhat.com/blog/2020/03/26/static-analysis-in-gcc-10">https://developers.redhat.com/blog/2020/03/26/static-analysis-in-gcc-10</a>
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Using-_0060Dr_002e-Memory_0027">
<div class="nav-panel">
<p>
Next: <a href="#Fortran-array-bounds-checking" accesskey="n" rel="next">Fortran array bounds checking</a>, Previous: <a href="#Other-analyses-with-_0060gcc_0027" accesskey="p" rel="prev">Other analyses with &lsquo;gcc&rsquo;</a>, Up: <a href="#Checking-memory-access" accesskey="u" rel="up">Checking memory access</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-_0060Dr_002e-Memory_0027-1"><span>4.3.7 Using &lsquo;Dr. Memory&rsquo;<a class="copiable-link" href="#Using-_0060Dr_002e-Memory_0027-1"> &para;</a></span></h4>

<p>&lsquo;Dr. Memory&rsquo; from <a class="uref" href="https://drmemory.org/">https://drmemory.org/</a> is a memory checker for
(currently) Windows, Linux and macOS with similar aims to
<code class="command">valgrind</code>.  It works with unmodified executables<a class="footnote" id="DOCF139" href="#FOOT139"><sup>139</sup></a>
and detects memory access errors, uninitialized reads and memory leaks.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Fortran-array-bounds-checking">
<div class="nav-panel">
<p>
Previous: <a href="#Using-_0060Dr_002e-Memory_0027" accesskey="p" rel="prev">Using &lsquo;Dr. Memory&rsquo;</a>, Up: <a href="#Checking-memory-access" accesskey="u" rel="up">Checking memory access</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Fortran-array-bounds-checking-1"><span>4.3.8 Fortran array bounds checking<a class="copiable-link" href="#Fortran-array-bounds-checking-1"> &para;</a></span></h4>

<p>Most of the Fortran compilers used with R allow code to be compiled
with checking of array bounds: for example <code class="command">gfortran</code> has option
<samp class="option">-fbounds-check</samp>.  This will give an error when the upper or
lower bound is exceeded, e.g.
</p><div class="example">
<pre class="example-preformatted">At line 97 of file .../src/appl/dqrdc2.f
Fortran runtime error: Index ‘1’ of dimension 1 of array ‘x’ above upper bound of 0
</pre></div>

<p>One does need to be aware that lazy programmers often specify Fortran
dimensions as <code class="code">1</code> rather than <code class="code">*</code> or a real bound and these
will be reported (as may <code class="code">*</code> dimensions)
</p>
<p>It is easy to arrange to use this check on just the code in your
package: add to <samp class="file">~/.R/Makevars</samp> something like (for
<code class="command">gfortran</code>)
</p><div class="example">
<pre class="example-preformatted">FFLAGS = -g -O2 -mtune=native -fbounds-check
</pre></div>

<p>when you run <code class="command">R CMD check</code>.
</p>
<p>This may report errors with the way that Fortran character variables are
passed, particularly when Fortran subroutines are called from C code and
character lengths are not passed (see <a class="pxref" href="#Fortran-character-strings">Fortran character strings</a>).
</p>

<hr>
</div>
</div>
<div class="section-level-extent" id="Debugging-compiled-code">
<div class="nav-panel">
<p>
Next: <a href="#Using-Link_002dtime-Optimization" accesskey="n" rel="next">Using Link-time Optimization</a>, Previous: <a href="#Checking-memory-access" accesskey="p" rel="prev">Checking memory access</a>, Up: <a href="#Debugging" accesskey="u" rel="up">Debugging</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Debugging-compiled-code-1"><span>4.4 Debugging compiled code<a class="copiable-link" href="#Debugging-compiled-code-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Debugging"></a>


<p>Sooner or later programmers will be faced with the need to debug
compiled code loaded into R.  This section is geared to platforms
using <code class="command">gdb</code> with code compiled by <code class="code">gcc</code>, but similar things
are possible with other debuggers such as <code class="command">lldb</code>
(<a class="uref" href="https://lldb.llvm.org/">https://lldb.llvm.org/</a>, used on macOS) and Sun&rsquo;s <code class="command">dbx</code>:
some debuggers have graphical front-ends available.
</p>
<p>Consider first &lsquo;crashes&rsquo;, that is when R terminated unexpectedly with
an illegal memory access (a &lsquo;segfault&rsquo; or &lsquo;bus error&rsquo;), illegal
instruction or similar.  Unix-alike versions of R use a signal
handler which aims to give some basic information.  For example
</p>
<div class="example">
<pre class="example-preformatted"> *** caught segfault ***
address 0x20000028, cause ‘memory not mapped’

Traceback:
 1: .identC(class1[[1]], class2)
 2: possibleExtends(class(sloti), classi, ClassDef2 = getClassDef(classi,
where = where))
 3: validObject(t(cu))
 4: stopifnot(validObject(cu &lt;- as(tu, &quot;dtCMatrix&quot;)), validObject(t(cu)),
validObject(t(tu)))

Possible actions:
1: abort (with core dump)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace
Selection: 3
</pre></div>

<p>Since the R process may be damaged, the only really safe options are
the first or third.  (Note that a core dump is only produced where
enabled: a common default in a shell is to limit its size to 0, thereby
disabling it.)
</p>
<p>A fairly common cause of such crashes is a package which uses <code class="code">.C</code>
or <code class="code">.Fortran</code> and writes beyond (at either end) one of the
arguments it is passed.  There is a good way to detect this: using
<code class="code">options(CBoundsCheck = TRUE)</code> (which can be selected <em class="emph">via</em>
the environment variable <code class="env">R_C_BOUNDS_CHECK=yes)</code> changes the way
<code class="code">.C</code> and <code class="code">.Fortran</code> work to check if the compiled code writes
in the 64 bytes at either end of an argument.
</p>
<p>Another cause of a &lsquo;crash&rsquo; is to overrun the C stack.  R tries to
track that in its own code, but it may happen in third-party compiled
code.  For modern POSIX-compliant OSes R can safely catch that and
return to the top-level prompt, so one gets something like
</p>
<div class="example">
<pre class="example-preformatted">&gt; .C(&quot;aaa&quot;)
Error: segfault from C stack overflow
&gt;
</pre></div>

<p>However, C stack overflows are fatal under Windows and normally defeat
attempts at debugging on that platform.  Further, the size of the stack
is set when R is compiled on Windows, whereas on POSIX OSes it can be
set in the shell from which R is launched.
</p>
<p>If you have a crash which gives a core dump you can use something like
</p>
<div class="example">
<pre class="example-preformatted">gdb /path/to/R/bin/exec/R core.12345
</pre></div>

<p>to examine the core dump.  If core dumps are disabled or to catch errors
that do not generate a dump one can run R directly under a debugger
by for example
</p>
<div class="example">
<pre class="example-preformatted">$ R -d gdb --vanilla
...
gdb&gt; run
</pre></div>

<p>at which point R will run normally, and hopefully the debugger will
catch the error and return to its prompt.  This can also be used to
catch infinite loops or interrupt very long-running code.  For a simple
example
</p>
<div class="example">
<pre class="example-preformatted">&gt; for(i in 1:1e7) x &lt;- rnorm(100)
[hit Ctrl-C]
Program received signal SIGINT, Interrupt.
0x00397682 in _int_free () from /lib/tls/libc.so.6
(gdb) where
#0  0x00397682 in _int_free () from /lib/tls/libc.so.6
#1  0x00397eba in free () from /lib/tls/libc.so.6
#2  0xb7cf2551 in R_gc_internal (size_needed=313)
    at /users/ripley/R/svn/R-devel/src/main/memory.c:743
#3  0xb7cf3617 in Rf_allocVector (type=13, length=626)
    at /users/ripley/R/svn/R-devel/src/main/memory.c:1906
#4  0xb7c3f6d3 in PutRNGstate ()
    at /users/ripley/R/svn/R-devel/src/main/RNG.c:351
#5  0xb7d6c0a5 in do_random2 (call=0x94bf7d4, op=0x92580e8, args=0x9698f98,
    rho=0x9698f28) at /users/ripley/R/svn/R-devel/src/main/random.c:183
...
</pre></div>

<p>In many cases it is possible to attach a debugger to a running process:
this is helpful if an alternative front-end is in use or to investigate
a task that seems to be taking far too long.  This is done by something
like
</p>
<div class="example">
<pre class="example-preformatted">gdb -p <var class="var">pid</var>
</pre></div>

<p>where <code class="code"><var class="var">pid</var></code> is the id of the R executable or front-end
process and can be found from within a running R process by calling
<code class="code">Sys.getpid()</code> or from a process monitor.  This stops the process
so its state can be examined: use <code class="code">continue</code> to resume execution.
</p>

<p>Some &ldquo;tricks&rdquo; worth knowing follow:
</p>

<ul class="mini-toc">
<li><a href="#Finding-entry-points" accesskey="1">Finding entry points in dynamically loaded code</a></li>
<li><a href="#Inspecting-R-objects" accesskey="2">Inspecting R objects when debugging</a></li>
<li><a href="#Debugging-on-macOS" accesskey="3">Debugging on macOS</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Finding-entry-points">
<div class="nav-panel">
<p>
Next: <a href="#Inspecting-R-objects" accesskey="n" rel="next">Inspecting R objects when debugging</a>, Previous: <a href="#Debugging-compiled-code" accesskey="p" rel="prev">Debugging compiled code</a>, Up: <a href="#Debugging-compiled-code" accesskey="u" rel="up">Debugging compiled code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Finding-entry-points-in-dynamically-loaded-code"><span>4.4.1 Finding entry points in dynamically loaded code<a class="copiable-link" href="#Finding-entry-points-in-dynamically-loaded-code"> &para;</a></span></h4>

<p>Under most compilation environments, compiled code dynamically loaded
into R cannot have breakpoints set within it until it is loaded.  To
use a symbolic debugger on such dynamically loaded code under
Unix-alikes use
</p>
<ul class="itemize mark-bullet">
<li>Call the debugger on the R executable, for example by <kbd class="kbd">R -d gdb</kbd>.
</li><li>Start R.
</li><li>At the R prompt, use <code class="code">dyn.load</code> or <code class="code">library</code> to load your
shared object.
</li><li>Send an interrupt signal.  This will put you back to the debugger
prompt.
</li><li>Set the breakpoints in your code.
</li><li>Continue execution of R by typing <kbd class="kbd">signal 0<kbd class="key">RET</kbd></kbd>.
</li></ul>

<p>Under Windows signals may not be able to be used, and if so the procedure is
more complicated.  See the rw-FAQ.
</p>

<hr>
</div>
<div class="subsection-level-extent" id="Inspecting-R-objects">
<div class="nav-panel">
<p>
Next: <a href="#Debugging-on-macOS" accesskey="n" rel="next">Debugging on macOS</a>, Previous: <a href="#Finding-entry-points" accesskey="p" rel="prev">Finding entry points in dynamically loaded code</a>, Up: <a href="#Debugging-compiled-code" accesskey="u" rel="up">Debugging compiled code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Inspecting-R-objects-when-debugging"><span>4.4.2 Inspecting R objects when debugging<a class="copiable-link" href="#Inspecting-R-objects-when-debugging"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Inspecting-R-objects-when-debugging"></a>

<p>The key to inspecting R objects from compiled code is the function
<code class="code">PrintValue(SEXP <var class="var">s</var>)</code> which uses the normal R printing
mechanisms to print the R object pointed to by <var class="var">s</var>, or the safer
version <code class="code">R_PV(SEXP <var class="var">s</var>)</code> which will only print &lsquo;objects&rsquo;.
<a class="index-entry-id" id="index-PrintValue"></a>
<a class="index-entry-id" id="index-R_005fPV"></a>
</p>
<p>One way to make use of <code class="code">PrintValue</code> is to insert suitable calls
into the code to be debugged.
</p>
<p>Another way is to call <code class="code">R_PV</code> from the symbolic debugger.
(<code class="code">PrintValue</code> is hidden as <code class="code">Rf_PrintValue</code>.)  For example,
from <code class="code">gdb</code> we can use
</p>
<div class="example">
<pre class="example-preformatted">(gdb) p R_PV(ab)
</pre></div>

<p>using the object <code class="code">ab</code> from the convolution example, if we have
placed a suitable breakpoint in the convolution C code.
</p>
<p>To examine an arbitrary R object we need to work a little harder.
For example, let
</p>
<div class="example">
<pre class="example-preformatted">R&gt; DF &lt;- data.frame(a = 1:3, b = 4:6)
</pre></div>

<p>By setting a breakpoint at <code class="code">do_get</code> and typing <kbd class="kbd">get(&quot;DF&quot;)</kbd> at
the R prompt, one can find out the address in memory of <code class="code">DF</code>, for
example
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">Value returned is $1 = (SEXPREC *) 0x40583e1c
(gdb) p *$1
$2 = {
  sxpinfo = {type = 19, obj = 1, named = 1, gp = 0,
    mark = 0, debug = 0, trace = 0, = 0},
  attrib = 0x40583e80,
  u = {
    vecsxp = {
      length = 2,
      type = {c = 0x40634700 &quot;0&gt;X@D&gt;X@0&gt;X@&quot;, i = 0x40634700,
        f = 0x40634700, z = 0x40634700, s = 0x40634700},
      truelength = 1075851272,
    },
    primsxp = {offset = 2},
    symsxp = {pname = 0x2, value = 0x40634700, internal = 0x40203008},
    listsxp = {carval = 0x2, cdrval = 0x40634700, tagval = 0x40203008},
    envsxp = {frame = 0x2, enclos = 0x40634700},
    closxp = {formals = 0x2, body = 0x40634700, env = 0x40203008},
    promsxp = {value = 0x2, expr = 0x40634700, env = 0x40203008}
  }
}
</pre></div></div>

<p>(Debugger output reformatted for better legibility).
</p>
<p>Using <code class="code">R_PV()</code> one can &ldquo;inspect&rdquo; the values of the various
elements of the <code class="code">SEXP</code>, for example,
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">(gdb) p R_PV($1-&gt;attrib)
$names
[1] &quot;a&quot; &quot;b&quot;

$row.names
[1] &quot;1&quot; &quot;2&quot; &quot;3&quot;

$class
[1] &quot;data.frame&quot;

$3 = void
</pre></div></div>

<p>To find out where exactly the corresponding information is stored, one
needs to go &ldquo;deeper&rdquo;:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">(gdb) set $a = $1-&gt;attrib
(gdb) p $a-&gt;u.listsxp.tagval-&gt;u.symsxp.pname-&gt;u.vecsxp.type.c
$4 = 0x405d40e8 &quot;names&quot;
(gdb) p $a-&gt;u.listsxp.carval-&gt;u.vecsxp.type.s[1]-&gt;u.vecsxp.type.c
$5 = 0x40634378 &quot;b&quot;
(gdb) p $1-&gt;u.vecsxp.type.s[0]-&gt;u.vecsxp.type.i[0]
$6 = 1
(gdb) p $1-&gt;u.vecsxp.type.s[1]-&gt;u.vecsxp.type.i[1]
$7 = 5
</pre></div></div>

<p>Another alternative is the <code class="code">R_inspect</code> function which shows the
low-level structure of the objects recursively (addresses differ from
the above as this example is created on another machine):
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">(gdb) p R_inspect($1)
@100954d18 19 VECSXP g0c2 [OBJ,NAM(2),ATT] (len=2, tl=0)
  @100954d50 13 INTSXP g0c2 [NAM(2)] (len=3, tl=0) 1,2,3
  @100954d88 13 INTSXP g0c2 [NAM(2)] (len=3, tl=0) 4,5,6
ATTRIB:
  @102a70140 02 LISTSXP g0c0 []
    TAG: @10083c478 01 SYMSXP g0c0 [MARK,NAM(2),gp=0x4000] &quot;names&quot;
    @100954dc0 16 STRSXP g0c2 [NAM(2)] (len=2, tl=0)
      @10099df28 09 CHARSXP g0c1 [MARK,gp=0x21] &quot;a&quot;
      @10095e518 09 CHARSXP g0c1 [MARK,gp=0x21] &quot;b&quot;
    TAG: @100859e60 01 SYMSXP g0c0 [MARK,NAM(2),gp=0x4000] &quot;row.names&quot;
    @102a6f868 13 INTSXP g0c1 [NAM(2)] (len=2, tl=1) -2147483648,-3
    TAG: @10083c948 01 SYMSXP g0c0 [MARK,gp=0x4000] &quot;class&quot;
    @102a6f838 16 STRSXP g0c1 [NAM(2)] (len=1, tl=1)
      @1008c6d48 09 CHARSXP g0c2 [MARK,gp=0x21,ATT] &quot;data.frame&quot;
</pre></div></div>

<p>In general the representation of each object follows the format:
</p>
<div class="example smallexample">
<pre class="example-preformatted">@&lt;address&gt; &lt;type-nr&gt; &lt;type-name&gt; &lt;gc-info&gt; [&lt;flags&gt;] ...
</pre></div>

<p>For a more fine-grained control over the depth of the recursion
and the output of vectors <code class="code">R_inspect3</code> takes additional two character()
parameters: maximum depth and the maximal number of elements that will
be printed for scalar vectors. The defaults in <code class="code">R_inspect</code> are
currently -1 (no limit) and 5 respectively.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Debugging-on-macOS">
<div class="nav-panel">
<p>
Previous: <a href="#Inspecting-R-objects" accesskey="p" rel="prev">Inspecting R objects when debugging</a>, Up: <a href="#Debugging-compiled-code" accesskey="u" rel="up">Debugging compiled code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Debugging-on-macOS-1"><span>4.4.3 Debugging on macOS<a class="copiable-link" href="#Debugging-on-macOS-1"> &para;</a></span></h4>

<p>To debug code in a package it is easiest to unpack it in a directory and
install it with
</p>
<div class="example">
<pre class="example-preformatted">R CMD INSTALL --dsym <var class="var">pkgname</var>
</pre></div>

<p>as macOS does not store debugging symbols in the <samp class="file">.so</samp> file.  (It
is not necessary to have R built with debugging symbols, although
compiling the package should be done including <samp class="option">-g</samp> in
<code class="code">CFLAGS</code> / <code class="code">CXXFLAGS</code> / <code class="code">FFLAGS</code> / <code class="code">FCFLAGS</code> as
appropriate.)
</p>
<p>Security measures may prevent running a <abbr class="acronym">CRAN</abbr> binary
distribution of R under <code class="command">lldb</code> or attaching this as a
debugger
(<a class="uref" href="https://cran.r-project.org/bin/macosx/RMacOSX-FAQ.html#I-cannot-attach-debugger-to-R">https://cran.r-project.org/bin/macosx/RMacOSX-FAQ.html#I-cannot-attach-debugger-to-R</a>),
although both were possible on High Sierra and are again from R
4.2.0.  This can also affect locally compiled builds, where attaching to
an interactive R session under Big Sur or Monterey worked in 2022
after giving administrator permission <em class="emph">via</em> a popup-up.  (To debug
in what Apple deems a non-interactive session, e.g. logged in remotely,
see <code class="command">man DevToolsSecurity</code>.)
</p>
<p>Debugging a local build of R on macOS can raise additional hurdles as
environment variables such as <code class="env">DYLD_FALLBACK_LIBRARY_PATH</code> are not
usually passed through<a class="footnote" id="DOCF140" href="#FOOT140"><sup>140</sup></a> the <code class="command">lldb</code> process, resulting in messages
like
</p><div class="example">
<pre class="example-preformatted">R -d lldb
...
(lldb) run
Process 16828 launched: ‘/path/to/bin/exec/R’ (x86_64)
dyld: Library not loaded: libR.dylib
  Referenced from: /path/to/bin/exec/R
</pre></div>

<p>A quick workaround is to symlink the dylibs under <samp class="file">R_HOME/lib</samp> to
somewhere where they will be found such as the current working
directory.  It would be possible to do as the distribution
does<a class="footnote" id="DOCF141" href="#FOOT141"><sup>141</sup></a>  and
use <code class="command">install_name_tool</code>, but that would have to be done for all
the dylibs including those in packages.
</p>
<p>It may be simplest to attach the debugger to a running process (see
above).  Specifically, run R and when it is at the prompt just before
a command that is to be debugged, at a terminal 
</p>
<div class="example">
<pre class="example-preformatted">ps -ef | grep exec/R
# identify the PID <var class="var">pid</var> for the next command: it is the second item
lldb -p <var class="var">pid</var>
(lldb) continue
</pre></div>

<p>and then return to the R console.
</p>
<p>For non-interactive use, one may need <code class="command">lldb --batch</code>.
</p>

<hr>
</div>
</div>
<div class="section-level-extent" id="Using-Link_002dtime-Optimization">
<div class="nav-panel">
<p>
Previous: <a href="#Debugging-compiled-code" accesskey="p" rel="prev">Debugging compiled code</a>, Up: <a href="#Debugging" accesskey="u" rel="up">Debugging</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Using-Link_002dtime-Optimization-1"><span>4.5 Using Link-time Optimization<a class="copiable-link" href="#Using-Link_002dtime-Optimization-1"> &para;</a></span></h3>

<p>Where supported, <em class="emph">link time optimization</em> provides a comprehensive
way to check the consistency of calls between Fortran files or between C
and Fortran.  Use this <em class="emph">via</em> <code class="command">R CMD INSTALL --use-LTO</code> (but
that does not apply if there is a <samp class="file">src/Makefile</samp> file or a Windows
analogue).
</p>
<p>To set up support on a Unix-alike, see
<a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Link_002dTime-Optimization">Link-Time Optimization</a> in <cite class="cite">R Installation and Administration</cite>.
On Linux using GCC without building R with <abbr class="abbr">LTO</abbr> support,
it should suffice to set
</p><div class="example">
<pre class="example-preformatted">LTO_OPT = -flto
LTO_FC_OPT = -flto
AR = gcc-ar
NM = gcc-nm
</pre></div>
<p>in a personal (or site) <samp class="file">Makevars</samp> file:
See <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Customizing-package-compilation">Customizing package compilation</a> in <cite class="cite">R Installation and Administration</cite>,
</p>
<p>For Windows, first edit file <samp class="file">etc/${R_ARCH}/Makeconf</samp> to give
<code class="code">LTO_OPT</code> the value <code class="code">-flto</code> or do so in a personal/site
<samp class="file">Makevars</samp> file; see also file
<samp class="file">src/gnuwin32/README.compilation</samp> in the sources.
</p>
<p>For example:
</p><div class="example">
<pre class="example-preformatted">boot.f:61: warning: type of ‘ddot’ does not match original declaration [-Wlto-type-mismatch]
        y(j,i)=ddot(p,x(j,1),n,b(1,j,i),1)
crq.f:1023: note: return value type mismatch
</pre></div>
<p>where the package author forgot to declare
</p><div class="example">
<pre class="example-preformatted">      double precision ddot
      external ddot
</pre></div>
<p>in <samp class="file">boot.f</samp>.  That package had its own copy of <code class="code">ddot</code>: to
detect misuse of the one in R&rsquo;s BLAS library would have needed R
configured with <samp class="option">--enable-lto=check</samp>.
</p>
<p>Further examples:
</p>
<div class="example">
<pre class="example-preformatted">rkpk2.f:77:5: warning: type of ‘dstup’ does not match original declaration [-Wlto-type-mismatch]
      *info, wk)
rkpk1.f:2565:5: note: type mismatch in parameter 14
       subroutine dstup (s, lds, nobs, nnull, qraux, jpvt, y, q, ldqr,
rkpk1.f:2565:5: note: ‘dstup’ was previously declared here
</pre></div>
<p>where the fourteenth argument <code class="code">dum</code> was missing in the call.
</p>
<div class="example">
<pre class="example-preformatted">reg.f:78:33: warning: type of ‘dqrdc’ does not match original declaration [-Wlto-type-mismatch]
       call dqrdc (sr, nobs, nobs, nnull, wk, dum, dum, 0)
dstup.f:20: note: ‘dqrdc’ was previously declared here
       call dqrdc (s, lds, nobs, nnull, qraux, jpvt, work, 1)
</pre></div>
<p><code class="code">dqrdc</code> is a LINPACK routine from R, <code class="code">jpvt</code> is an integer
array and <code class="code">work</code> is a double precision one so <code class="code">dum</code> cannot
match both.  (If <samp class="option">--enable-lto=check</samp> had been used the
comparison would have been with the definition in R.)
</p>
<p>For Fortran files all in the package, most inconsistencies can be
detected by concatenating the Fortran files and compiling the result,
sometimes with clearer diagnostics than provided by <abbr class="abbr">LTO</abbr>.  For our last
two examples this gives
</p>
<div class="example">
<pre class="example-preformatted">all.f:2966:72:

      *info, work1)
                                                                        1
Warning: Missing actual argument for argument ‘dum’ at (1)
</pre></div>
<p>and
</p><div class="example">
<pre class="example-preformatted">all.f:1663:72:

      *ipvtwk), wk(ikwk), wk(iwork1), wk(iwork2), info)
                                                                        1
Warning: Type mismatch in argument ‘jpvt’ at (1); passed REAL(8) to INTEGER(4)
</pre></div>

<p>On a Unix-alike for a package with a <samp class="file">src/Makefile</samp> file, <abbr class="abbr">LTO</abbr> can
be enabled by including suitable flags in that file, for example
</p><div class="example">
<pre class="example-preformatted">LTO = $(LTO_OPT)
LTO_FC = $(LTO_FC_OPT)
</pre></div>
<p>and ensuring these are used for compilation, for example as part of
<code class="code">CFLAGS</code>, <code class="code">CXXFLAGS</code> or <code class="code">FCFLAGS</code>.  If <code class="command">R CMD
SHLIB</code> is used for compilation, add <samp class="option">--use-LTO</samp> to its call.
</p>
<p>On Windows for a package with a <samp class="file">src/Makefile.ucrt</samp> or
<samp class="file">src/Makefile.win</samp> file which includes
&lsquo;<samp class="samp">&quot;${R_HOME}/etc${R_ARCH}/Makeconf&quot;</samp>&rsquo;, include
</p><div class="example">
<pre class="example-preformatted">LTO = $(LTO_OPT)
</pre></div>
<p>or to always use <abbr class="abbr">LTO</abbr> however R was built,
</p><div class="example">
<pre class="example-preformatted">LTO = -flto
</pre></div>


<hr>
</div>
</div>
<div class="chapter-level-extent" id="System-and-foreign-language-interfaces">
<div class="nav-panel">
<p>
Next: <a href="#The-R-API" accesskey="n" rel="next">The R <abbr class="acronym">API</abbr>: entry points for C code</a>, Previous: <a href="#Debugging" accesskey="p" rel="prev">Debugging</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="chapter" id="System-and-foreign-language-interfaces-1"><span>5 System and foreign language interfaces<a class="copiable-link" href="#System-and-foreign-language-interfaces-1"> &para;</a></span></h2>


<ul class="mini-toc">
<li><a href="#Operating-system-access" accesskey="1">Operating system access</a></li>
<li><a href="#Interface-functions-_002eC-and-_002eFortran" accesskey="2">Interface functions <code class="code">.C</code> and <code class="code">.Fortran</code></a></li>
<li><a href="#dyn_002eload-and-dyn_002eunload" accesskey="3"><code class="code">dyn.load</code> and <code class="code">dyn.unload</code></a></li>
<li><a href="#Registering-native-routines" accesskey="4">Registering native routines</a></li>
<li><a href="#Creating-shared-objects" accesskey="5">Creating shared objects</a></li>
<li><a href="#Interfacing-C_002b_002b-code" accesskey="6">Interfacing C++ code</a></li>
<li><a href="#Fortran-I_002fO" accesskey="7">Fortran I/O</a></li>
<li><a href="#Linking-to-other-packages" accesskey="8">Linking to other packages</a></li>
<li><a href="#Handling-R-objects-in-C" accesskey="9">Handling R objects in C</a></li>
<li><a href="#Interface-functions-_002eCall-and-_002eExternal">Interface functions <code class="code">.Call</code> and <code class="code">.External</code></a></li>
<li><a href="#Evaluating-R-expressions-from-C">Evaluating R expressions from C</a></li>
<li><a href="#Parsing-R-code-from-C">Parsing R code from C</a></li>
<li><a href="#External-pointers-and-weak-references">External pointers and weak references</a></li>
<li><a href="#Vector-accessor-functions">Vector accessor functions</a></li>
<li><a href="#Character-encoding-issues">Character encoding issues</a></li>
</ul>
<hr>
<div class="section-level-extent" id="Operating-system-access">
<div class="nav-panel">
<p>
Next: <a href="#Interface-functions-_002eC-and-_002eFortran" accesskey="n" rel="next">Interface functions <code class="code">.C</code> and <code class="code">.Fortran</code></a>, Previous: <a href="#System-and-foreign-language-interfaces" accesskey="p" rel="prev">System and foreign language interfaces</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Operating-system-access-1"><span>5.1 Operating system access<a class="copiable-link" href="#Operating-system-access-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Operating-system-access"></a>

<p>Access to operating system functions is <em class="emph">via</em> the R functions
<code class="code">system</code> and <code class="code">system2</code>.
<a class="index-entry-id" id="index-system"></a>
<a class="index-entry-id" id="index-system2"></a>
The details will differ by platform (see the on-line help), and about
all that can safely be assumed is that the first argument will be a
string <code class="code">command</code> that will be passed for execution (not necessarily
by a shell) and the second argument to <code class="code">system</code> will be
<code class="code">internal</code> which if true will collect the output of the command
into an R character vector.
</p>
<p>On POSIX-compliant OSes these commands pass a command-line to a shell:
Windows is not POSIX-compliant and there is a separate function
<code class="code">shell</code> to do so.
</p>
<p>The function <code class="code">system.time</code>
<a class="index-entry-id" id="index-system_002etime"></a>
is available for timing.  Timing on child processes is only available on
Unix-alikes, and may not be reliable there.
</p>
<hr>
</div>
<div class="section-level-extent" id="Interface-functions-_002eC-and-_002eFortran">
<div class="nav-panel">
<p>
Next: <a href="#dyn_002eload-and-dyn_002eunload" accesskey="n" rel="next"><code class="code">dyn.load</code> and <code class="code">dyn.unload</code></a>, Previous: <a href="#Operating-system-access" accesskey="p" rel="prev">Operating system access</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Interface-functions-_002eC-and-_002eFortran-1"><span>5.2 Interface functions <code class="code">.C</code> and <code class="code">.Fortran</code><a class="copiable-link" href="#Interface-functions-_002eC-and-_002eFortran-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Interfaces-to-compiled-code"></a>

<a class="index-entry-id" id="index-_002eC"></a>
<a class="index-entry-id" id="index-_002eFortran"></a>

<p>These two functions provide an interface to compiled code that has been
linked into R, either at build time or <em class="emph">via</em> <code class="code">dyn.load</code>
(see <a class="pxref" href="#dyn_002eload-and-dyn_002eunload"><code class="code">dyn.load</code> and <code class="code">dyn.unload</code></a>).  They are primarily intended for
compiled C and Fortran code respectively, but the <code class="code">.C</code> function can
be used with other languages which can generate C interfaces, for
example C++ (see <a class="pxref" href="#Interfacing-C_002b_002b-code">Interfacing C++ code</a>).
</p>
<p>The first argument to each function is a character string specifying the
symbol name as known<a class="footnote" id="DOCF142" href="#FOOT142"><sup>142</sup></a> to C or
Fortran, that is the function or subroutine name.  (That the symbol is
loaded can be tested by, for example, <code class="code">is.loaded(&quot;cg&quot;)</code>.  Use the
name you pass to <code class="code">.C</code> or <code class="code">.Fortran</code> rather than the translated
symbol name.)
</p>
<p>There can be up to 65 further arguments giving R objects to be passed
to compiled code.  Normally these are copied before being passed in, and
copied again to an R list object when the compiled code returns.  If
the arguments are given names, these are used as names for the
components in the returned list object (but not passed to the compiled
code).
</p>
<p>The following table gives the mapping between the modes of R atomic
vectors and the types of arguments to a C function or Fortran
subroutine.
</p>
<blockquote class="quotation">
<table summary="" class="multitable">
<thead><tr><th>R storage mode</th><th>C type</th><th>Fortran type</th></tr></thead>
<tbody><tr><td><code class="code">logical</code></td><td><code class="code">int *</code></td><td><code class="code">INTEGER</code></td></tr>
<tr><td><code class="code">integer</code></td><td><code class="code">int *</code></td><td><code class="code">INTEGER</code></td></tr>
<tr><td><code class="code">double</code></td><td><code class="code">double *</code></td><td><code class="code">DOUBLE PRECISION</code></td></tr>
<tr><td><code class="code">complex</code></td><td><code class="code">Rcomplex *</code></td><td><code class="code">DOUBLE COMPLEX</code></td></tr>
<tr><td><code class="code">character</code></td><td><code class="code">char **</code></td><td><code class="code">CHARACTER(255)</code></td></tr>
<tr><td><code class="code">raw</code></td><td><code class="code">unsigned char *</code></td><td>none</td></tr>
</tbody>
</table>
</blockquote>

<p>On all R platforms <code class="code">int</code> and <code class="code">INTEGER</code> are 32-bit.  Code
ported from S-PLUS (which uses <code class="code">long *</code> for <code class="code">logical</code> and
<code class="code">integer</code>) will not work on all 64-bit platforms (although it may
appear to work on some, including &lsquo;<samp class="samp">x86_64</samp>&rsquo; Windows).  Note also
that if your compiled code is a mixture of C functions and Fortran
subprograms the argument types must match as given in the table above.
</p>
<p>C type <code class="code">Rcomplex</code> is a structure with <code class="code">double</code> members
<code class="code">r</code> and <code class="code">i</code> defined in the header file
<samp class="file">R_ext/Complex.h</samp>.<a class="footnote" id="DOCF143" href="#FOOT143"><sup>143</sup></a>  (On most platforms this is stored in a way compatible
with the C99 <code class="code">double complex</code> type: however, it may not be possible
to pass <code class="code">Rcomplex</code> to a C99 function expecting a <code class="code">double
complex</code> argument.  Nor need it be compatible with a C++ <code class="code">complex</code>
type.  Moreover, the compatibility can depend on the optimization level
set for the compiler.)
</p>
<p>Only a single character string of fixed length can be passed to or from
Fortran (the length is not passed), and the success of this is
compiler-dependent: its use was formally deprecated in 2019.  Other R
objects can be passed to <code class="code">.C</code>, but it is much better to use one of
the other interfaces.
</p>
<p>It is possible to pass numeric vectors of storage mode <code class="code">double</code> to
C as <code class="code">float *</code> or to Fortran as <code class="code">REAL</code> by setting the
attribute <code class="code">Csingle</code>, most conveniently by using the R functions
<code class="code">as.single</code>, <code class="code">single</code> or <code class="code">mode</code>.  This is intended only
to be used to aid interfacing existing C or Fortran code.
</p>
<p>Logical values are sent as <code class="code">0</code> (<code class="code">FALSE</code>), <code class="code">1</code>
(<code class="code">TRUE</code>) or <code class="code">INT_MIN = -2147483648</code> (<code class="code">NA</code>, but only if
<code class="code">NAOK</code> is true), and the compiled code should return one of these
three values.  (Non-zero values other than <code class="code">INT_MIN</code> are mapped to
<code class="code">TRUE</code>.)  Note that the use of <code class="code">int *</code> for Fortran logical is
not guaranteed to be portable (although people have gotten away with it
for many years): it is better to pass integers and convert to/from
Fortran logical in a Fortran wrapper.
</p>
<p>Unless formal argument <code class="code">NAOK</code> is true, all the other arguments are
checked for missing values <code class="code">NA</code> and for the <abbr class="acronym">IEEE</abbr> special
values <code class="code">NaN</code>, <code class="code">Inf</code> and <code class="code">-Inf</code>, and the presence of any
of these generates an error.  If it is true, these values are passed
unchecked.
</p>
<p>Argument <code class="code">PACKAGE</code> confines the search for the symbol name to a
specific shared object (or use <code class="code">&quot;base&quot;</code> for code compiled into
R).  Its use is highly desirable, as there is no way to avoid two
package writers using the same symbol name, and such name clashes are
normally sufficient to cause R to crash.  (If it is not present and
the call is from the body of a function defined in a package namespace,
the shared object loaded by the first (if any) <code class="code">useDynLib</code>
directive will be used.) 
</p>
<p>Note that the compiled code should not return anything except through
its arguments: C functions should be of type <code class="code">void</code> and Fortran
subprograms should be subroutines.
</p>
<p>To fix ideas, let us consider a very simple example which convolves two
finite sequences. (This is hard to do fast in interpreted R code, but
easy in C code.)  We could do this using <code class="code">.C</code> by
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">void convolve(double *a, int *na, double *b, int *nb, double *ab)
{
    int nab = *na + *nb - 1;

    for(int i = 0; i &lt; nab; i++)
        ab[i] = 0.0;
    for(int i = 0; i &lt; *na; i++)
        for(int j = 0; j &lt; *nb; j++)
            ab[i + j] += a[i] * b[j];
}
</pre></div></div>

<p>called from R by
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">conv &lt;- function(a, b)
    .C(&quot;convolve&quot;,
       as.double(a),
       as.integer(length(a)),
       as.double(b),
       as.integer(length(b)),
       ab = double(length(a) + length(b) - 1))$ab
</pre></div></div>

<p>Note that we take care to coerce all the arguments to the correct R
storage mode before calling <code class="code">.C</code>; mistakes in matching the types
can lead to wrong results or hard-to-catch errors.
</p>
<p>Special care is needed in handling <code class="code">character</code> vector arguments in
C (or C++).  On entry the contents of the elements are duplicated and
assigned to the elements of a <code class="code">char **</code> array, and on exit the
elements of the C array are copied to create new elements of a character
vector.  This means that the contents of the character strings of the
<code class="code">char **</code> array can be changed, including to <code class="code">\0</code> to shorten
the string, but the strings cannot be lengthened.  It is
possible<a class="footnote" id="DOCF144" href="#FOOT144"><sup>144</sup></a> to allocate a new string <em class="emph">via</em>
<code class="code">R_alloc</code> and replace an entry in the <code class="code">char **</code> array by the
new string.  However, when character vectors are used other than in a
read-only way, the <code class="code">.Call</code> interface is much to be preferred.
</p>
<p>Passing character strings to Fortran code needs even more care, is
deprecated and should be avoided where possible.  Only the first element
of the character vector is passed in, as a fixed-length (255) character
array.  Up to 255 characters are passed back to a length-one character
vector.  How well this works (or even if it works at all) depends on the
C and Fortran compilers on each platform (including on their options).
Often what is being passed to Fortran is one of a small set of possible
values (a factor in R terms) which could alternatively be passed as
an integer code: similarly Fortran code that wants to generate
diagnostic messages could pass an integer code to a C or R wrapper
which would convert it to a character string.
</p>
<p>It is possible to pass some R objects other than atomic vectors <em class="emph">via</em>
<code class="code">.C</code>, but this is only supported for historical compatibility: use
the <code class="code">.Call</code> or <code class="code">.External</code> interfaces for such objects.  Any
C/C++ code that includes <samp class="file">Rinternals.h</samp> should be called <em class="emph">via</em>
<code class="code">.Call</code> or <code class="code">.External</code>.
</p>
<p><code class="code">.Fortran</code> is primarily intended for Fortran 77 code, and long
precedes any support for &lsquo;modern&rsquo; Fortran.  Nowadays implementations of
Fortran support the Fortran 2003 module <code class="code">iso_c_binding</code>, a better
way to interface modern Fortran code to R is to use <code class="code">.C</code> and
write a C interface using <code class="code">use iso_c_binding</code>.
</p>
<hr>
</div>
<div class="section-level-extent" id="dyn_002eload-and-dyn_002eunload">
<div class="nav-panel">
<p>
Next: <a href="#Registering-native-routines" accesskey="n" rel="next">Registering native routines</a>, Previous: <a href="#Interface-functions-_002eC-and-_002eFortran" accesskey="p" rel="prev">Interface functions <code class="code">.C</code> and <code class="code">.Fortran</code></a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="dyn_002eload-and-dyn_002eunload-1"><span>5.3 <code class="code">dyn.load</code> and <code class="code">dyn.unload</code><a class="copiable-link" href="#dyn_002eload-and-dyn_002eunload-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Dynamic-loading"></a>

<a class="index-entry-id" id="index-dyn_002eload"></a>
<a class="index-entry-id" id="index-dyn_002eunload"></a>

<p>Compiled code to be used with R is loaded as a shared object
(Unix-alikes including macOS, see <a class="pxref" href="#Creating-shared-objects">Creating shared objects</a> for more
information) or DLL (Windows).
</p>
<p>The shared object/DLL is loaded by <code class="code">dyn.load</code> and unloaded by
<code class="code">dyn.unload</code>.  Unloading is not normally necessary and is not safe
in general, but it is needed to allow the DLL to be re-built on some
platforms, including Windows. Unloading a DLL and then re-loading a DLL
of the same name may not work: Solaris used the first version loaded. A
DLL that registers C finalizers, but fails to unregister them when
unloaded, may cause R to crash after unloading.
</p>
<p>The first argument to both functions is a character string giving the
path to the object.  Programmers should not assume a specific file
extension for the object/DLL (such as <samp class="file">.so</samp>) but use a construction
like
</p>
<div class="example">
<pre class="example-preformatted">file.path(path1, path2, paste0(&quot;mylib&quot;, .Platform$dynlib.ext))
</pre></div>

<p>for platform independence.  On Unix-alike systems the path supplied to
<code class="code">dyn.load</code> can be an absolute path, one relative to the current
directory or, if it starts with &lsquo;<samp class="samp">~</samp>&rsquo;, relative to the user&rsquo;s home
directory.
</p>
<p>Loading is most often done automatically based on the <code class="code">useDynLib()</code>
declaration in the <samp class="file">NAMESPACE</samp> file, but may be done
explicitly <em class="emph">via</em> a call to <code class="code">library.dynam</code>.
<a class="index-entry-id" id="index-library_002edynam-1"></a>
This has the form
</p>
<div class="example">
<pre class="example-preformatted">library.dynam(&quot;libname&quot;, package, lib.loc)
</pre></div>

<p>where <code class="code">libname</code> is the object/DLL name <em class="emph">with the extension
omitted</em>.  Note that the first argument, <code class="code">chname</code>, should
<strong class="strong">not</strong> be <code class="code">package</code> since this will not work if the package
is installed under another name.
</p>
<p>Under some Unix-alike systems there is a choice of how the symbols are
resolved when the object is loaded, governed by the arguments
<code class="code">local</code> and <code class="code">now</code>.  Only use these if really necessary: in
particular using <code class="code">now=FALSE</code> and then calling an unresolved symbol
will terminate R unceremoniously.
</p>
<p>R provides a way of executing some code automatically when a object/DLL
is either loaded or unloaded.  This can be used, for example, to
register native routines with R&rsquo;s dynamic symbol mechanism, initialize
some data in the native code, or initialize a third party library.  On
loading a DLL, R will look for a routine within that DLL named
<code class="code">R_init_<var class="var">lib</var></code> where <var class="var">lib</var> is the name of the DLL file with
the extension removed.  For example, in the command
</p>
<div class="example">
<pre class="example-preformatted">library.dynam(&quot;mylib&quot;, package, lib.loc)
</pre></div>

<p>R looks for the symbol named <code class="code">R_init_mylib</code>.  Similarly, when
unloading the object, R looks for a routine named
<code class="code">R_unload_<var class="var">lib</var></code>, e.g., <code class="code">R_unload_mylib</code>.  In either case,
if the routine is present, R will invoke it and pass it a single
argument describing the DLL.  This is a value of type <code class="code">DllInfo</code>
which is defined in the <samp class="file">Rdynload.h</samp> file in the <samp class="file">R_ext</samp>
directory.
</p>
<p>Note that there are some implicit restrictions on this mechanism as the
basename of the DLL needs to be both a valid file name and valid as part
of a C entry point (e.g. it cannot contain &lsquo;<samp class="samp">.</samp>&rsquo;): for portable
code it is best to confine DLL names to be <abbr class="acronym">ASCII</abbr> alphanumeric
plus underscore.  If entry point <code class="code">R_init_<var class="var">lib</var></code> is not found it
is also looked for with &lsquo;<samp class="samp">.</samp>&rsquo; replaced by &lsquo;<samp class="samp">_</samp>&rsquo;.
</p>

<p>The following example shows templates for the initialization and
unload routines for the <code class="code">mylib</code> DLL.
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">#include &lt;R_ext/Rdynload.h&gt;

void
R_init_mylib(DllInfo *info)
{
  /* Register routines,
     allocate resources. */
}

void
R_unload_mylib(DllInfo *info)
{
  /* Release resources. */
}
</pre></div>
</td></tr></table>
</blockquote>

<p>If a shared object/DLL is loaded more than once the most recent version
is used.<a class="footnote" id="DOCF145" href="#FOOT145"><sup>145</sup></a>  More generally, if the same symbol name
appears in several shared objects, the most recently loaded occurrence
is used.  The <code class="code">PACKAGE</code> argument and registration (see the next
section) provide good ways to avoid any ambiguity in which occurrence is
meant.
</p>
<p>On Unix-alikes the paths used to resolve dynamically linked dependent
libraries are fixed (for security reasons) when the process is launched,
so <code class="code">dyn.load</code> will only look for such libraries in the locations
set by the <samp class="file">R</samp> shell script (<em class="emph">via</em> <samp class="file">etc/ldpaths</samp>) and in
the OS-specific defaults.
</p>
<p>Windows allows more control (and less security) over where dependent
DLLs are looked for.  On all versions this includes the <code class="env">PATH</code>
environment variable, but with lowest priority: note that it does not
include the directory from which the DLL was loaded.  It is possible to
add a single path with quite high priority <em class="emph">via</em> the <code class="code">DLLpath</code>
argument to <code class="code">dyn.load</code>.  This is (by default) used by
<code class="code">library.dynam</code> to include the package&rsquo;s <samp class="file">libs/x64</samp> directory (on
Intel) in the DLL search path.
</p>

<hr>
</div>
<div class="section-level-extent" id="Registering-native-routines">
<div class="nav-panel">
<p>
Next: <a href="#Creating-shared-objects" accesskey="n" rel="next">Creating shared objects</a>, Previous: <a href="#dyn_002eload-and-dyn_002eunload" accesskey="p" rel="prev"><code class="code">dyn.load</code> and <code class="code">dyn.unload</code></a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Registering-native-routines-1"><span>5.4 Registering native routines<a class="copiable-link" href="#Registering-native-routines-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Registering-native-routines"></a>


<p>By &lsquo;native&rsquo; routine, we mean an entry point in compiled code.
</p>
<p>In calls to <code class="code">.C</code>, <code class="code">.Call</code>, <code class="code">.Fortran</code> and
<code class="code">.External</code>, R must locate the specified native routine by
looking in the appropriate shared object/DLL.  By default, R uses the
operating-system-specific dynamic loader to lookup the symbol in
all<a class="footnote" id="DOCF146" href="#FOOT146"><sup>146</sup></a> loaded DLLs and the R executable
or libraries it is linked to.  Alternatively, the author of the DLL can
explicitly register routines with R and use a single,
platform-independent mechanism for finding the routines in the DLL.  One
can use this registration mechanism to provide additional information
about a routine, including the number and type of the arguments, and
also make it available to R programmers under a different name.
</p>
<p>Registering routines has two main advantages: it provides a
faster<a class="footnote" id="DOCF147" href="#FOOT147"><sup>147</sup></a> way to
find the address of the entry point <em class="emph">via</em> tables stored in the DLL
at compilation time, and it provides a run-time check that the entry
point is called with the right number of arguments and, optionally, the
right argument types.
</p>
<a class="index-entry-id" id="index-R_005fregisterRoutines"></a>
<p>To register routines with R, one calls the C routine
<code class="code">R_registerRoutines</code>.  This is typically done when the DLL is first
loaded within the initialization routine <code class="code">R_init_<var class="var">dll name</var></code>
described in <a class="ref" href="#dyn_002eload-and-dyn_002eunload"><code class="code">dyn.load</code> and <code class="code">dyn.unload</code></a>.  <code class="code">R_registerRoutines</code>
takes 5 arguments.  The first is the <code class="code">DllInfo</code> object passed by
R to the initialization routine. This is where R stores the
information about the methods.  The remaining 4 arguments are arrays
describing the routines for each of the 4 different interfaces:
<code class="code">.C</code>, <code class="code">.Call</code>, <code class="code">.Fortran</code> and <code class="code">.External</code>.  Each
argument is a <code class="code">NULL</code>-terminated array of the element types given in
the following table:
</p>
<blockquote class="quotation">
<table summary="" class="multitable">
<tbody><tr><td><code class="code">.C</code></td><td><code class="code">R_CMethodDef</code></td></tr>
<tr><td><code class="code">.Call</code></td><td><code class="code">R_CallMethodDef</code></td></tr>
<tr><td><code class="code">.Fortran</code></td><td><code class="code">R_FortranMethodDef</code></td></tr>
<tr><td><code class="code">.External</code></td><td><code class="code">R_ExternalMethodDef</code></td></tr>
</tbody>
</table>
</blockquote>

<p>Currently, the <code class="code">R_ExternalMethodDef</code> type is the same as
<code class="code">R_CallMethodDef</code> type and contains fields for the name of the
routine by which it can be accessed in R, a pointer to the actual
native symbol (i.e., the routine itself), and the number of arguments
the routine expects to be passed from R. For example, if we had a
routine named <code class="code">myCall</code> defined as
</p>
<div class="example">
<pre class="example-preformatted">SEXP myCall(SEXP a, SEXP b, SEXP c);
</pre></div>

<p>we would describe this as
</p>
<div class="example">
<pre class="example-preformatted">static const R_CallMethodDef callMethods[]  = {
  {&quot;myCall&quot;, (DL_FUNC) &amp;myCall, 3},
  {NULL, NULL, 0}
};
</pre></div>

<p>along with any other routines for the <code class="code">.Call</code> interface. For
routines with a variable number of arguments invoked <em class="emph">via</em> the
<code class="code">.External</code> interface, one specifies <code class="code">-1</code> for the number of
arguments which tells R not to check the actual number passed.
</p>
<p>Routines for use with the <code class="code">.C</code> and <code class="code">.Fortran</code> interfaces are
described with similar data structures, which have one optional
additional field for describing the type of each argument.  If
specified, this field should be an array with the <code class="code">SEXP</code> types
describing the expected type of each argument of the routine.
(Technically, the elements of the types array are of type
<code class="code">R_NativePrimitiveArgType</code> which is just an unsigned integer.)
The R types and corresponding type identifiers are provided in the
following table:
</p>
<blockquote class="quotation">
<table summary="" class="multitable">
<tbody><tr><td><code class="code">numeric</code></td><td><code class="code">REALSXP</code></td></tr>
<tr><td><code class="code">integer</code></td><td><code class="code">INTSXP</code></td></tr>
<tr><td><code class="code">logical</code></td><td><code class="code">LGLSXP</code></td></tr>
<tr><td><code class="code">single</code></td><td><code class="code">SINGLESXP</code></td></tr>
<tr><td><code class="code">character</code></td><td><code class="code">STRSXP</code></td></tr>
<tr><td><code class="code">list</code></td><td><code class="code">VECSXP</code></td></tr>
</tbody>
</table>
</blockquote>

<p>Consider a C routine, <code class="code">myC</code>, declared as
</p>
<div class="example">
<pre class="example-preformatted">void myC(double *x, int *n, char **names, int *status);
</pre></div>

<p>We would register it as
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">static R_NativePrimitiveArgType myC_type[] = {
    REALSXP, INTSXP, STRSXP, LGLSXP
};

static const R_CMethodDef cMethods[] = {
   {&quot;myC&quot;, (DL_FUNC) &amp;myC, 4, myC_type},
   {NULL, NULL, 0, NULL}
};
</pre></div></div>


<p>If registering types, check carefully that the number of types matches
the number of arguments: as the type array (here <code class="code">myC_type</code>) is
passed as a pointer in C, the registration mechanism cannot check this
for you.
</p>
<p>Note that <code class="code">.Fortran</code> entry points are mapped to lowercase, so
registration should use lowercase only.
</p>
<p>Having created the arrays describing each routine, the last step is to
actually register them with R.  We do this by calling
<code class="code">R_registerRoutines</code>.  For example, if we have the descriptions
above for the routines accessed by the <code class="code">.C</code> and <code class="code">.Call</code>
we would use the following code:
</p>
<div class="example">
<pre class="example-preformatted">void
R_init_myLib(DllInfo *info)
{
   R_registerRoutines(info, cMethods, callMethods, NULL, NULL);
}
</pre></div>

<p>This routine will be invoked when R loads the shared object/DLL named
<code class="code">myLib</code>.  The last two arguments in the call to
<code class="code">R_registerRoutines</code> are for the routines accessed by
<code class="code">.Fortran</code> and <code class="code">.External</code> interfaces.  In our example, these
are given as <code class="code">NULL</code> since we have no routines of these types.
</p>
<p>When R unloads a shared object/DLL, its registrations are removed.
There is no other facility for unregistering a symbol.
</p>
<p>Examples of registering routines can be found in the different packages
in the R source tree (e.g., <strong class="strong">stats</strong> and <strong class="strong">graphics</strong>).  Also,
there is a brief, high-level introduction in <em class="emph">R News</em> (volume 1/3,
September 2001, pages 20&ndash;23,
<a class="uref" href="https://www.r-project.org/doc/Rnews/Rnews_2001-3.pdf">https://www.r-project.org/doc/Rnews/Rnews_2001-3.pdf</a>).
</p>
<p>Once routines are registered, they can be referred to as R objects if
this is arranged in the <code class="code">useDynLib</code> call in the package&rsquo;s
<samp class="file">NAMESPACE</samp> file (see <a class="ref" href="#useDynLib"><code class="code">useDynLib</code></a>).  So for example the
<strong class="strong">stats</strong> package has
</p><div class="example">
<pre class="example-preformatted"># Refer to all C/Fortran routines by their name prefixed by C_
useDynLib(stats, .registration = TRUE, .fixes = &quot;C_&quot;)
</pre></div>

<p>in its <samp class="file">NAMESPACE</samp> file, and then <code class="code">ansari.test</code>&rsquo;s default
methods can contain
</p><div class="example">
<pre class="example-preformatted">        pansari &lt;- function(q, m, n)
            .C(C_pansari, as.integer(length(q)), p = as.double(q),
                as.integer(m), as.integer(n))$p
</pre></div>

<p>This avoids the overhead of looking up an entry point each time it is
used, and ensures that the entry point in the package is the one used
(without a <code class="code">PACKAGE = &quot;pkg&quot;</code> argument).
</p>
<p><code class="code">R_init_</code> routines are often of the form
</p><div class="example">
<pre class="example-preformatted">void attribute_visible R_init_mypkg(DllInfo *dll)
{
    R_registerRoutines(dll, CEntries, CallEntries, FortEntries,
                       ExternalEntries);
    R_useDynamicSymbols(dll, FALSE);
    R_forceSymbols(dll, TRUE);
...
}
</pre></div>

<a class="index-entry-id" id="index-R_005fuseDynamicSymbols"></a>
<a class="index-entry-id" id="index-R_005fforceSymbols"></a>
<p>The <code class="code">R_useDynamicSymbols</code> call says the DLL is not to be searched
for entry points specified by character strings so <code class="code">.C</code> etc calls
will only find registered symbols: the <code class="code">R_forceSymbols</code> call only
allows <code class="code">.C</code> etc calls which specify entry points by R objects
such as <code class="code">C_pansari</code> (and not by character strings).  Each provides
some protection against accidentally finding your entry points when
people supply a character string without a package, and avoids slowing
down such searches.  (For the visibility attribute see <a class="pxref" href="#Controlling-visibility">Controlling visibility</a>.)
</p>
<p>In more detail, if a package <code class="code">mypkg</code> contains entry points
<code class="code">reg</code> and <code class="code">unreg</code> and the first is registered as a 0-argument
<code class="code">.Call</code> routine, we could use (from code in the package)
</p>
<div class="example">
<pre class="example-preformatted">.Call(&quot;reg&quot;)
.Call(&quot;unreg&quot;)
</pre></div>

<p>Without or with registration, these will both work.  If
<code class="code">R_init_mypkg</code> calls <code class="code">R_useDynamicSymbols(dll, FALSE)</code>, only
the first will work.  If in addition to registration the
<samp class="file">NAMESPACE</samp> file contains
</p>
<div class="example">
<pre class="example-preformatted">useDynLib(mypkg, .registration = TRUE, .fixes = &quot;C_&quot;)
</pre></div>

<p>then we can call <code class="code">.Call(C_reg)</code>.  Finally, if <code class="code">R_init_mypkg</code>
also calls <code class="code">R_forceSymbols(dll, TRUE)</code>, only <code class="code">.Call(C_reg)</code>
will work (and not <code class="code">.Call(&quot;reg&quot;)</code>).  This is usually what we want:
it ensures that all of our own <code class="code">.Call</code> calls go directly to the
intended code in our package and that no one else accidentally finds our
entry points.  (Should someone need to call our code from outside the
package, for example for debugging, they can use
<code class="code">.Call(mypkg:::C_reg)</code>.)
</p>

<ul class="mini-toc">
<li><a href="#Speed-considerations" accesskey="1">Speed considerations</a></li>
<li><a href="#Converting-a-package-to-use-registration" accesskey="2">Example: converting a package to use registration</a></li>
<li><a href="#Linking-to-native-routines-in-other-packages" accesskey="3">Linking to native routines in other packages</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Speed-considerations">
<div class="nav-panel">
<p>
Next: <a href="#Converting-a-package-to-use-registration" accesskey="n" rel="next">Example: converting a package to use registration</a>, Previous: <a href="#Registering-native-routines" accesskey="p" rel="prev">Registering native routines</a>, Up: <a href="#Registering-native-routines" accesskey="u" rel="up">Registering native routines</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Speed-considerations-1"><span>5.4.1 Speed considerations<a class="copiable-link" href="#Speed-considerations-1"> &para;</a></span></h4>

<p>Sometimes registering native routines or using a <code class="code">PACKAGE</code> argument
can make a large difference.  The results can depend quite markedly on
the OS (and even if it is 32- or 64-bit), on the version of R and
what else is loaded into R at the time.
</p>
<p>To fix ideas, first consider <code class="code">x86_64</code> OS 10.7 and R 2.15.2.  A
simple <code class="code">.Call</code> function might be
</p><div class="example">
<pre class="example-preformatted">foo &lt;- function(x) .Call(&quot;foo&quot;, x)
</pre></div>
<p>with C code
</p><div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;Rinternals.h&gt;

SEXP foo(SEXP x)
{
    return x;
}
</pre></div></div>
<p>If we compile with by <code class="command">R CMD SHLIB foo.c</code>, load the code by
<code class="code">dyn.load(&quot;foo.so&quot;)</code> and run <code class="code">foo(pi)</code> it took around 22
microseconds (us). Specifying the DLL by
</p><div class="example">
<pre class="example-preformatted">foo2 &lt;- function(x) .Call(&quot;foo&quot;, x, PACKAGE = &quot;foo&quot;)
</pre></div>
<p>reduced the time to 1.7 us.
</p>
<p>Now consider making these functions part of a package whose
<samp class="file">NAMESPACE</samp> file uses <code class="code">useDynlib(foo)</code>.  This immediately
reduces the running time as <code class="code">&quot;foo&quot;</code> will be preferentially looked
for <samp class="file">foo.dll</samp>.  Without specifying <code class="code">PACKAGE</code> it took about 5
us (it needs to fathom out the appropriate DLL each time it is invoked
but it does not need to search all DLLs), and with the <code class="code">PACKAGE</code>
argument it is again about 1.7 us.
</p>
<p>Next suppose the package has registered the native routine <code class="code">foo</code>.
Then <code class="code">foo()</code> still has to find the appropriate DLL but can get to
the entry point in the DLL faster, in about 4.2 us.  And <code class="code">foo2()</code>
now takes about 1 us.  If we register the symbols in the
<samp class="file">NAMESPACE</samp> file and use
</p><div class="example">
<pre class="example-preformatted">foo3 &lt;- function(x) .Call(C_foo, x)
</pre></div>
<p>then the address for the native routine is looked up just once when the
package is loaded, and <code class="code">foo3(pi)</code> takes about 0.8 us.
</p>
<p>Versions using <code class="code">.C()</code> rather than <code class="code">.Call()</code> took about 0.2 us
longer.
</p>
<p>These are all quite small differences, but C routines are not uncommonly
invoked millions of times for run times of a few microseconds each, and
those doing such things may wish to be aware of the differences.
</p>
<p>On Linux and Solaris there is a smaller overhead in looking up
symbols.
</p>
<p>Symbol lookup on Windows used to be far slower, so R maintains a
small cache.  If the cache is currently empty enough that the symbol can
be stored in the cache then the performance is similar to Linux and
Solaris: if not it may be slower.  R&rsquo;s own code always uses
registered symbols and so these never contribute to the cache: however
many other packages do rely on symbol lookup.
</p>
<p>In more recent versions of R all the standard packages register
native symbols and do not allow symbol search, so in a new session
<code class="code">foo()</code> can only look in <samp class="file">foo.so</samp> and may be as fast as
<code class="code">foo2()</code>.  This will no longer apply when many contributed packages
are loaded, and generally those last loaded are searched first.  For
example, consider R 3.3.2 on x86_64 Linux.  In an empty R session,
both <code class="code">foo()</code> and <code class="code">foo2()</code> took about 0.75 us; however after
packages <a class="url" href="https://CRAN.R-project.org/package=igraph"><strong class="strong">igraph</strong></a> and <a class="url" href="https://CRAN.R-project.org/package=spatstat"><strong class="strong">spatstat</strong></a> had been loaded (which
loaded another 12 DLLs), <code class="code">foo()</code> took 3.6 us but <code class="code">foo2()</code>
still took about 0.80 us.  Using registration in a package reduced this
to 0.55 us and <code class="code">foo3()</code> took 0.40 us, times which were unchanged
when further packages were loaded.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Converting-a-package-to-use-registration">
<div class="nav-panel">
<p>
Next: <a href="#Linking-to-native-routines-in-other-packages" accesskey="n" rel="next">Linking to native routines in other packages</a>, Previous: <a href="#Speed-considerations" accesskey="p" rel="prev">Speed considerations</a>, Up: <a href="#Registering-native-routines" accesskey="u" rel="up">Registering native routines</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Example_003a-converting-a-package-to-use-registration"><span>5.4.2 Example: converting a package to use registration<a class="copiable-link" href="#Example_003a-converting-a-package-to-use-registration"> &para;</a></span></h4>

<p>The <strong class="strong">splines</strong> package was converted to use symbol registration in
2001, but we can use it as an example<a class="footnote" id="DOCF148" href="#FOOT148"><sup>148</sup></a> of what needs to be done for a small package.
</p>
<ul class="itemize mark-bullet">
<li>Find the relevant entry points.
This is somewhat OS-specific, but something like the following should be
possible at the OS command-line

<div class="example">
<div class="group"><pre class="example-preformatted">nm -g /path/to/splines.so | grep &quot; T &quot;
0000000000002670 T _spline_basis
0000000000001ec0 T _spline_value
</pre></div></div>

<p>This indicates that there are two relevant entry points. (They may or
may not have a leading underscore, as here. Fortran entry points will
have a trailing underscore.)  Check in the R code that they are
called by the package and how: in this case they are used by
<code class="code">.Call</code>.
</p>
<p>Alternatively, examine the package&rsquo;s R code for all <code class="code">.C</code>,
<code class="code">.Fortran</code>, <code class="code">.Call</code> and <code class="code">.External</code> calls.
</p>
</li><li>Construct the registration table.  First write skeleton registration
code, conventionally in file <samp class="file">src/init.c</samp> (or at the end of the
only C source file in the package: if included in a C++ file the
&lsquo;<samp class="samp">R_init</samp>&rsquo; function would need to be declared <code class="code">extern &quot;C&quot;</code>):

<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;stdlib.h&gt; // for NULL
#include &lt;R_ext/Rdynload.h&gt;

#define CALLDEF(name, n)  {#name, (DL_FUNC) &amp;name, n}

static const R_CallMethodDef R_CallDef[] = {
   CALLDEF(spline_basis, ?),
   CALLDEF(spline_value, ?),
   {NULL, NULL, 0}
};

void R_init_splines(DllInfo *dll)
{
    R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);
}
</pre></div></div>

<p>and then replace the <code class="code">?</code> in the skeleton with the actual numbers of
arguments.  You will need to add declarations (also known as
&lsquo;prototypes&rsquo;) of the functions unless appending to the only C source
file.  Some packages will already have these in a header file, or you
could create one and include it in <samp class="file">init.c</samp>, for example
<samp class="file">splines.h</samp> containing
</p>
<div class="example smallexample">
<div class="group"><pre class="example-preformatted">#include &lt;Rinternals.h&gt; // for SEXP
extern SEXP spline_basis(SEXP knots, SEXP order, SEXP xvals, SEXP derivs);
extern SEXP spline_value(SEXP knots, SEXP coeff, SEXP order, SEXP x, SEXP deriv);
</pre></div></div>
<p>Tools are available to extract declarations, at least for C and C++
code: see the help file for
<code class="code">package_native_routine_registration_skeleton</code> in package
<strong class="strong">tools</strong>. Here we could have used
</p><div class="example">
<pre class="example-preformatted">cproto -I/path/to/R/include -e splines.c
</pre></div>

<p>For examples of registering other types of calls, see packages
<strong class="strong">graphics</strong> and <strong class="strong">stats</strong>.  In particular, when registering entry
points for <code class="code">.Fortran</code> one needs declarations as if called from C,
such as
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R_ext/RS.h&gt;
void F77_NAME(supsmu)(int *n, double *x, double *y,
                      double *w, int *iper, double *span, double *alpha,
                      double *smo, double *sc, double *edf);
</pre></div></div>

<p><code class="command">gfortran</code> 8.4, 9.2 and later can help generate such prototypes
with its flag <samp class="option">-fc-prototypes-external</samp> (although one will need
to replace the hard-coded trailing underscore with the <code class="code">F77_NAME</code>
macro).
</p>
<p>One can get away with inaccurate argument lists in the declarations: it
is easy to specify the arguments for <code class="code">.Call</code> (all <code class="code">SEXP</code>) and
<code class="code">.External</code> (one <code class="code">SEXP</code>) and as the arguments for <code class="code">.C</code>
and <code class="code">.Fortran</code> are all pointers, specifying them as <code class="code">void *</code>
suffices. (For most platforms one can omit all the arguments, although
link-time optimization will warn, as will compilers set up to warn on
strict prototypes &ndash; and C23 will require correct arguments.)
</p>
<p>Using <samp class="option">-fc-prototypes-external</samp> will give a prototype using
<code class="code">int_least32_t *lgl</code> for Fortran <code class="code">LOGICAL LGL</code>, but this is
not portable and traditionally it has been assumed that the C/C++
equivalent was <code class="code">int *lgl</code>.  If adding a declaration just to
register a <code class="code">.Fortran</code> call, the most portable version is <code class="code">void
*lgl</code>.
</p>
</li><li>(Optional but highly recommended.)  Restrict <code class="code">.Call</code> etc to use the
symbols you chose to register by editing <samp class="file">src/init.c</samp> to contain

<div class="example">
<div class="group"><pre class="example-preformatted">void R_init_splines(DllInfo *dll)
{
    R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);
    R_useDynamicSymbols(dll, FALSE);
}
</pre></div></div>

</li></ul>

<p>A skeleton for the steps so far can be made using
<code class="code">package_native_routine_registration_skeleton</code> in package
<strong class="strong">tools</strong>.  This will optionally create declarations based on the
usage in the R code.
</p>
<p>The remaining steps are optional but recommended.
</p>
<ul class="itemize mark-bullet">
<li>Edit the <samp class="file">NAMESPACE</samp> file to create R objects for the registered
symbols:

<div class="example">
<pre class="example-preformatted">useDynLib(splines, .registration = TRUE, .fixes = &quot;C_&quot;)
</pre></div>

</li><li>Find all the relevant calls in the R code and edit them to use the
R objects.  This entailed changing the lines

<div class="example smallexample">
<pre class="example-preformatted">temp &lt;- .Call(&quot;spline_basis&quot;, knots, ord, x, derivs, PACKAGE = &quot;splines&quot;)
y[accept] &lt;- .Call(&quot;spline_value&quot;, knots, coeff, ord, x[accept], deriv, PACKAGE = &quot;splines&quot;)
y = .Call(&quot;spline_value&quot;, knots, coef(object), ord, x, deriv, PACKAGE = &quot;splines&quot;)
</pre></div>
<p>to
</p>
<div class="example smallexample">
<pre class="example-preformatted">temp &lt;- .Call(C_spline_basis, knots, ord, x, derivs)
y[accept] &lt;- .Call(C_spline_value, knots, coeff, ord, x[accept], deriv)
y = .Call(C_spline_value, knots, coef(object), ord, x, deriv)
</pre></div>

<p>Check that there is no <code class="code">exportPattern</code> directive which
unintentionally exports the newly created R objects.
</p>
</li><li>Restrict <code class="code">.Call</code> to use the R symbols by editing
<samp class="file">src/init.c</samp> to contain

<div class="example">
<div class="group"><pre class="example-preformatted">void R_init_splines(DllInfo *dll)
{
    R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);
    R_useDynamicSymbols(dll, FALSE);
    R_forceSymbols(dll, TRUE);
}
</pre></div></div>

</li><li>Consider visibility.  On some OSes we can hide entry points from the
loader, which precludes any possible name clashes and calling them
accidentally (usually with incorrect arguments and crashing the R
process). If we repeat the first step we now see

<div class="example">
<div class="group"><pre class="example-preformatted">nm -g /path/to/splines.so | grep &quot; T &quot;
0000000000002e00 T _R_init_splines
00000000000025e0 T _spline_basis
0000000000001e20 T _spline_value
</pre></div></div>

<p>If there were any entry points not intended to be used by the package we
should try to avoid exporting them, for example by making them
<code class="code">static</code>.  Now that the two relevant entry points are only accessed
<em class="emph">via</em> the registration table, we can hide them.  There are two ways
to do so on some Unix-alikes.  We can hide individual entry points
<em class="emph">via</em>
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R_ext/Visibility.h&gt;

SEXP attribute_hidden
spline_basis(SEXP knots, SEXP order, SEXP xvals, SEXP derivs)
...

SEXP attribute_hidden
spline_value(SEXP knots, SEXP coeff, SEXP order, SEXP x, SEXP deriv)
...
</pre></div></div>

<p>Alternatively, we can change the default visibility for all C symbols by
including
</p>
<div class="example">
<pre class="example-preformatted">PKG_CFLAGS = $(C_VISIBILITY)
</pre></div>

<p>in <samp class="file">src/Makevars</samp>, and then we need to allow registration by
declaring <code class="code">R_init_splines</code> to be visible:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R_ext/Visibility.h&gt;

void attribute_visible
R_init_splines(DllInfo *dll)
...
</pre></div></div>

<p>See <a class="xref" href="#Controlling-visibility">Controlling visibility</a> for more details, including using Fortran
code and ways to restrict visibility on Windows.
</p>
</li><li>We end up with a file <samp class="file">src/init.c</samp> containing

<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">#include &lt;stdlib.h&gt;
#include &lt;R_ext/Rdynload.h&gt;
#include &lt;R_ext/Visibility.h&gt;  // optional

#include &quot;splines.h&quot;

#define CALLDEF(name, n)  {#name, (DL_FUNC) &amp;name, n}

static const R_CallMethodDef R_CallDef[] = {
    CALLDEF(spline_basis, 4),
    CALLDEF(spline_value, 5),
    {NULL, NULL, 0}
};

void
attribute_visible  // optional
R_init_splines(DllInfo *dll)
{
    R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);
    R_useDynamicSymbols(dll, FALSE);
    R_forceSymbols(dll, TRUE);
}
</pre></div>
</td></tr></table>
</blockquote>

</li></ul>

<hr>
</div>
<div class="subsection-level-extent" id="Linking-to-native-routines-in-other-packages">
<div class="nav-panel">
<p>
Previous: <a href="#Converting-a-package-to-use-registration" accesskey="p" rel="prev">Example: converting a package to use registration</a>, Up: <a href="#Registering-native-routines" accesskey="u" rel="up">Registering native routines</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Linking-to-native-routines-in-other-packages-1"><span>5.4.3 Linking to native routines in other packages<a class="copiable-link" href="#Linking-to-native-routines-in-other-packages-1"> &para;</a></span></h4>

<p>In addition to registering C routines to be called by R, it can at
times be useful for one package to make some of its C routines available
to be called by C code in another package.  The interface consists of
two routines declared in header <samp class="file">R_ext/Rdynload.h</samp> as
</p>
<a class="index-entry-id" id="index-R_005fRegisterCCallable"></a>
<a class="index-entry-id" id="index-R_005fGetCCallable"></a>
<div class="example">
<pre class="example-preformatted">void R_RegisterCCallable(const char *package, const char *name,
                         DL_FUNC fptr);
DL_FUNC R_GetCCallable(const char *package, const char *name);
</pre></div>

<p>A package <strong class="strong">packA</strong> that wants to make a C routine <code class="code">myCfun</code>
available to C code in other packages would include the call
</p>
<div class="example">
<pre class="example-preformatted">R_RegisterCCallable(&quot;packA&quot;, &quot;myCfun&quot;, myCfun);
</pre></div>
<p>in its initialization function <code class="code">R_init_packA</code>.  A package
<strong class="strong">packB</strong> that wants to use this routine would retrieve the function
pointer with a call of the form
</p>
<div class="example">
<pre class="example-preformatted">p_myCfun = R_GetCCallable(&quot;packA&quot;, &quot;myCfun&quot;);
</pre></div>
<p>As the type <code class="code">DL_FUNC</code> is only appropriate for functions with no
arguments, other users will need to cast to an appropriate type.  For
example
</p><div class="example">
<pre class="example-preformatted">typedef SEXP (*na_omit_xts_func) (SEXP x);
...
  na_omit_xts_func fun = (na_omit_xts_func) R_GetCCallable(&quot;xts&quot;, &quot;na_omit_xts&quot;);
  return fun(x);
</pre></div>

<p>The author of <strong class="strong">packB</strong> is responsible for ensuring that
<code class="code">p_myCfun</code> has an appropriate declaration. In the future R may
provide some automated tools to simplify exporting larger numbers of
routines.
</p>
<p>A package that wishes to make use of header files in other packages
needs to declare them as a comma-separated list in the field
&lsquo;<samp class="samp">LinkingTo</samp>&rsquo; in the <samp class="file">DESCRIPTION</samp> file.  This then arranges
for the <samp class="file">include</samp> directories in the installed linked-to packages
to be added to the include paths for C and C++ code.
</p>
<p>It must specify<a class="footnote" id="DOCF149" href="#FOOT149"><sup>149</sup></a>
&lsquo;<samp class="samp">Imports</samp>&rsquo; or &lsquo;<samp class="samp">Depends</samp>&rsquo; of those packages, for they have to be
loaded<a class="footnote" id="DOCF150" href="#FOOT150"><sup>150</sup></a> prior to this one
(so the path to their compiled code has been registered).
</p>

<p><abbr class="acronym">CRAN</abbr> examples of the use of this mechanism include <a class="url" href="https://CRAN.R-project.org/package=coxme"><strong class="strong">coxme</strong></a>
linking to <a class="url" href="https://CRAN.R-project.org/package=bdsmatrix"><strong class="strong">bdsmatrix</strong></a> and <a class="url" href="https://CRAN.R-project.org/package=xts"><strong class="strong">xts</strong></a> linking to
<a class="url" href="https://CRAN.R-project.org/package=zoo"><strong class="strong">zoo</strong></a>.
</p>
<p><strong class="strong">NB</strong>: this mechanism is fragile, as changes to the interface
provided by <strong class="strong">packA</strong> have to be recognised by <strong class="strong">packB</strong>.  The
consequences of not doing so have included serious corruption to the
memory pool of the R session.  Either <strong class="strong">packB</strong> has to depend on
the exact version of <strong class="strong">packA</strong> or there needs to be a mechanism for
<strong class="strong">packB</strong> to test at runtime the version of <strong class="strong">packA</strong> it is linked
to matches that it was compiled against.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Creating-shared-objects">
<div class="nav-panel">
<p>
Next: <a href="#Interfacing-C_002b_002b-code" accesskey="n" rel="next">Interfacing C++ code</a>, Previous: <a href="#Registering-native-routines" accesskey="p" rel="prev">Registering native routines</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Creating-shared-objects-1"><span>5.5 Creating shared objects<a class="copiable-link" href="#Creating-shared-objects-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Creating-shared-objects"></a>
<a class="index-entry-id" id="index-R-CMD-SHLIB"></a>

<p>Shared objects for loading into R can be created using <code class="command">R CMD
SHLIB</code>.  This accepts as arguments a list of files which must be object
files (with extension <samp class="file">.o</samp>) or sources for C, C++, Fortran,
Objective C or Objective C++ (with extensions <samp class="file">.c</samp>, <samp class="file">.cc</samp> or
<samp class="file">.cpp</samp>, <samp class="file">.f</samp> (fixed-form Fortran), <samp class="file">.f90</samp> or <samp class="file">.f95</samp>
(free-form), <samp class="file">.m</samp>, and <samp class="file">.mm</samp> or <samp class="file">.M</samp>, respectively), or
commands to be passed to the linker.  See <kbd class="kbd">R CMD SHLIB --help</kbd> (or
the R help for <code class="code">SHLIB</code>) for usage information.  Note that files
intended for the Fortran pre-processor with extension <samp class="file">.F</samp> are not
accepted.
</p>
<p>If compiling the source files does not work &ldquo;out of the box&rdquo;, you can
specify additional flags by setting some of the variables
<a class="index-entry-id" id="index-PKG_005fCPPFLAGS"></a>
<code class="code">PKG_CPPFLAGS</code> (for the C/C++ preprocessor, mainly &lsquo;<samp class="samp">-I</samp>&rsquo;,
&lsquo;<samp class="samp">-D</samp>&rsquo; and &lsquo;<samp class="samp">-U</samp>&rsquo; flags),
<a class="index-entry-id" id="index-PKG_005fCFLAGS"></a>
<a class="index-entry-id" id="index-PKG_005fCXXFLAGS"></a>
<a class="index-entry-id" id="index-PKG_005fFFLAGS"></a>
<a class="index-entry-id" id="index-PKG_005fOBJCFLAGS"></a>
<a class="index-entry-id" id="index-PKG_005fOBJCXXFLAGS"></a>
<code class="code">PKG_CFLAGS</code>, <code class="code">PKG_CXXFLAGS</code>, <code class="code">PKG_FFLAGS</code>,
<code class="code">PKG_OBJCFLAGS</code>, and <code class="code">PKG_OBJCXXFLAGS</code>
(for the C, C++, Fortran, Objective C, and Objective C++
compilers, respectively) in the file <samp class="file">Makevars</samp> in the compilation
directory (or, of course, create the object files directly from the
command line).
<a class="index-entry-id" id="index-PKG_005fLIBS"></a>
Similarly, variable <code class="code">PKG_LIBS</code> in <samp class="file">Makevars</samp> can be used for
additional &lsquo;<samp class="samp">-l</samp>&rsquo; and &lsquo;<samp class="samp">-L</samp>&rsquo; flags to be passed to the linker when
building the shared object. (Supplying linker commands as arguments to
<code class="code">R CMD SHLIB</code> will take precedence over <code class="code">PKG_LIBS</code> in
<samp class="file">Makevars</samp>.)
</p>
<a class="index-entry-id" id="index-OBJECTS-1"></a>
<p>It is possible to arrange to include compiled code from other languages
by setting the macro &lsquo;<samp class="samp">OBJECTS</samp>&rsquo; in file <samp class="file">Makevars</samp>, together
with suitable rules to make the objects.
</p>
<p>Flags that are already set (for example in file
<samp class="file">etc<var class="var">R_ARCH</var>/Makeconf</samp>) can be overridden by the environment
variable <code class="env">MAKEFLAGS</code> (at least for systems using a POSIX-compliant
<code class="code">make</code>), as in (Bourne shell syntax)
</p>
<div class="example">
<pre class="example-preformatted">MAKEFLAGS=&quot;CFLAGS=-O3&quot; R CMD SHLIB *.c
</pre></div>

<p>It is also possible to set such variables in personal <samp class="file">Makevars</samp>
files, which are read after the local <samp class="file">Makevars</samp> and the system
makefiles or in a site-wide <samp class="file">Makevars.site</samp> file.
See <a data-manual="R-admin" href="https://cran.r-project.org/doc/manuals/R-admin.html#Customizing-package-compilation">Customizing package compilation</a> in <cite class="cite">R Installation and Administration</cite>,
</p>
<p>Note that as <code class="command">R CMD SHLIB</code> uses Make, it will not remake a shared
object just because the flags have changed, and if <samp class="file">test.c</samp> and
<samp class="file">test.f</samp> both exist in the current directory
</p>
<div class="example">
<pre class="example-preformatted">R CMD SHLIB test.f
</pre></div>

<p>will compile <samp class="file">test.c</samp>!
</p>

<p>If the <samp class="file">src</samp> subdirectory of an add-on package contains source code
with one of the extensions listed above or a file <samp class="file">Makevars</samp> but
<strong class="strong">not</strong> a file <samp class="file">Makefile</samp>, <code class="command">R CMD INSTALL</code> creates a
shared object (for loading into R through <code class="code">useDynlib</code> in the
<samp class="file">NAMESPACE</samp>, or in the <code class="code">.onLoad</code> function of the package)
using the <code class="command">R CMD SHLIB</code> mechanism.  If file <samp class="file">Makevars</samp>
exists it is read first, then the system makefile and then any personal
<samp class="file">Makevars</samp> files.
</p>
<p>If the <samp class="file">src</samp> subdirectory of package contains a file
<samp class="file">Makefile</samp>, this is used by <code class="command">R CMD INSTALL</code> in place of the
<code class="code">R CMD SHLIB</code> mechanism.  <code class="command">make</code> is called with makefiles
<samp class="file"><var class="var">R_HOME</var>/etc<var class="var">R_ARCH</var>/Makeconf</samp>, <samp class="file">src/Makefile</samp> and
any personal <samp class="file">Makevars</samp> files (in that order).  The first target
found in <samp class="file">src/Makefile</samp> is used.
</p>
<p>It is better to make use of a <samp class="file">Makevars</samp> file rather than a
<samp class="file">Makefile</samp>: the latter should be needed only exceptionally.
</p>

<p>Under Windows the same commands work, but <samp class="file">Makevars.win</samp> will be
used in preference to <samp class="file">Makevars</samp>, and only <samp class="file">src/Makefile.win</samp>
will be used by <code class="code">R CMD INSTALL</code> with <samp class="file">src/Makefile</samp> being
ignored. Since R 4.2.0, <samp class="file">Makevars.ucrt</samp> will be used in preference to
<samp class="file">Makevars.win</samp> and <samp class="file">src/Makefile.ucrt</samp> will be used in preference
to <samp class="file">src/Makefile.win</samp>.
For past experiences of building DLLs with a variety of
compilers, see file &lsquo;<samp class="samp">README.packages</samp>&rsquo;.  
Under Windows you can supply an exports definitions file called
<samp class="file"><var class="var">dllname</var>-win.def</samp>: otherwise all entry points in objects (but
not libraries) supplied to <code class="code">R CMD SHLIB</code> will be exported from the
DLL.  An example is <samp class="file">stats-win.def</samp> for the <strong class="strong">stats</strong> package: a
<abbr class="acronym">CRAN</abbr> example in package <a class="url" href="https://CRAN.R-project.org/package=fastICA"><strong class="strong">fastICA</strong></a>.
</p>
<p>If you feel tempted to read the source code and subvert these
mechanisms, please resist.  Far too much developer time has been wasted
in chasing down errors caused by failures to follow this documentation,
and even more by package authors demanding explanations as to why their
packages no longer work.
In particular, undocumented environment or <code class="command">make</code> variables are
not for use by package writers and are subject to change without notice.
</p>
<hr>
</div>
<div class="section-level-extent" id="Interfacing-C_002b_002b-code">
<div class="nav-panel">
<p>
Next: <a href="#Fortran-I_002fO" accesskey="n" rel="next">Fortran I/O</a>, Previous: <a href="#Creating-shared-objects" accesskey="p" rel="prev">Creating shared objects</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Interfacing-C_002b_002b-code-1"><span>5.6 Interfacing C++ code<a class="copiable-link" href="#Interfacing-C_002b_002b-code-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Interfacing-C_002b_002b-code"></a>
<a class="index-entry-id" id="index-C_002b_002b-code_002c-interfacing"></a>

<p>Suppose we have the following hypothetical C++ library, consisting of
the two files <samp class="file">X.h</samp> and <samp class="file">X.cpp</samp>, and implementing the two
classes <code class="code">X</code> and <code class="code">Y</code> which we want to use in R.
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">// X.h

class X {
public: X (); ~X ();
};

class Y {
public: Y (); ~Y ();
};
</pre></div>
</td></tr></table>
</blockquote>

<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">// X.cpp

#include &lt;R.h&gt;
#include &quot;X.h&quot;

static Y y;

X::X()  { REprintf(&quot;constructor X\n&quot;); }
X::~X() { REprintf(&quot;destructor X\n&quot;);  }
Y::Y()  { REprintf(&quot;constructor Y\n&quot;); }
Y::~Y() { REprintf(&quot;destructor Y\n&quot;);  }
</pre></div>
</td></tr></table>
</blockquote>

<p>To use with R, the only thing we have to do is writing a wrapper
function and ensuring that the function is enclosed in
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">extern &quot;C&quot; {

}
</pre></div></div>

<p>For example,
</p>
<blockquote class="quotation">
<table summary="" class="cartouche" border="1"><tr><td>
<div class="example">
<pre class="example-preformatted">// X_main.cpp:

#include &quot;X.h&quot;

extern &quot;C&quot; {

void X_main () {
  X x;
}

} // extern &quot;C&quot;
</pre></div>
</td></tr></table>
</blockquote>

<p>Compiling and linking should be done with the C++ compiler-linker
(rather than the C compiler-linker or the linker itself); otherwise, the
C++ initialization code (and hence the constructor of the static
variable <code class="code">Y</code>) are not called.  On a properly configured system, one
can simply use
</p>
<div class="example">
<pre class="example-preformatted">R CMD SHLIB X.cpp X_main.cpp
</pre></div>

<p>to create the shared object, typically <samp class="file">X.so</samp> (the file name
extension may be different on your platform).  Now starting R yields
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">R version 2.14.1 Patched (2012-01-16 r58124)
Copyright (C) 2012 The R Foundation for Statistical Computing
...
Type    &quot;q()&quot; to quit R.
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">R&gt; dyn.load(paste(&quot;X&quot;, .Platform$dynlib.ext, sep = &quot;&quot;))
constructor Y
R&gt; .C(&quot;X_main&quot;)
constructor X
destructor X
list()
R&gt; q()
Save workspace image? [y/n/c]: y
destructor Y
</pre></div></div>

<p>The R for Windows <abbr class="acronym">FAQ</abbr> (<samp class="file">rw-FAQ</samp>) contains details of how
to compile this example under Windows.
</p>
<p>Earlier versions of this example used C++ iostreams: this is best
avoided.  There is no guarantee that the output will appear in the R
console, and indeed it will not on the R for Windows console.  Use
R code or the C entry points (see <a class="pxref" href="#Printing">Printing</a>) for all I/O if at all
possible.  Examples have been seen where merely loading a DLL that
contained calls to C++ I/O upset R&rsquo;s own C I/O (for example by
resetting buffers on open files).
</p>
<p>Most R header files can be included within C++ programs but they
should <strong class="strong">not</strong> be included within an <code class="code">extern &quot;C&quot;</code> block (as
they include system headers<a class="footnote" id="DOCF151" href="#FOOT151"><sup>151</sup></a>).
</p>
<ul class="mini-toc">
<li><a href="#External-C_002b_002b-code" accesskey="1">External C++ code</a></li>
</ul>
<div class="subsection-level-extent" id="External-C_002b_002b-code">
<h4 class="subsection"><span>5.6.1 External C++ code<a class="copiable-link" href="#External-C_002b_002b-code"> &para;</a></span></h4>

<p>Quite a lot of external C++ software is header-only (e.g. most of the
Boost &lsquo;libraries&rsquo; including all those supplied by package <a class="url" href="https://CRAN.R-project.org/package=BH"><strong class="strong">BH</strong></a>,
and most of Armadillo as supplied by package <a class="url" href="https://CRAN.R-project.org/package=RcppArmadillo"><strong class="strong">RcppArmadillo</strong></a>)
and so is compiled when an R package which uses it is installed.
This causes few problems.
</p>
<p>A small number of external libraries used in R packages have a C++
interface to a library of compiled code, e.g. packages <a class="url" href="https://CRAN.R-project.org/package=sf"><strong class="strong">sf</strong></a>
and <a class="url" href="https://CRAN.R-project.org/package=rjags"><strong class="strong">rjags</strong></a>.  This raises many more problems!  The C++ interface
uses name-mangling and the
<abbr class="abbr">ABI</abbr><a class="footnote" id="DOCF152" href="#FOOT152"><sup>152</sup></a>
may depend on the compiler, version and even C++ defines<a class="footnote" id="DOCF153" href="#FOOT153"><sup>153</sup></a>,
so requires the package C++ code to be compiled in exactly the same way
as the library (and what that was is often undocumented).
</p>

<p>Even fewer external libraries use C++ internally but present a C
interface, such as <a class="url" href="https://CRAN.R-project.org/package=rgeos"><strong class="strong">rgeos</strong></a>.  These require the C++ runtime
library to be linked into the package&rsquo;s shared object/DLL, and this is
best done by including a dummy C++ file in the package sources.
</p>
<p>There is a trend to link to the C++ interfaces offered by C software
such as <strong class="strong">hdf5</strong>, <strong class="strong">pcre</strong> and <strong class="strong">ImageMagick</strong>.  Their C
interfaces are much preferred for portability (and can be used from C++
code).  Also, the C++ interfaces are often optional in the software
build or packaged separately and so users installing from package
sources are less likely to already have them installed.
</p>

<hr>
</div>
</div>
<div class="section-level-extent" id="Fortran-I_002fO">
<div class="nav-panel">
<p>
Next: <a href="#Linking-to-other-packages" accesskey="n" rel="next">Linking to other packages</a>, Previous: <a href="#Interfacing-C_002b_002b-code" accesskey="p" rel="prev">Interfacing C++ code</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Fortran-I_002fO-1"><span>5.7 Fortran I/O<a class="copiable-link" href="#Fortran-I_002fO-1"> &para;</a></span></h3>

<p>We have already warned against the use of C++ iostreams not least
because output is not guaranteed to appear on the R console, and this
warning applies equally to Fortran output to units <code class="code">*</code>
and <code class="code">6</code>. See <a class="xref" href="#Printing-from-Fortran">Printing from Fortran</a>, which describes workarounds.
</p>
<p>In the past most Fortran compilers implemented I/O on top of the C I/O
system and so the two interworked successfully.  This was true of
<code class="command">g77</code>, but it is less true of <code class="command">gfortran</code> as used in
<code class="command">gcc</code> 4 and later.  In particular, any package that makes use of
Fortran I/O will when compiled on Windows interfere with C I/O: when the
Fortran I/O support code is initialized (typically when the package is
loaded) the C <code class="code">stdout</code> and <code class="code">stderr</code> are switched to <abbr class="abbr">LF</abbr> line
endings.  (Function <code class="code">init</code> in file
<samp class="file">src/modules/lapack/init_win.c</samp> shows how to mitigate this.  In a
package this would look something like
</p><div class="example">
<pre class="example-preformatted">#ifdef _WIN32
# include &lt;fcntl.h&gt;
#endif

void R_init_mypkgname(DllInfo *dll)
{
    // Native symbol registration calls

#ifdef _WIN32
    // gfortran I/O initialization sets these to _O_BINARY
    setmode(1, _O_TEXT); /* stdout */
    setmode(2, _O_TEXT); /* stderr */
#endif
}
</pre></div>
<p>in the file used for native symbol registration.)
</p>

<hr>
</div>
<div class="section-level-extent" id="Linking-to-other-packages">
<div class="nav-panel">
<p>
Next: <a href="#Handling-R-objects-in-C" accesskey="n" rel="next">Handling R objects in C</a>, Previous: <a href="#Fortran-I_002fO" accesskey="p" rel="prev">Fortran I/O</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Linking-to-other-packages-1"><span>5.8 Linking to other packages<a class="copiable-link" href="#Linking-to-other-packages-1"> &para;</a></span></h3>

<p>It is not in general possible to link a DLL in package <strong class="strong">packA</strong> to a
DLL provided by package <strong class="strong">packB</strong> (for the security reasons mentioned
in <a class="ref" href="#dyn_002eload-and-dyn_002eunload"><code class="code">dyn.load</code> and <code class="code">dyn.unload</code></a>, and also because some platforms
distinguish between shared objects and dynamic libraries), but it is on
Windows.
</p>
<p>Note that there can be tricky versioning issues here, as package
<strong class="strong">packB</strong> could be re-installed after package <strong class="strong">packA</strong> &mdash; it is
desirable that the API provided by package <strong class="strong">packB</strong> remains
backwards-compatible.
</p>
<p>Shipping a static library in package <strong class="strong">packB</strong> for other packages to
link to avoids most of the difficulties.
</p>

<ul class="mini-toc">
<li><a href="#Unix_002dalikes" accesskey="1">Unix-alikes</a></li>
<li><a href="#Windows" accesskey="2">Windows</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Unix_002dalikes">
<div class="nav-panel">
<p>
Next: <a href="#Windows" accesskey="n" rel="next">Windows</a>, Previous: <a href="#Linking-to-other-packages" accesskey="p" rel="prev">Linking to other packages</a>, Up: <a href="#Linking-to-other-packages" accesskey="u" rel="up">Linking to other packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Unix_002dalikes-1"><span>5.8.1 Unix-alikes<a class="copiable-link" href="#Unix_002dalikes-1"> &para;</a></span></h4>

<p>It is possible to link a shared object in package <strong class="strong">packA</strong> to a
library provided by package <strong class="strong">packB</strong> under limited circumstances
on a Unix-alike OS.  There are severe portability issues, so this is not
recommended for a distributed package.
</p>
<p>This is easiest if <strong class="strong">packB</strong> provides a static library
<samp class="file">packB/lib/libpackB.a</samp>.  (Note using directory <samp class="file">lib</samp> rather
than <samp class="file">libs</samp> is conventional, and architecture-specific
sub-directories may be needed and are assumed in the sample code
below. The code in the static library will need to be compiled with
<code class="code">PIC</code> flags on platforms where it matters.)  Then as the code from
package <strong class="strong">packB</strong> is incorporated when package <strong class="strong">packA</strong> is
installed, we only need to find the static library at install time for
package <strong class="strong">packA</strong>.  The only issue is to find package <strong class="strong">packB</strong>, and
for that we can ask R by something like (long lines broken for
display here)
</p>
<div class="example">
<pre class="example-preformatted">PKGB_PATH=‘echo ’library(packB);
  cat(system.file(&quot;lib&quot;,  package=&quot;packB&quot;, mustWork=TRUE))' \
 | &quot;${R_HOME}/bin/R&quot; --vanilla --no-echo`
PKG_LIBS=&quot;$(PKGB_PATH)$(R_ARCH)/libpackB.a&quot;
</pre></div>

<p>For a dynamic library <samp class="file">packB/lib/libpackB.so</samp>
(<samp class="file">packB/lib/libpackB.dylib</samp> on macOS: note that you cannot link to
a shared object, <samp class="file">.so</samp>, on that platform) we could use
</p>
<div class="example">
<pre class="example-preformatted">PKGB_PATH=‘echo ’library(packB);
  cat(system.file(&quot;lib&quot;, package=&quot;packB&quot;, mustWork=TRUE))' \
 | &quot;${R_HOME}/bin/R&quot; --vanilla --no-echo`
PKG_LIBS=-L&quot;$(PKGB_PATH)$(R_ARCH)&quot; -lpackB
</pre></div>

<p>This will work for installation, but very likely not when package
<code class="code">packB</code> is loaded, as the path to package <strong class="strong">packB</strong>&rsquo;s <samp class="file">lib</samp>
directory is not in the <code class="command">ld.so</code><a class="footnote" id="DOCF154" href="#FOOT154"><sup>154</sup></a>  search path.  You can arrange to
put it there <strong class="strong">before</strong> R is launched by setting (on some
platforms) <code class="env">LD_RUN_PATH</code> or <code class="env">LD_LIBRARY_PATH</code> or adding to the
<code class="command">ld.so</code> cache (see <code class="command">man ldconfig</code>).  On platforms that
support it, the path to the directory containing the dynamic library can
be hardcoded at install time (which assumes that the location of package
<strong class="strong">packB</strong> will not be changed nor the package updated to a changed
API).  On systems with the <code class="command">gcc</code> or <code class="command">clang</code> and the
<abbr class="acronym">GNU</abbr> linker (e.g. Linux) and some others this can be done by
e.g.
</p>
<div class="example">
<pre class="example-preformatted">PKGB_PATH=‘echo ’library(packB);
  cat(system.file(&quot;lib&quot;, package=&quot;packB&quot;, mustWork=TRUE)))' \
 | &quot;${R_HOME}/bin/R&quot; --vanilla --no-echo`
PKG_LIBS=-L&quot;$(PKGB_PATH)$(R_ARCH)&quot; -Wl,-rpath,&quot;$(PKGB_PATH)$(R_ARCH)&quot; -lpackB
</pre></div>

<p>Some other systems (e.g. Solaris with its native linker) use
<samp class="option">-Rdir</samp> rather than <samp class="option">-rpath,dir</samp> (and this is accepted by
the compiler as well as the linker).
</p>
<p>It may be possible to figure out what is required semi-automatically
from the result of <code class="command">R CMD libtool --config</code> (look for
&lsquo;<samp class="samp">hardcode</samp>&rsquo;).
</p>
<p>Making headers provided by package <strong class="strong">packB</strong> available to the code to
be compiled in package <strong class="strong">packA</strong> can be done by the <code class="code">LinkingTo</code>
mechanism (see <a class="pxref" href="#Registering-native-routines">Registering native routines</a>).
</p>

<hr>
</div>
<div class="subsection-level-extent" id="Windows">
<div class="nav-panel">
<p>
Previous: <a href="#Unix_002dalikes" accesskey="p" rel="prev">Unix-alikes</a>, Up: <a href="#Linking-to-other-packages" accesskey="u" rel="up">Linking to other packages</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Windows-1"><span>5.8.2 Windows<a class="copiable-link" href="#Windows-1"> &para;</a></span></h4>

<p>Suppose package <strong class="strong">packA</strong> wants to make use of compiled code provided
by <strong class="strong">packB</strong> in DLL <samp class="file">packB/libs/exB.dll</samp>, possibly the package&rsquo;s
DLL <samp class="file">packB/libs/packB.dll</samp>.  (This can be extended to linking to
more than one package in a similar way.)  There are three issues to be
addressed:
</p>
<ul class="itemize mark-bullet">
<li>Making headers provided by package <strong class="strong">packB</strong> available to the code to
be compiled in package <strong class="strong">packA</strong>.

<p>This is done by the <code class="code">LinkingTo</code> mechanism (see <a class="pxref" href="#Registering-native-routines">Registering native routines</a>).
</p>
</li><li>preparing <code class="code">packA.dll</code> to link to <samp class="file">packB/libs/exB.dll</samp>.

<p>This needs an entry in <samp class="file">Makevars.win</samp> or <samp class="file">Makevars.ucrt</samp> of the form
</p>
<div class="example">
<pre class="example-preformatted">PKG_LIBS= -L&lt;something&gt; -lexB
</pre></div>
<p>and one possibility is that <code class="code">&lt;something&gt;</code> is the path to the
installed <samp class="file">pkgB/libs</samp> directory.  To find that we need to ask R
where it is by something like
</p>
<div class="example">
<pre class="example-preformatted">PKGB_PATH=‘echo ’library(packB);
  cat(system.file(&quot;libs&quot;, package=&quot;packB&quot;, mustWork=TRUE))' \
 | rterm --vanilla --no-echo`
PKG_LIBS= -L&quot;$(PKGB_PATH)$(R_ARCH)&quot; -lexB
</pre></div>

<p>Another possibility is to use an import library, shipping with package
<strong class="strong">packA</strong> an exports file <samp class="file">exB.def</samp>.  Then <samp class="file">Makevars.win</samp> (or
<samp class="file">Makevars.ucrt</samp>)
could contain
</p>
<div class="example">
<pre class="example-preformatted">PKG_LIBS= -L. -lexB

all: $(SHLIB) before

before: libexB.dll.a
libexB.dll.a: exB.def
</pre></div>
<p>and then installing package <strong class="strong">packA</strong> will make and use the import
library for <samp class="file">exB.dll</samp>.  (One way to prepare the exports file is to
use <samp class="file">pexports.exe</samp>.)
</p>
</li><li>loading <samp class="file">packA.dll</samp> which depends on <samp class="file">exB.dll</samp>.

<p>If <code class="code">exB.dll</code> was used by package <strong class="strong">packB</strong> (because it is in fact
<samp class="file">packB.dll</samp> or <samp class="file">packB.dll</samp> depends on it) and <strong class="strong">packB</strong> has
been loaded before <strong class="strong">packA</strong>, then nothing more needs to be done as
<samp class="file">exB.dll</samp> will already be loaded into the R executable.  (This
is the most common scenario.)
</p>
<p>More generally, we can use the <code class="code">DLLpath</code> argument to
<code class="code">library.dynam</code> to ensure that <code class="code">exB.dll</code> is found, for example
by setting
</p>
<div class="example">
<pre class="example-preformatted">library.dynam(&quot;packA&quot;, pkg, lib,
              DLLpath = system.file(&quot;libs&quot;, package=&quot;packB&quot;))
</pre></div>

<p>Note that <code class="code">DLLpath</code> can only set one path, and so for linking to
two or more packages you would need to resort to setting environment
variable <code class="env">PATH</code>.
</p>
</li></ul>

<hr>
</div>
</div>
<div class="section-level-extent" id="Handling-R-objects-in-C">
<div class="nav-panel">
<p>
Next: <a href="#Interface-functions-_002eCall-and-_002eExternal" accesskey="n" rel="next">Interface functions <code class="code">.Call</code> and <code class="code">.External</code></a>, Previous: <a href="#Linking-to-other-packages" accesskey="p" rel="prev">Linking to other packages</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Handling-R-objects-in-C-1"><span>5.9 Handling R objects in C<a class="copiable-link" href="#Handling-R-objects-in-C-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Handling-R-objects-in-C"></a>

<p>Using C code to speed up the execution of an R function is often very
fruitful.  Traditionally this has been done <em class="emph">via</em> the <code class="code">.C</code>
function in R.  However, if a user wants to write C code using
internal R data structures, then that can be done using the
<code class="code">.Call</code> and <code class="code">.External</code> functions.  The syntax for the calling
function in R in each case is similar to that of <code class="code">.C</code>, but the
two functions have different C interfaces.  Generally the <code class="code">.Call</code>
interface is simpler to use, but <code class="code">.External</code> is a little more
general.
<a class="index-entry-id" id="index-_002eCall"></a>
<a class="index-entry-id" id="index-_002eExternal"></a>
</p>
<p>A call to <code class="code">.Call</code> is very similar to <code class="code">.C</code>, for example
</p>
<div class="example">
<pre class="example-preformatted">.Call(&quot;convolve2&quot;, a, b)
</pre></div>

<p>The first argument should be a character string giving a C symbol name
of code that has already been loaded into R.  Up to 65 R objects
can passed as arguments.  The C side of the interface is
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt;
#include &lt;Rinternals.h&gt;

SEXP convolve2(SEXP a, SEXP b)
 ...
</pre></div></div>

<p>A call to <code class="code">.External</code> is almost identical
</p>
<div class="example">
<pre class="example-preformatted">.External(&quot;convolveE&quot;, a, b)
</pre></div>

<p>but the C side of the interface is different, having only one argument
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt;
#include &lt;Rinternals.h&gt;

SEXP convolveE(SEXP args)
 ...
</pre></div></div>

<p>Here <code class="code">args</code> is a <code class="code">LISTSXP</code>, a Lisp-style pairlist from which
the arguments can be extracted.
</p>
<p>In each case the R objects are available for manipulation <em class="emph">via</em>
a set of functions and macros defined in the header file
<samp class="file">Rinternals.h</samp> or some S-compatibility macros<a class="footnote" id="DOCF155" href="#FOOT155"><sup>155</sup></a>  See
<a class="ref" href="#Interface-functions-_002eCall-and-_002eExternal">Interface functions <code class="code">.Call</code> and <code class="code">.External</code></a> for details on
<code class="code">.Call</code> and <code class="code">.External</code>.
</p>
<p>Before you decide to use <code class="code">.Call</code> or <code class="code">.External</code>, you should
look at other alternatives.  First, consider working in interpreted R
code; if this is fast enough, this is normally the best option.  You
should also see if using <code class="code">.C</code> is enough.  If the task to be
performed in C is simple enough involving only atomic vectors and
requiring no call to R, <code class="code">.C</code> suffices. A great deal of useful
code was written using just <code class="code">.C</code> before <code class="code">.Call</code> and
<code class="code">.External</code> were available.  These interfaces allow much more
control, but they also impose much greater responsibilities so need to
be used with care.  Neither <code class="code">.Call</code> nor <code class="code">.External</code> copy their
arguments: you should treat arguments you receive through these
interfaces as read-only.
</p>
<p>To handle R objects from within C code we use the macros and functions
that have been used to implement the core parts of R.  A
public<a class="footnote" id="DOCF156" href="#FOOT156"><sup>156</sup></a>  subset of these is defined in the header file
<samp class="file">Rinternals.h</samp> in the directory <samp class="file"><var class="var">R_INCLUDE_DIR</var></samp> (default
<samp class="file"><var class="var">R_HOME</var>/include</samp>) that should be available on any R
installation.
</p>
<p>A substantial amount of R, including the standard packages, is
implemented using the functions and macros described here, so the R
source code provides a rich source of examples and &ldquo;how to do it&rdquo;: do
make use of the source code for inspirational examples.
</p>
<p>It is necessary to know something about how R objects are handled in
C code.  All the R objects you will deal with will be handled with
the type <em class="dfn">SEXP</em><a class="footnote" id="DOCF157" href="#FOOT157"><sup>157</sup></a>, which is a
pointer to a structure with typedef <code class="code">SEXPREC</code>.  Think of this
structure as a <em class="emph">variant type</em> that can handle all the usual types
of R objects, that is vectors of various modes, functions,
environments, language objects and so on.  The details are given later
in this section and in 
<a data-manual="R-ints" href="https://cran.r-project.org/doc/manuals/R-ints.html#R-Internal-Structures">R Internal Structures</a> in <cite class="cite">R Internals</cite>,
but for most
purposes the programmer does not need to know them.  Think rather of a
model such as that used by Visual Basic, in which R objects are
handed around in C code (as they are in interpreted R code) as the
variant type, and the appropriate part is extracted for, for example,
numerical calculations, only when it is needed.  As in interpreted R
code, much use is made of coercion to force the variant object to the
right type.
</p>

<ul class="mini-toc">
<li><a href="#Garbage-Collection" accesskey="1">Handling the effects of garbage collection</a></li>
<li><a href="#Allocating-storage" accesskey="2">Allocating storage</a></li>
<li><a href="#Details-of-R-types" accesskey="3">Details of R types</a></li>
<li><a href="#Attributes" accesskey="4">Attributes</a></li>
<li><a href="#Classes" accesskey="5">Classes</a></li>
<li><a href="#Handling-lists" accesskey="6">Handling lists</a></li>
<li><a href="#Handling-character-data" accesskey="7">Handling character data</a></li>
<li><a href="#Finding-and-setting-variables" accesskey="8">Finding and setting variables</a></li>
<li><a href="#Some-convenience-functions" accesskey="9">Some convenience functions</a></li>
<li><a href="#Named-objects-and-copying">Named objects and copying</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Garbage-Collection">
<div class="nav-panel">
<p>
Next: <a href="#Allocating-storage" accesskey="n" rel="next">Allocating storage</a>, Previous: <a href="#Handling-R-objects-in-C" accesskey="p" rel="prev">Handling R objects in C</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Handling-the-effects-of-garbage-collection"><span>5.9.1 Handling the effects of garbage collection<a class="copiable-link" href="#Handling-the-effects-of-garbage-collection"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Garbage-collection"></a>

<a class="index-entry-id" id="index-PROTECT"></a>
<a class="index-entry-id" id="index-UNPROTECT"></a>
<a class="index-entry-id" id="index-protect"></a>
<a class="index-entry-id" id="index-unprotect"></a>

<p>We need to know a little about the way R handles memory allocation.
The memory allocated for R objects is not freed by the user; instead,
the memory is from time to time <em class="dfn">garbage collected</em>.  That is, some
or all of the allocated memory not being used is freed or marked as
re-usable.
</p>
<p>The R object types are represented by a C structure defined by a
typedef <code class="code">SEXPREC</code> in <samp class="file">Rinternals.h</samp>.  It contains several
things among which are pointers to data blocks and to other
<code class="code">SEXPREC</code>s.  A <code class="code">SEXP</code> is simply a pointer to a <code class="code">SEXPREC</code>.
</p>
<p>If you create an R object in your C code, you must tell R that you
are using the object by using the <code class="code">PROTECT</code> macro on a pointer to
the object. This tells R that the object is in use so it is not
destroyed during garbage collection.  Notice that it is the object which
is protected, not the pointer variable.  It is a common mistake to
believe that if you invoked <code class="code">PROTECT(<var class="var">p</var>)</code> at some point then
<var class="var">p</var> is protected from then on, but that is not true once a new
object is assigned to <var class="var">p</var>.
</p>
<p>Protecting an R object automatically protects all the R objects
pointed to in the corresponding <code class="code">SEXPREC</code>, for example all elements
of a protected list are automatically protected.
</p>
<p>The programmer is solely responsible for housekeeping the calls to
<code class="code">PROTECT</code>.  There is a corresponding macro <code class="code">UNPROTECT</code> that
takes as argument an <code class="code">int</code> giving the number of objects to
unprotect when they are no longer needed.  The protection mechanism is
stack-based, so <code class="code">UNPROTECT(<var class="var">n</var>)</code> unprotects the last <var class="var">n</var>
objects which were protected.  The calls to <code class="code">PROTECT</code> and
<code class="code">UNPROTECT</code> must balance when the user&rsquo;s code returns and should
balance in all functions.  R will warn about
<code class="code">&quot;stack imbalance in .Call&quot;</code> (or <code class="code">.External</code>) if the 
housekeeping is wrong. 
</p>
<p>Here is a small example of creating an R numeric vector in C code:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt;
#include &lt;Rinternals.h&gt;

    SEXP ab;
      ....
    ab = PROTECT(allocVector(REALSXP, 2));
    REAL(ab)[0] = 123.45;
    REAL(ab)[1] = 67.89;
    UNPROTECT(1);
</pre></div></div>

<p>Now, the reader may ask how the R object could possibly get removed
during those manipulations, as it is just our C code that is running.
As it happens, we can do without the protection in this example, but in
general we do not know (nor want to know) what is hiding behind the R
macros and functions we use, and any of them might cause memory to be
allocated, hence garbage collection and hence our object <code class="code">ab</code> to be
removed. It is usually wise to err on the side of caution and assume
that any of the R macros and functions might remove the object.
</p>
<p>In some cases it is necessary to keep better track of whether protection
is really needed.  Be particularly aware of situations where a large
number of objects are generated.  The pointer protection stack has a
fixed size (default 10,000) and can become full.  It is not a good idea
then to just <code class="code">PROTECT</code> everything in sight and <code class="code">UNPROTECT</code>
several thousand objects at the end. It will almost invariably be
possible to either assign the objects as part of another object (which
automatically protects them) or unprotect them immediately after use.
</p>
<p>There is a less-used macro <code class="code">UNPROTECT_PTR(<var class="var">s</var>)</code> that unprotects the
object pointed to by the <code class="code">SEXP</code> <var class="var">s</var>, even if it is not the top item
on the pointer protection stack.  This macro was introduced for use in the
parser, where the code interfacing with the R heap is generated and the
generator cannot be configured to insert proper calls to <code class="code">PROTECT</code> and
<code class="code">UNPROTECT</code>.  However, <code class="code">UNPROTECT_PTR</code> is dangerous to use in
combination with <code class="code">UNPROTECT</code> when the same object has been protected
multiple times.  It has been superseded by multi-set based functions
<code class="code">R_PreserveInMSet</code> and <code class="code">R_ReleaseFromMSet</code>, which protect objects
in a multi-set created by <code class="code">R_NewPreciousMSet</code> and typically itself
protected using <code class="code">PROTECT</code>.  These functions should not be needed
outside parsers.
<a class="index-entry-id" id="index-UNPROTECT_005fPTR"></a>
<a class="index-entry-id" id="index-unprotect_005fptr"></a>
<a class="index-entry-id" id="index-R_005fPreserveInMSet"></a>
<a class="index-entry-id" id="index-R_005fReleaseFromMSet"></a>
<a class="index-entry-id" id="index-R_005fNewPreciousMSet"></a>
</p>
<p>Sometimes an object is changed (for example duplicated, coerced or
grown) yet the current value needs to be protected.  For these cases
<code class="code">PROTECT_WITH_INDEX</code> saves an index of the protection location that
can be used to replace the protected value using <code class="code">REPROTECT</code>.
<a class="index-entry-id" id="index-PROTECT_005fWITH_005fINDEX"></a>
<a class="index-entry-id" id="index-REPROTECT"></a>
<a class="index-entry-id" id="index-R_005fProtectWithIndex"></a>
<a class="index-entry-id" id="index-R_005fReprotect"></a>
For example (from the internal code for <code class="code">optim</code>)
</p>
<div class="example">
<pre class="example-preformatted">    PROTECT_INDEX ipx;

    ....
    PROTECT_WITH_INDEX(s = eval(OS-&gt;R_fcall, OS-&gt;R_env), &amp;ipx);
    REPROTECT(s = coerceVector(s, REALSXP), ipx);
</pre></div>

<p>Note that it is dangerous to mix <code class="code">UNPROTECT_PTR</code> also with
<code class="code">PROTECT_WITH_INDEX</code>, as the former changes the protection
locations of objects that were protected after the one being
unprotected.
</p>
<a class="index-entry-id" id="index-R_005fPreserveObject"></a>
<a class="index-entry-id" id="index-R_005fReleaseObject"></a>
<p>There is another way to avoid the effects of garbage collection: a call
to <code class="code">R_PreserveObject</code> adds an object to an internal list of objects
not to be collects, and a subsequent call to <code class="code">R_ReleaseObject</code>
removes it from that list.  This provides a way for objects which are
not returned as part of R objects to be protected across calls to
compiled code: on the other hand it becomes the user&rsquo;s responsibility to
release them when they are no longer needed (and this often requires the
use of a finalizer).  It is less efficient than the normal protection
mechanism, and should be used sparingly.
</p>
<p>For functions from packages as well as R to safely co-operate in
protecting objects, certain rules have to be followed:
</p>
<ul class="itemize mark-bullet">
<li>Pointer-protection balance.  Calls to <code class="code">PROTECT</code> and <code class="code">UNPROTECT</code>
should balance in each function.  A function may only call <code class="code">UNPROTECT</code> or
<code class="code">REPROTECT</code> on objects it has itself protected.  Note that the pointer
protection stack balance is restored automatically on non-local transfer of
control (See <a class="ref" href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a>.), as if a call to
<code class="code">UNPROTECT</code> was invoked with the right argument.

</li><li>Caller protection.  It is the responsibility of the caller that all
arguments passed to a function are protected and will stay protected for the
whole execution of the callee.  Typically this is achieved by <code class="code">PROTECT</code>
and <code class="code">UNPROTECT</code> calls.

</li><li>Protecting return values. Any R objects returned from a function are
unprotected (the callee must maintain pointer-protection balance), and hence
should be protected immediately by the caller. To be safe against future
code changes, assume that any R object returned from any function may
need protection. Note that even when conceptually returning an existing
protected object, that object may be duplicated.

</li><li>All functions/macros allocate.  To be safe against future code changes,
assume that any function or macro may allocate and hence garbage collector
may run and destroy unprotected objects.

</li></ul>

<p>It is always safe and recommended to follow those rules.  In fact, several
R functions and macros protect their own arguments and some functions do
not allocate or do not allocate when used in a certain way, but that is
subject to change, so relying on that may be fragile.  <code class="code">PROTECT</code> and
<code class="code">PROTECT_WITH_INDEX</code> can be safely called with unprotected arguments
and <code class="code">UNPROTECT</code> does not allocate.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Allocating-storage">
<div class="nav-panel">
<p>
Next: <a href="#Details-of-R-types" accesskey="n" rel="next">Details of R types</a>, Previous: <a href="#Garbage-Collection" accesskey="p" rel="prev">Handling the effects of garbage collection</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Allocating-storage-1"><span>5.9.2 Allocating storage<a class="copiable-link" href="#Allocating-storage-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Allocating-storage"></a>

<p>For many purposes it is sufficient to allocate R objects and
manipulate those.  There are quite a few <code class="code">alloc<var class="var">Xxx</var></code> functions
defined in <samp class="file">Rinternals.h</samp>&mdash;you may want to explore them.
</p>
<a class="index-entry-id" id="index-allocVector"></a>
<p>One that is commonly used is <code class="code">allocVector</code>, the C-level equivalent
of R-level <code class="code">vector()</code> and its wrappers such as <code class="code">integer()</code>
and <code class="code">character()</code>.  One distinction is that whereas the R
functions always initialize the elements of the vector,
<code class="code">allocVector</code> only does so for lists, expressions and character
vectors (the cases where the elements are themselves R objects).
</p>
<p>If storage is required for C objects during the calculations this is
best allocating by calling <code class="code">R_alloc</code>; see <a class="pxref" href="#Memory-allocation">Memory allocation</a>.
All of these memory allocation routines do their own error-checking, so
the programmer may assume that they will raise an error and not return
if the memory cannot be allocated.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Details-of-R-types">
<div class="nav-panel">
<p>
Next: <a href="#Attributes" accesskey="n" rel="next">Attributes</a>, Previous: <a href="#Allocating-storage" accesskey="p" rel="prev">Allocating storage</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Details-of-R-types-1"><span>5.9.3 Details of R types<a class="copiable-link" href="#Details-of-R-types-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Details-of-R-types"></a>

<p>Users of the <samp class="file">Rinternals.h</samp> macros will need to know how the R
types are known internally.  The different R data types are
represented in C by <em class="dfn">SEXPTYPE</em>.  Some of these are familiar from
R and some are internal data types.  The usual R object modes are
given in the table.
</p>
<blockquote class="quotation">
<table summary="" class="multitable">
<thead><tr><th>SEXPTYPE</th><th>R equivalent</th></tr></thead>
<tbody><tr><td><code class="code">REALSXP</code></td><td>numeric with storage mode <code class="code">double</code></td></tr>
<tr><td><code class="code">INTSXP</code></td><td>integer</td></tr>
<tr><td><code class="code">CPLXSXP</code></td><td>complex</td></tr>
<tr><td><code class="code">LGLSXP</code></td><td>logical</td></tr>
<tr><td><code class="code">STRSXP</code></td><td>character</td></tr>
<tr><td><code class="code">VECSXP</code></td><td>list (generic vector)</td></tr>
<tr><td><code class="code">LISTSXP</code></td><td>pairlist</td></tr>
<tr><td><code class="code">DOTSXP</code></td><td>a &lsquo;<samp class="samp">&hellip;</samp>&rsquo; object</td></tr>
<tr><td><code class="code">NILSXP</code></td><td>NULL</td></tr>
<tr><td><code class="code">SYMSXP</code></td><td>name/symbol</td></tr>
<tr><td><code class="code">CLOSXP</code></td><td>function or function closure</td></tr>
<tr><td><code class="code">ENVSXP</code></td><td>environment</td></tr>
</tbody>
</table>
</blockquote>

<p>Among the important internal <code class="code">SEXPTYPE</code>s are <code class="code">LANGSXP</code>,
<code class="code">CHARSXP</code>, <code class="code">PROMSXP</code>, etc.  (<strong class="strong">N.B.</strong>: although it is
possible to return objects of internal types, it is unsafe to do so as
assumptions are made about how they are handled which may be violated at
user-level evaluation.)  More details are given in 
<a data-manual="R-ints" href="https://cran.r-project.org/doc/manuals/R-ints.html#R-Internal-Structures">R Internal Structures</a> in <cite class="cite">R Internals</cite>.
</p>
<p>Unless you are very sure about the type of the arguments, the code
should check the data types.  Sometimes it may also be necessary to
check data types of objects created by evaluating an R expression in
the C code.  You can use functions like <code class="code">isReal</code>, <code class="code">isInteger</code>
and <code class="code">isString</code> to do type checking.
<a class="index-entry-id" id="index-isReal"></a>
<a class="index-entry-id" id="index-isInteger"></a>
<a class="index-entry-id" id="index-isString"></a>
Other such functions declared in the header file <samp class="file">Rinternals.h</samp>
include <code class="code">isNull</code>, <code class="code">isSymbol</code>, <code class="code">isLogical</code>,
<code class="code">isComplex</code>, <code class="code">isExpression</code>, and <code class="code">isEnvironment</code>.
<a class="index-entry-id" id="index-isNull"></a>
<a class="index-entry-id" id="index-isSymbol"></a>
<a class="index-entry-id" id="index-isLogical"></a>
<a class="index-entry-id" id="index-isComplex"></a>
<a class="index-entry-id" id="index-isExpression"></a>
<a class="index-entry-id" id="index-isEnvironment"></a>
All of these take a <code class="code">SEXP</code> as argument and return 1 or 0 to
indicate <var class="var">TRUE</var> or <var class="var">FALSE</var>.
</p>
<p>What happens if the <code class="code">SEXP</code> is not of the correct type?  Sometimes
you have no other option except to generate an error.  You can use the
function <code class="code">error</code> for this.  It is usually better to coerce the
object to the correct type.  For example, if you find that an
<code class="code">SEXP</code> is of the type <code class="code">INTEGER</code>, but you need a <code class="code">REAL</code>
object, you can change the type by using
</p>
<div class="example">
<pre class="example-preformatted"><var class="var">newSexp</var> = PROTECT(coerceVector(<var class="var">oldSexp</var>, REALSXP));
</pre></div>
<a class="index-entry-id" id="index-coerceVector"></a>

<p>Protection is needed as a new <em class="emph">object</em> is created; the object
formerly pointed to by the <code class="code">SEXP</code> is still protected but now
unused.<a class="footnote" id="DOCF158" href="#FOOT158"><sup>158</sup></a>
</p>
<p>All the coercion functions do their own error-checking, and generate
<code class="code">NA</code>s with a warning or stop with an error as appropriate.
</p>
<p>Note that these coercion functions are <em class="emph">not</em> the same as calling
<code class="code">as.numeric</code> (and so on) in R code, as they do not dispatch on
the class of the object.  Thus it is normally preferable to do the
coercion in the calling R code.
</p>
<p>So far we have only seen how to create and coerce R objects from C
code, and how to extract the numeric data from numeric R vectors.
These can suffice to take us a long way in interfacing R objects to
numerical algorithms, but we may need to know a little more to create
useful return objects.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Attributes">
<div class="nav-panel">
<p>
Next: <a href="#Classes" accesskey="n" rel="next">Classes</a>, Previous: <a href="#Details-of-R-types" accesskey="p" rel="prev">Details of R types</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Attributes-1"><span>5.9.4 Attributes<a class="copiable-link" href="#Attributes-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Attributes"></a>

<p>Many R objects have attributes: some of the most useful are classes
and the <code class="code">dim</code> and <code class="code">dimnames</code> that mark objects as matrices or
arrays.  It can also be helpful to work with the <code class="code">names</code> attribute
of vectors.
</p>
<p>To illustrate this, let us write code to take the outer product of two
vectors (which <code class="code">outer</code> and <code class="code">%o%</code> already do).  As usual the
R code is simple
</p>
<div class="example">
<pre class="example-preformatted">out &lt;- function(x, y)
{
    storage.mode(x) &lt;- storage.mode(y) &lt;- &quot;double&quot;
    .Call(&quot;out&quot;, x, y)
}
</pre></div>

<p>where we expect <code class="code">x</code> and <code class="code">y</code> to be numeric vectors (possibly
integer), possibly with names.  This time we do the coercion in the
calling R code.
</p>
<p>C code to do the computations is
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt;
#include &lt;Rinternals.h&gt;

SEXP out(SEXP x, SEXP y)
{
    int nx = length(x), ny = length(y);
    SEXP ans = PROTECT(allocMatrix(REALSXP, nx, ny));
    double *rx = REAL(x), *ry = REAL(y), *rans = REAL(ans);
    for(int i = 0; i &lt; nx; i++) {
        double tmp = rx[i];
        for(int j = 0; j &lt; ny; j++)
            rans[i + nx*j] = tmp * ry[j];
    }
    UNPROTECT(1);
    return ans;
}
</pre></div></div>

<p>Note the way <code class="code">REAL</code> is used: as it is a function call it can be
considerably faster to store the result and index that.
</p>
<p>However, we would like to set the <code class="code">dimnames</code> of the result.  We can use
</p>
<div class="example">
<pre class="example-preformatted">#include &lt;R.h&gt;
#include &lt;Rinternals.h&gt;

</pre><div class="group"><pre class="example-preformatted">SEXP out(SEXP x, SEXP y)
{
    int nx = length(x), ny = length(y);
    SEXP ans = PROTECT(allocMatrix(REALSXP, nx, ny));
    double *rx = REAL(x), *ry = REAL(y), *rans = REAL(ans);

    for(int i = 0; i &lt; nx; i++) {
      double tmp = rx[i];
      for(int j = 0; j &lt; ny; j++)
        rans[i + nx*j] = tmp * ry[j];
    }

    SEXP dimnames = PROTECT(allocVector(VECSXP, 2));
    SET_VECTOR_ELT(dimnames, 0, getAttrib(x, R_NamesSymbol));
    SET_VECTOR_ELT(dimnames, 1, getAttrib(y, R_NamesSymbol));
    setAttrib(ans, R_DimNamesSymbol, dimnames);
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">    UNPROTECT(2);
    return ans;
}
</pre></div></div>

<p>This example introduces several new features.  The <code class="code">getAttrib</code> and
<code class="code">setAttrib</code>
<a class="index-entry-id" id="index-getAttrib"></a>
<a class="index-entry-id" id="index-setAttrib"></a>
functions get and set individual attributes.  Their second argument is a
<code class="code">SEXP</code> defining the name in the symbol table of the attribute we
want; these and many such symbols are defined in the header file
<samp class="file">Rinternals.h</samp>.
</p>
<p>There are shortcuts here too: the functions <code class="code">namesgets</code>,
<code class="code">dimgets</code> and <code class="code">dimnamesgets</code> are the internal versions of the
default methods of <code class="code">names&lt;-</code>, <code class="code">dim&lt;-</code> and <code class="code">dimnames&lt;-</code>
(for vectors and arrays), and there are functions such as
<code class="code">GetColNames</code>, <code class="code">GetRowNames</code>, <code class="code">GetMatrixDimnames</code> and
<code class="code">GetArrayDimnames</code>.
<a class="index-entry-id" id="index-GetArrayDimnames"></a>
<a class="index-entry-id" id="index-GetMatrixDimnames"></a>
<a class="index-entry-id" id="index-GetColNames"></a>
<a class="index-entry-id" id="index-GetRowNames"></a>
<a class="index-entry-id" id="index-namesgets"></a>
<a class="index-entry-id" id="index-dimnamesgets"></a>
<a class="index-entry-id" id="index-dimgets"></a>
</p>
<p>What happens if we want to add an attribute that is not pre-defined? We
need to add a symbol for it <em class="emph">via</em> a call to
<a class="index-entry-id" id="index-install"></a>
<code class="code">install</code>.  Suppose for illustration we wanted to add an attribute
<code class="code">&quot;version&quot;</code> with value <code class="code">3.0</code>.  We could use
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">    SEXP version;
    version = PROTECT(allocVector(REALSXP, 1));
    REAL(version)[0] = 3.0;
    setAttrib(ans, install(&quot;version&quot;), version);
    UNPROTECT(1);
</pre></div></div>

<p>Using <code class="code">install</code> when it is not needed is harmless and provides a
simple way to retrieve the symbol from the symbol table if it is already
installed. However, the lookup takes a non-trivial amount of time, so
consider code such as
</p>
<div class="example">
<pre class="example-preformatted">static SEXP VerSymbol = NULL;
...
    if (VerSymbol == NULL) VerSymbol = install(&quot;version&quot;);
</pre></div>

<p>if it is to be done frequently.
</p>
<p>This example can be simplified by another convenience function:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">    SEXP version = PROTECT(ScalarReal(3.0));
    setAttrib(ans, install(&quot;version&quot;), version);
    UNPROTECT(1);
</pre></div></div>


<hr>
</div>
<div class="subsection-level-extent" id="Classes">
<div class="nav-panel">
<p>
Next: <a href="#Handling-lists" accesskey="n" rel="next">Handling lists</a>, Previous: <a href="#Attributes" accesskey="p" rel="prev">Attributes</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Classes-1"><span>5.9.5 Classes<a class="copiable-link" href="#Classes-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Classes"></a>

<p>In R the class is just the attribute named <code class="code">&quot;class&quot;</code> so it can
be handled as such, but there is a shortcut <code class="code">classgets</code>.  Suppose
we want to give the return value in our example the class <code class="code">&quot;mat&quot;</code>.
We can use
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt;
#include &lt;Rinternals.h&gt;
      ....
    SEXP ans, dim, dimnames, class;
      ....
    class = PROTECT(allocVector(STRSXP, 1));
    SET_STRING_ELT(class, 0, mkChar(&quot;mat&quot;));
    classgets(ans, class);
    UNPROTECT(4);
    return ans;
}
</pre></div></div>
<a class="index-entry-id" id="index-classgets"></a>

<p>As the value is a character vector, we have to know how to create that
from a C character array, which we do using the function
<code class="code">mkChar</code>.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Handling-lists">
<div class="nav-panel">
<p>
Next: <a href="#Handling-character-data" accesskey="n" rel="next">Handling character data</a>, Previous: <a href="#Classes" accesskey="p" rel="prev">Classes</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Handling-lists-1"><span>5.9.6 Handling lists<a class="copiable-link" href="#Handling-lists-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Handling-lists"></a>

<p>Some care is needed with lists, as R moved early on from using
LISP-like lists (now called &ldquo;pairlists&rdquo;) to S-like generic vectors.
As a result, the appropriate test for an object of mode <code class="code">list</code> is
<code class="code">isNewList</code>, and we need <code class="code">allocVector(VECSXP, <var class="var">n</var></code>) and
<em class="emph">not</em> <code class="code">allocList(<var class="var">n</var>)</code>.
</p>
<p>List elements can be retrieved or set by direct access to the elements
of the generic vector.  Suppose we have a list object
</p>
<div class="example">
<pre class="example-preformatted">a &lt;- list(f = 1, g = 2, h = 3)
</pre></div>

<p>Then we can access <code class="code">a$g</code> as <code class="code">a[[2]]</code> by
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">    double g;
      ....
    g = REAL(VECTOR_ELT(a, 1))[0];
</pre></div></div>

<p>This can rapidly become tedious, and the following function (based on
one in package <strong class="strong">stats</strong>) is very useful:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">/* get the list element named str, or return NULL */

SEXP getListElement(SEXP list, const char *str)
{
    SEXP elmt = R_NilValue, names = getAttrib(list, R_NamesSymbol);
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">    for (int i = 0; i &lt; length(list); i++)
        if(strcmp(CHAR(STRING_ELT(names, i)), str) == 0) {
           elmt = VECTOR_ELT(list, i);
           break;
        }
    return elmt;
}
</pre></div></div>

<p>and enables us to say
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">  double g;
  g = REAL(getListElement(a, &quot;g&quot;))[0];
</pre></div></div>

<hr>
</div>
<div class="subsection-level-extent" id="Handling-character-data">
<div class="nav-panel">
<p>
Next: <a href="#Finding-and-setting-variables" accesskey="n" rel="next">Finding and setting variables</a>, Previous: <a href="#Handling-lists" accesskey="p" rel="prev">Handling lists</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Handling-character-data-1"><span>5.9.7 Handling character data<a class="copiable-link" href="#Handling-character-data-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-handling-character-data"></a>

<p>R character vectors are stored as <code class="code">STRSXP</code>s, a vector type like
<code class="code">VECSXP</code> where every element is of type <code class="code">CHARSXP</code>.  The
<code class="code">CHARSXP</code> elements of <code class="code">STRSXP</code>s are accessed using
<code class="code">STRING_ELT</code> and <code class="code">SET_STRING_ELT</code>.
<a class="index-entry-id" id="index-STRING_005fELT"></a>
<a class="index-entry-id" id="index-SET_005fSTRING_005fELT"></a>
</p>
<p><code class="code">CHARSXP</code>s are read-only objects and must never be modified.  In
particular, the C-style string contained in a <code class="code">CHARSXP</code> should be
treated as read-only and for this reason the <code class="code">CHAR</code> function used
to access the character data of a <code class="code">CHARSXP</code> returns <code class="code">(const
char *)</code> (this also allows compilers to issue warnings about improper
use).  Since <code class="code">CHARSXP</code>s are immutable, the same <code class="code">CHARSXP</code> can
be shared by any <code class="code">STRSXP</code> needing an element representing the same
string. R maintains a global cache of <code class="code">CHARSXP</code>s so that there
is only ever one <code class="code">CHARSXP</code> representing a given string in memory.
</p>
<a class="index-entry-id" id="index-mkChar"></a>
<a class="index-entry-id" id="index-mkCharLen"></a>
<p>You can obtain a <code class="code">CHARSXP</code> by calling <code class="code">mkChar</code> and providing a
<abbr class="abbr">NUL</abbr>-terminated C-style string.  This function will return a pre-existing
<code class="code">CHARSXP</code> if one with a matching string already exists, otherwise
it will create a new one and add it to the cache before returning it to
you.   The variant <code class="code">mkCharLen</code> can be used to create a
<code class="code">CHARSXP</code> from part of a buffer and will ensure null-termination.
</p>
<p>Note that R character strings are restricted to <code class="code">2^31 - 1</code>
bytes, and hence so should the input to <code class="code">mkChar</code> be (C allows
longer strings on 64-bit platforms).
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Finding-and-setting-variables">
<div class="nav-panel">
<p>
Next: <a href="#Some-convenience-functions" accesskey="n" rel="next">Some convenience functions</a>, Previous: <a href="#Handling-character-data" accesskey="p" rel="prev">Handling character data</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Finding-and-setting-variables-1"><span>5.9.8 Finding and setting variables<a class="copiable-link" href="#Finding-and-setting-variables-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Finding-variables"></a>
<a class="index-entry-id" id="index-Setting-variables"></a>

<p>It will be usual that all the R objects needed in our C computations
are passed as arguments to <code class="code">.Call</code> or <code class="code">.External</code>, but it is
possible to find the values of R objects from within the C given
their names.  The following code is the equivalent of <code class="code">get(name,
envir = rho)</code>.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">SEXP getvar(SEXP name, SEXP rho)
{
    SEXP ans;

    if(!isString(name) || length(name) != 1)
        error(&quot;name is not a single string&quot;);
    if(!isEnvironment(rho))
        error(&quot;rho should be an environment&quot;);
    ans = findVar(installChar(STRING_ELT(name, 0)), rho);
    Rprintf(&quot;first value is %f\n&quot;, REAL(ans)[0]);
    return R_NilValue;
}
</pre></div></div>
<a class="index-entry-id" id="index-installChar"></a>

<p>The main work is done by
<a class="index-entry-id" id="index-findVar"></a>
<code class="code">findVar</code>, but to use it we need to install <code class="code">name</code> as a name
in the symbol table.  As we wanted the value for internal use, we return
<code class="code">NULL</code>.
</p>
<p>Similar functions with syntax
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">void defineVar(SEXP symbol, SEXP value, SEXP rho)
void setVar(SEXP symbol, SEXP value, SEXP rho)
</pre></div></div>
<a class="index-entry-id" id="index-defineVar"></a>
<a class="index-entry-id" id="index-setVar"></a>

<p>can be used to assign values to R variables.  <code class="code">defineVar</code>
creates a new binding or changes the value of an existing binding in the
specified environment frame; it is the analogue of <code class="code">assign(symbol,
value, envir = rho, inherits = FALSE)</code>, but unlike <code class="code">assign</code>,
<code class="code">defineVar</code> does not make a copy of the object
<code class="code">value</code>.<a class="footnote" id="DOCF159" href="#FOOT159"><sup>159</sup></a>  <code class="code">setVar</code> searches for an existing
binding for <code class="code">symbol</code> in <code class="code">rho</code> or its enclosing environments.
If a binding is found, its value is changed to <code class="code">value</code>.  Otherwise,
a new binding with the specified value is created in the global
environment.  This corresponds to <code class="code">assign(symbol, value, envir =
rho, inherits = TRUE)</code>.
</p>
<p>At times it may also be useful to create a new environment frame in C code.
<code class="code">R_NewEnv</code> is a C version of the R function <code class="code">new.env</code>:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">SEXP R_NewEnv(SEXP enclos, int hash, int size)
</pre></div></div>
<a class="index-entry-id" id="index-R_005fNewEnv"></a>

<hr>
</div>
<div class="subsection-level-extent" id="Some-convenience-functions">
<div class="nav-panel">
<p>
Next: <a href="#Named-objects-and-copying" accesskey="n" rel="next">Named objects and copying</a>, Previous: <a href="#Finding-and-setting-variables" accesskey="p" rel="prev">Finding and setting variables</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Some-convenience-functions-1"><span>5.9.9 Some convenience functions<a class="copiable-link" href="#Some-convenience-functions-1"> &para;</a></span></h4>

<p>Some operations are done so frequently that there are convenience
functions to handle them. (All these are provided <em class="emph">via</em> the header
file <samp class="file">Rinternals.h</samp>.)
</p>
<p>Suppose we wanted to pass a single logical argument
<code class="code">ignore_quotes</code>: we could use
</p>
<div class="example">
<pre class="example-preformatted">    int ign = asLogical(ignore_quotes);
    if(ign == NA_LOGICAL) error(&quot;'ignore_quotes' must be TRUE or FALSE&quot;);
</pre></div>

<p>which will do any coercion needed (at least from a vector argument), and
return <code class="code">NA_LOGICAL</code> if the value passed was <code class="code">NA</code> or coercion
failed.  There are also <code class="code">asInteger</code>, <code class="code">asReal</code> and
<code class="code">asComplex</code>.  The function <code class="code">asChar</code> returns a <code class="code">CHARSXP</code>.
All of these functions ignore any elements of an input vector after the
first.
<a class="index-entry-id" id="index-asInteger"></a>
<a class="index-entry-id" id="index-asLogical"></a>
<a class="index-entry-id" id="index-asReal"></a>
<a class="index-entry-id" id="index-asComplex"></a>
<a class="index-entry-id" id="index-asChar"></a>
</p>
<p>To return a length-one real vector we can use
</p>
<div class="example">
<pre class="example-preformatted">    double x;

    ...
    return ScalarReal(x);
</pre></div>

<p>and there are versions of this for all the atomic vector types (those for
a length-one character vector being <code class="code">ScalarString</code> with argument a
<code class="code">CHARSXP</code> and <code class="code">mkString</code> with argument <code class="code">const char *</code>).
</p>
<a class="index-entry-id" id="index-ScalarReal"></a>
<a class="index-entry-id" id="index-ScalarInteger"></a>
<a class="index-entry-id" id="index-ScalarLogical"></a>
<a class="index-entry-id" id="index-ScalarComplex"></a>
<a class="index-entry-id" id="index-ScalarRaw"></a>
<a class="index-entry-id" id="index-ScalarString"></a>
<a class="index-entry-id" id="index-mkString"></a>
<div class="example">
<div class="group"><pre class="example-preformatted">SEXP ScalarReal(double);
SEXP ScalarInteger(int);
SEXP ScalarLogical(int)
SEXP ScalarRaw(Rbyte);
SEXP ScalarComplex(Rcomplex);
SEXP ScalarString(SEXP);
SEXP mkString(const char *);
</pre></div></div>

<p>Some of the <code class="code">is<var class="var">XXXX</var></code> functions differ from their apparent
R-level counterparts: for example <code class="code">isVector</code> is true for any
atomic vector type (<code class="code">isVectorAtomic</code>) and for lists and expressions
(<code class="code">isVectorList</code>) (with no check on attributes).  <code class="code">isMatrix</code> is
a test of a length-2 <code class="code">&quot;dim&quot;</code> attribute.
<a class="index-entry-id" id="index-isVector"></a>
<a class="index-entry-id" id="index-isVectorAtomic"></a>
<a class="index-entry-id" id="index-isVectorList"></a>
<a class="index-entry-id" id="index-isMatrix"></a>
<a class="index-entry-id" id="index-isPairList"></a>
<a class="index-entry-id" id="index-isPrimitive"></a>
<a class="index-entry-id" id="index-isTs"></a>
<a class="index-entry-id" id="index-isNumeric"></a>
<a class="index-entry-id" id="index-isArray"></a>
<a class="index-entry-id" id="index-isFactor"></a>
<a class="index-entry-id" id="index-isObject"></a>
<a class="index-entry-id" id="index-isFunction"></a>
<a class="index-entry-id" id="index-isLanguage"></a>
<a class="index-entry-id" id="index-isNewList"></a>
<a class="index-entry-id" id="index-isList"></a>
<a class="index-entry-id" id="index-isOrdered"></a>
<a class="index-entry-id" id="index-isUnordered"></a>
</p><div class="example">
<div class="group"><pre class="example-preformatted">Rboolean isVector(SEXP);
Rboolean isVectorAtomic(SEXP);
Rboolean isVectorList(SEXP);
Rboolean isMatrix(SEXP);
Rboolean isPairList(SEXP);
Rboolean isPrimitive(SEXP);
Rboolean isTs(SEXP);
Rboolean isNumeric(SEXP);
Rboolean isArray(SEXP);
Rboolean isFactor(SEXP);
Rboolean isObject(SEXP);
Rboolean isFunction(SEXP);
Rboolean isLanguage(SEXP);
Rboolean isNewList(SEXP);
Rboolean isList(SEXP);
Rboolean isOrdered(SEXP);
Rboolean isUnordered(SEXP);
</pre></div></div>

<p>There are a series of small macros/functions to help construct pairlists
and language objects (whose internal structures just differ by
<code class="code">SEXPTYPE</code>).  Function <code class="code">CONS(u, v)</code> is the basic building
block: it constructs a pairlist from <code class="code">u</code> followed by <code class="code">v</code>
(which is a pairlist or <code class="code">R_NilValue</code>).  <code class="code">LCONS</code> is a variant
that constructs a language object.  Functions <code class="code">list1</code> to
<code class="code">list6</code> construct a pairlist from one to six items, and
<code class="code">lang1</code> to <code class="code">lang6</code> do the same for a language object (a
function to call plus zero to five arguments).
<a class="index-entry-id" id="index-CONS"></a>
<a class="index-entry-id" id="index-cons"></a>
<a class="index-entry-id" id="index-list1"></a>
<a class="index-entry-id" id="index-list2"></a>
<a class="index-entry-id" id="index-list3"></a>
<a class="index-entry-id" id="index-list4"></a>
<a class="index-entry-id" id="index-list5"></a>
<a class="index-entry-id" id="index-list6"></a>
<a class="index-entry-id" id="index-LCONS"></a>
<a class="index-entry-id" id="index-lcons"></a>
<a class="index-entry-id" id="index-lang1"></a>
<a class="index-entry-id" id="index-lang2"></a>
<a class="index-entry-id" id="index-lang3"></a>
<a class="index-entry-id" id="index-lang4"></a>
<a class="index-entry-id" id="index-lang5"></a>
<a class="index-entry-id" id="index-lang6"></a>
Functions <code class="code">elt</code> and <code class="code">lastElt</code> find the <var class="var">i</var>-th element and
the last element of a pairlist, and <code class="code">nthcdr</code> returns a pointer to
the <var class="var">n</var>-th position in the pairlist (whose <code class="code">CAR</code> is the
<var class="var">n</var>-th item).
<a class="index-entry-id" id="index-elt"></a>
<a class="index-entry-id" id="index-lastElt"></a>
<a class="index-entry-id" id="index-nthcdr"></a>
</p>
<p>Functions <code class="code">str2type</code> and <code class="code">type2str</code> map R
length-one character strings to and from <code class="code">SEXPTYPE</code> numbers, and
<code class="code">type2char</code> maps numbers to C character strings.
<a class="index-entry-id" id="index-str2type"></a>
<a class="index-entry-id" id="index-type2str"></a>
<a class="index-entry-id" id="index-type2char"></a>
</p>

<ul class="mini-toc">
<li><a href="#Semi_002dinternal-convenience-functions" accesskey="1">Semi-internal convenience functions</a></li>
</ul>
<hr>
<div class="subsubsection-level-extent" id="Semi_002dinternal-convenience-functions">
<div class="nav-panel">
<p>
Previous: <a href="#Some-convenience-functions" accesskey="p" rel="prev">Some convenience functions</a>, Up: <a href="#Some-convenience-functions" accesskey="u" rel="up">Some convenience functions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsubsection" id="Semi_002dinternal-convenience-functions-1"><span>5.9.9.1 Semi-internal convenience functions<a class="copiable-link" href="#Semi_002dinternal-convenience-functions-1"> &para;</a></span></h4>

<p>There is quite a collection of functions that may be used in your C code
<em class="emph">if</em> you are willing to adapt to rare &ldquo;API&rdquo; changes.
These typically contain &ldquo;workhorses&rdquo; of their R counterparts.
</p>
<p>Functions <code class="code">any_duplicated</code> and <code class="code">any_duplicated3</code> are fast
versions of R&rsquo;s <code class="code">any(duplicated(.))</code>.
<a class="index-entry-id" id="index-any_005fduplicated"></a>
<a class="index-entry-id" id="index-any_005fduplicated3"></a>
</p>
<p>Function <code class="code">R_compute_identical</code> corresponds to R&rsquo;s <code class="code">identical</code> function.
<a class="index-entry-id" id="index-R_005fcompute_005fidentical"></a>
</p>
<hr>
</div>
</div>
<div class="subsection-level-extent" id="Named-objects-and-copying">
<div class="nav-panel">
<p>
Previous: <a href="#Some-convenience-functions" accesskey="p" rel="prev">Some convenience functions</a>, Up: <a href="#Handling-R-objects-in-C" accesskey="u" rel="up">Handling R objects in C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Named-objects-and-copying-1"><span>5.9.10 Named objects and copying<a class="copiable-link" href="#Named-objects-and-copying-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-duplicate"></a>
<a class="index-entry-id" id="index-Copying-objects"></a>

<p>[The <code class="code">NAMED</code> mechanism has been replaced by reference counting.]
</p>
<p>When assignments are done in R such as
</p>
<div class="example">
<pre class="example-preformatted">x &lt;- 1:10
y &lt;- x
</pre></div>

<p>the named object is not necessarily copied, so after those two
assignments <code class="code">y</code> and <code class="code">x</code> are bound to the same <code class="code">SEXPREC</code>
(the structure a <code class="code">SEXP</code> points to).  This means that any code which
alters one of them has to make a copy before modifying the copy if the
usual R semantics are to apply.  Note that whereas <code class="code">.C</code> and
<code class="code">.Fortran</code> do copy their arguments (unless the dangerous <code class="code">dup
= FALSE</code> is used), <code class="code">.Call</code> and <code class="code">.External</code> do not.  So
<code class="code">duplicate</code> is commonly called on arguments to <code class="code">.Call</code> before
modifying them.
</p>
<p>However, at least some of this copying is unneeded.  In the first
assignment shown, <code class="code">x &lt;- 1:10</code>, R first creates an object with
value <code class="code">1:10</code> and then assigns it to <code class="code">x</code> but if <code class="code">x</code> is
modified no copy is necessary as the temporary object with value
<code class="code">1:10</code> cannot be referred to again.  R distinguishes between
named and unnamed objects <em class="emph">via</em> a field in a <code class="code">SEXPREC</code> that
can be accessed <em class="emph">via</em> the macros <code class="code">NAMED</code> and <code class="code">SET_NAMED</code>.  This
can take values
</p>
<dl class="table">
<dt><code class="code">0</code></dt>
<dd><p>The object is not bound to any symbol
</p></dd>
<dt><code class="code">1</code></dt>
<dd><p>The object has been bound to exactly one symbol
</p></dd>
<dt><code class="code">&gt;= 2</code></dt>
<dd><p>The object has potentially been bound to two or more symbols, and one
should act as if another variable is currently bound to this value.
The maximal value is <code class="code">NAMEDMAX</code>.
</p></dd>
</dl>

<p>Note the past tenses: R does not do currently do full reference
counting and there may currently be fewer bindings.
</p>
<p>It is safe to modify the value of any <code class="code">SEXP</code> for which
<code class="code">NAMED(foo)</code> is zero, and if <code class="code">NAMED(foo)</code> is two or more, the
value should be duplicated (<em class="emph">via</em> a call to <code class="code">duplicate</code>)
before any modification.  Note that it is the responsibility of the
author of the code making the modification to do the duplication, even
if it is <code class="code">x</code> whose value is being modified after <code class="code">y &lt;- x</code>.
</p>
<p>The case <code class="code">NAMED(foo) == 1</code> allows some optimization, but it can be
ignored (and duplication done whenever <code class="code">NAMED(foo) &gt; 0</code>).  (This
optimization is not currently usable in user code.)  It is intended
for use within replacement functions.  Suppose we used
</p>
<div class="example">
<pre class="example-preformatted">x &lt;- 1:10
foo(x) &lt;- 3
</pre></div>

<p>which is computed as
</p>
<div class="example">
<pre class="example-preformatted">x &lt;- 1:10
x &lt;- &quot;foo&lt;-&quot;(x, 3)
</pre></div>

<p>Then inside <code class="code">&quot;foo&lt;-&quot;</code> the object pointing to the current value of
<code class="code">x</code> will have <code class="code">NAMED(foo)</code> as one, and it would be safe to
modify it as the only symbol bound to it is <code class="code">x</code> and that will be
rebound immediately.  (Provided the remaining code in <code class="code">&quot;foo&lt;-&quot;</code>
make no reference to <code class="code">x</code>, and no one is going to attempt a direct
call such as <code class="code">y &lt;- &quot;foo&lt;-&quot;(x)</code>.)
</p>
<p>This mechanism was replaced in R 4.0.0. To
support future changes, package code should use the macros
<code class="code">MAYBE_REFERENCED</code>, <code class="code">MAYBE_SHARED</code>, and
<code class="code">MARK_NOT_MUTABLE</code>. These currently correspond to
<a class="index-entry-id" id="index-MAYBE_005fREFERENCED"></a>
<a class="index-entry-id" id="index-MAYBE_005fSHARED"></a>
<a class="index-entry-id" id="index-MARK_005fNOT_005fMUTABLE"></a>
</p>
<dl class="table">
<dt><code class="code">MAYBE_REFERENCED(x)</code></dt>
<dd><p><code class="code">NAMED(x) &gt; 0</code>
</p></dd>
<dt><code class="code">MAYBE_SHARED(x)</code></dt>
<dd><p><code class="code">NAMED(x) &gt; 1</code>
</p></dd>
<dt><code class="code">MARK_NOT_MUTABLE(x)</code></dt>
<dd><p><code class="code">SET_NAMED(x, NAMEDMAX)</code>
</p></dd>
</dl>


<hr>
</div>
</div>
<div class="section-level-extent" id="Interface-functions-_002eCall-and-_002eExternal">
<div class="nav-panel">
<p>
Next: <a href="#Evaluating-R-expressions-from-C" accesskey="n" rel="next">Evaluating R expressions from C</a>, Previous: <a href="#Handling-R-objects-in-C" accesskey="p" rel="prev">Handling R objects in C</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Interface-functions-_002eCall-and-_002eExternal-1"><span>5.10 Interface functions <code class="code">.Call</code> and <code class="code">.External</code><a class="copiable-link" href="#Interface-functions-_002eCall-and-_002eExternal-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Interfaces-to-compiled-code-1"></a>

<p>In this section we consider the details of the R/C interfaces.
</p>
<p>These two interfaces have almost the same functionality. <code class="code">.Call</code> is
based on the interface of the same name in S version 4, and
<code class="code">.External</code> is based on R&rsquo;s <code class="code">.Internal</code>.  <code class="code">.External</code>
is more complex but allows a variable number of arguments.
</p>

<ul class="mini-toc">
<li><a href="#Calling-_002eCall" accesskey="1">Calling <code class="code">.Call</code></a></li>
<li><a href="#Calling-_002eExternal" accesskey="2">Calling <code class="code">.External</code></a></li>
<li><a href="#Missing-and-special-values" accesskey="3">Missing and special values</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Calling-_002eCall">
<div class="nav-panel">
<p>
Next: <a href="#Calling-_002eExternal" accesskey="n" rel="next">Calling <code class="code">.External</code></a>, Previous: <a href="#Interface-functions-_002eCall-and-_002eExternal" accesskey="p" rel="prev">Interface functions <code class="code">.Call</code> and <code class="code">.External</code></a>, Up: <a href="#Interface-functions-_002eCall-and-_002eExternal" accesskey="u" rel="up">Interface functions <code class="code">.Call</code> and <code class="code">.External</code></a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Calling-_002eCall-1"><span>5.10.1 Calling <code class="code">.Call</code><a class="copiable-link" href="#Calling-_002eCall-1"> &para;</a></span></h4>

<a class="index-entry-id" id="index-_002eCall-1"></a>

<p>Let us convert our finite convolution example to use <code class="code">.Call</code>.  The
calling function in R is
</p>
<div class="example">
<pre class="example-preformatted">conv &lt;- function(a, b) .Call(&quot;convolve2&quot;, a, b)
</pre></div>

<p>which could hardly be simpler, but as we shall see all the type
coercion is transferred to the C code, which is
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt;
#include &lt;Rinternals.h&gt;

SEXP convolve2(SEXP a, SEXP b)
{
    int na, nb, nab;
    double *xa, *xb, *xab;
    SEXP ab;

    a = PROTECT(coerceVector(a, REALSXP));
    b = PROTECT(coerceVector(b, REALSXP));
    na = length(a); nb = length(b); nab = na + nb - 1;
    ab = PROTECT(allocVector(REALSXP, nab));
    xa = REAL(a); xb = REAL(b); xab = REAL(ab);
    for(int i = 0; i &lt; nab; i++) xab[i] = 0.0;
    for(int i = 0; i &lt; na; i++)
        for(int j = 0; j &lt; nb; j++) xab[i + j] += xa[i] * xb[j];
    UNPROTECT(3);
    return ab;
}
</pre></div></div>

<hr>
</div>
<div class="subsection-level-extent" id="Calling-_002eExternal">
<div class="nav-panel">
<p>
Next: <a href="#Missing-and-special-values" accesskey="n" rel="next">Missing and special values</a>, Previous: <a href="#Calling-_002eCall" accesskey="p" rel="prev">Calling <code class="code">.Call</code></a>, Up: <a href="#Interface-functions-_002eCall-and-_002eExternal" accesskey="u" rel="up">Interface functions <code class="code">.Call</code> and <code class="code">.External</code></a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Calling-_002eExternal-1"><span>5.10.2 Calling <code class="code">.External</code><a class="copiable-link" href="#Calling-_002eExternal-1"> &para;</a></span></h4>

<a class="index-entry-id" id="index-_002eExternal-1"></a>

<p>We can use the same example to illustrate <code class="code">.External</code>.  The R
code changes only by replacing <code class="code">.Call</code> by <code class="code">.External</code>
</p>
<div class="example">
<pre class="example-preformatted">conv &lt;- function(a, b) .External(&quot;convolveE&quot;, a, b)
</pre></div>

<p>but the main change is how the arguments are passed to the C code, this
time as a single SEXP.  The only change to the C code is how we handle
the arguments.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt;
#include &lt;Rinternals.h&gt;

SEXP convolveE(SEXP args)
{
    int i, j, na, nb, nab;
    double *xa, *xb, *xab;
    SEXP a, b, ab;

    a = PROTECT(coerceVector(CADR(args), REALSXP));
    b = PROTECT(coerceVector(CADDR(args), REALSXP));
    ...
}
</pre></div></div>

<p>Once again we do not need to protect the arguments, as in the R side
of the interface they are objects that are already in use.  The macros
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">  first = CADR(args);
  second = CADDR(args);
  third = CADDDR(args);
  fourth = CAD4R(args);
  fifth  = CAD5R(args);
</pre></div></div>
<a class="index-entry-id" id="index-CADR"></a>
<a class="index-entry-id" id="index-CADDR"></a>
<a class="index-entry-id" id="index-CADDDR"></a>
<a class="index-entry-id" id="index-CAD4R"></a>
<a class="index-entry-id" id="index-CAD5R"></a>

<p>provide convenient ways to access the first four arguments.  More
generally we can use the
<a class="index-entry-id" id="index-CAR"></a>
<a class="index-entry-id" id="index-CDR"></a>
<code class="code">CDR</code> and <code class="code">CAR</code> macros as in
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">  args = CDR(args); a = CAR(args);
  args = CDR(args); b = CAR(args);
</pre></div></div>

<p>which clearly allows us to extract an unlimited number of arguments
(whereas <code class="code">.Call</code> has a limit, albeit at 65 not a small one).
</p>
<p>More usefully, the <code class="code">.External</code> interface provides an easy way to
handle calls with a variable number of arguments, as <code class="code">length(args)</code>
will give the number of arguments supplied (of which the first is
ignored).  We may need to know the names (&lsquo;tags&rsquo;) given to the actual
arguments, which we can by using the <code class="code">TAG</code> macro and using
something like the following example, that prints the names and the first
value of its arguments if they are vector types.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">SEXP showArgs(SEXP args)
{
    args = CDR(args); /* skip ‘name’ */
    for(int i = 0; args != R_NilValue; i++, args = CDR(args)) {
        const char *name =
            isNull(TAG(args)) ? &quot;&quot; : CHAR(PRINTNAME(TAG(args)));
        SEXP el = CAR(args);
        if (length(el) == 0) {
            Rprintf(&quot;[%d] ‘%s’ R type, length 0\n&quot;, i+1, name);
           continue;
        }
</pre></div><div class="group"><pre class="example-preformatted">        switch(TYPEOF(el)) {
        case REALSXP:
            Rprintf(&quot;[%d] ‘%s’ %f\n&quot;, i+1, name, REAL(el)[0]);
            break;
</pre></div><div class="group"><pre class="example-preformatted">        case LGLSXP:
        case INTSXP:
            Rprintf(&quot;[%d] ‘%s’ %d\n&quot;, i+1, name, INTEGER(el)[0]);
            break;
</pre></div><div class="group"><pre class="example-preformatted">        case CPLXSXP:
        {
            Rcomplex cpl = COMPLEX(el)[0];
            Rprintf(&quot;[%d] ‘%s’ %f + %fi\n&quot;, i+1, name, cpl.r, cpl.i);
        }
            break;
</pre></div><div class="group"><pre class="example-preformatted">        case STRSXP:
            Rprintf(&quot;[%d] ‘%s’ %s\n&quot;, i+1, name,
                   CHAR(STRING_ELT(el, 0)));
           break;
</pre></div><div class="group"><pre class="example-preformatted">        default:
            Rprintf(&quot;[%d] ‘%s’ R type\n&quot;, i+1, name);
       }
    }
    return R_NilValue;
}
</pre></div></div>
<a class="index-entry-id" id="index-PRINTNAME"></a>
<a class="index-entry-id" id="index-TYPEOF"></a>
<a class="index-entry-id" id="index-TAG"></a>

<p>This can be called by the wrapper function
</p>
<div class="example">
<pre class="example-preformatted">showArgs &lt;- function(...) invisible(.External(&quot;showArgs&quot;, ...))
</pre></div>

<p>Note that this style of programming is convenient but not necessary, as
an alternative style is
</p>
<div class="example">
<pre class="example-preformatted">showArgs1 &lt;- function(...) invisible(.Call(&quot;showArgs1&quot;, list(...)))
</pre></div>

<p>The (very similar) C code is in the scripts.
</p>
<p>Additional functions for accessing pairlist components are <code class="code">CAAR</code>,
<code class="code">CDAR</code>, <code class="code">CDDR</code>, and <code class="code">CDDDR</code>.
<a class="index-entry-id" id="index-CAAR"></a>
<a class="index-entry-id" id="index-CDAR"></a>
<a class="index-entry-id" id="index-CDDR"></a>
<a class="index-entry-id" id="index-CDDDR"></a>
These components can be modified with <code class="code">SETCAR</code>, <code class="code">SETCDR</code>,
<code class="code">SETCADR</code>, <code class="code">SETCADDR</code>, <code class="code">SETCADDDR</code>, and <code class="code">SETCAD4R</code>.
<a class="index-entry-id" id="index-SETCAR"></a>
<a class="index-entry-id" id="index-SETCDR"></a>
<a class="index-entry-id" id="index-SETCADR"></a>
<a class="index-entry-id" id="index-SETCADDR"></a>
<a class="index-entry-id" id="index-SETCADDDR"></a>
<a class="index-entry-id" id="index-SETCAD4R"></a>
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Missing-and-special-values">
<div class="nav-panel">
<p>
Previous: <a href="#Calling-_002eExternal" accesskey="p" rel="prev">Calling <code class="code">.External</code></a>, Up: <a href="#Interface-functions-_002eCall-and-_002eExternal" accesskey="u" rel="up">Interface functions <code class="code">.Call</code> and <code class="code">.External</code></a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Missing-and-special-values-1"><span>5.10.3 Missing and special values<a class="copiable-link" href="#Missing-and-special-values-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Missing-values"></a>
<a class="index-entry-id" id="index-IEEE-special-values"></a>

<p>One piece of error-checking the <code class="code">.C</code> call does (unless <code class="code">NAOK</code>
is true) is to check for missing (<code class="code">NA</code>) and <abbr class="acronym">IEEE</abbr> special
values (<code class="code">Inf</code>, <code class="code">-Inf</code> and <code class="code">NaN</code>) and give an error if any
are found.  With the <code class="code">.Call</code> interface these will be passed to our
code.  In this example the special values are no problem, as
<abbr class="acronym">IEC</abbr>&nbsp;60559 arithmetic will handle them correctly.  In the current
implementation this is also true of <code class="code">NA</code> as it is a type of
<code class="code">NaN</code>, but it is unwise to rely on such details.  Thus we will
re-write the code to handle <code class="code">NA</code>s using macros defined in
<samp class="file">R_ext/Arith.h</samp> included by <samp class="file">R.h</samp>.
</p>
<p>The code changes are the same in any of the versions of <code class="code">convolve2</code>
or <code class="code">convolveE</code>:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">    ...
  for(int i = 0; i &lt; na; i++)
    for(int j = 0; j &lt; nb; j++)
        if(ISNA(xa[i]) || ISNA(xb[j]) || ISNA(xab[i + j]))
            xab[i + j] = NA_REAL;
        else
            xab[i + j] += xa[i] * xb[j];
    ...
</pre></div></div>

<a class="index-entry-id" id="index-ISNA"></a>
<a class="index-entry-id" id="index-ISNAN"></a>

<p>Note that the <code class="code">ISNA</code> macro, and the similar macros <code class="code">ISNAN</code>
(which checks for <code class="code">NaN</code> or <code class="code">NA</code>) and <code class="code">R_FINITE</code> (which is
false for <code class="code">NA</code> and all the special values), only apply to numeric
values of type <code class="code">double</code>.  Missingness of integers, logicals and
character strings can be tested by equality to the constants
<code class="code">NA_INTEGER</code>, <code class="code">NA_LOGICAL</code> and <code class="code">NA_STRING</code>.  These and
<code class="code">NA_REAL</code> can be used to set elements of R vectors to <code class="code">NA</code>.
</p>
<p>The constants <code class="code">R_NaN</code>, <code class="code">R_PosInf</code> and <code class="code">R_NegInf</code> can be
used to set <code class="code">double</code>s to the special values.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Evaluating-R-expressions-from-C">
<div class="nav-panel">
<p>
Next: <a href="#Parsing-R-code-from-C" accesskey="n" rel="next">Parsing R code from C</a>, Previous: <a href="#Interface-functions-_002eCall-and-_002eExternal" accesskey="p" rel="prev">Interface functions <code class="code">.Call</code> and <code class="code">.External</code></a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Evaluating-R-expressions-from-C-1"><span>5.11 Evaluating R expressions from C<a class="copiable-link" href="#Evaluating-R-expressions-from-C-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Evaluating-R-expressions-from-C"></a>

<p>The main function we will use is
</p>
<div class="example">
<pre class="example-preformatted">SEXP eval(SEXP expr, SEXP rho);
</pre></div>
<a class="index-entry-id" id="index-eval"></a>

<p>the equivalent of the interpreted R code <code class="code">eval(expr, envir =
rho)</code> (so <code class="code">rho</code> must be an environment), although we can also make
use of <code class="code">findVar</code>, <code class="code">defineVar</code> and <code class="code">findFun</code> (which
restricts the search to functions).
<a class="index-entry-id" id="index-findFun"></a>
</p>
<p>To see how this might be applied, here is a simplified internal version
of <code class="code">lapply</code> for expressions, used as
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">a &lt;- list(a = 1:5, b = rnorm(10), test = runif(100))
.Call(&quot;lapply&quot;, a, quote(sum(x)), new.env())
</pre></div></div>

<p>with C code
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">SEXP lapply(SEXP list, SEXP expr, SEXP rho)
{
    int n = length(list);
    SEXP ans;

    if(!isNewList(list)) error(&quot;'list' must be a list&quot;);
    if(!isEnvironment(rho)) error(&quot;'rho' should be an environment&quot;);
    ans = PROTECT(allocVector(VECSXP, n));
    for(int i = 0; i &lt; n; i++) {
        defineVar(install(&quot;x&quot;), VECTOR_ELT(list, i), rho);
        SET_VECTOR_ELT(ans, i, eval(expr, rho));
    }
    setAttrib(ans, R_NamesSymbol, getAttrib(list, R_NamesSymbol));
    UNPROTECT(1);
    return ans;
}
</pre></div></div>

<p>It would be closer to <code class="code">lapply</code> if we could pass in a function
rather than an expression.  One way to do this is <em class="emph">via</em> interpreted
R code as in the next example, but it is possible (if somewhat
obscure) to do this in C code.  The following is based on the code in
<samp class="file">src/main/optimize.c</samp>.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">SEXP lapply2(SEXP list, SEXP fn, SEXP rho)
{
    int n = length(list);
    SEXP R_fcall, ans;

    if(!isNewList(list)) error(&quot;'list' must be a list&quot;);
    if(!isFunction(fn)) error(&quot;'fn' must be a function&quot;);
    if(!isEnvironment(rho)) error(&quot;'rho' should be an environment&quot;);
    R_fcall = PROTECT(lang2(fn, R_NilValue));
    ans = PROTECT(allocVector(VECSXP, n));
    for(int i = 0; i &lt; n; i++) {
        SETCADR(R_fcall, VECTOR_ELT(list, i));
        SET_VECTOR_ELT(ans, i, eval(R_fcall, rho));
    }
    setAttrib(ans, R_NamesSymbol, getAttrib(list, R_NamesSymbol));
    UNPROTECT(2);
    return ans;
}
</pre></div></div>

<p>used by
</p>
<div class="example">
<pre class="example-preformatted">.Call(&quot;lapply2&quot;, a, sum, new.env())
</pre></div>

<p>Function <code class="code">lang2</code> creates an executable pairlist of two elements, but
this will only be clear to those with a knowledge of a LISP-like
language.
</p>
<p>As a more comprehensive example of constructing an R call in C code
and evaluating, consider the following fragment of
<code class="code">printAttributes</code> in <samp class="file">src/main/print.c</samp>.
</p>
<div class="example">
<pre class="example-preformatted">    /* Need to construct a call to
       print(CAR(a), digits=digits)
       based on the R_print structure, then eval(call, env).
       See do_docall for the template for this sort of thing.
    */
    SEXP s, t;
    t = s = PROTECT(allocList(3));
    SET_TYPEOF(s, LANGSXP);
    SETCAR(t, install(&quot;print&quot;)); t = CDR(t);
    SETCAR(t,  CAR(a)); t = CDR(t);
    SETCAR(t, ScalarInteger(digits));
    SET_TAG(t, install(&quot;digits&quot;));
    eval(s, env);
    UNPROTECT(1);
</pre></div>
<a class="index-entry-id" id="index-allocList"></a>
<a class="index-entry-id" id="index-SET_005fTAG"></a>

<p>At this point <code class="code">CAR(a)</code> is the R object to be printed, the
current attribute.  There are three steps: the call is constructed as
a pairlist of length 3, the list is filled in, and the expression
represented by the pairlist is evaluated.
</p>
<p>A pairlist is quite distinct from a generic vector list, the only
user-visible form of list in R.  A pairlist is a linked list (with
<code class="code">CDR(t)</code> computing the next entry), with items (accessed by
<code class="code">CAR(t)</code>) and names or tags (set by <code class="code">SET_TAG</code>).  In this call
there are to be three items, a symbol (pointing to the function to be
called) and two argument values, the first unnamed and the second named.
Setting the type to <code class="code">LANGSXP</code> makes this a call which can be evaluated.
</p>
<p>Customarily, the evaluation environment is passed from the calling
R code (see <code class="code">rho</code> above). In special cases it is possible that
the C code may need to obtain the current evaluation environment
which can be done via <code class="code">R_GetCurrentEnv()</code> function.
<a class="index-entry-id" id="index-R_005fGetCurrentEnv"></a>
</p>

<ul class="mini-toc">
<li><a href="#Zero_002dfinding" accesskey="1">Zero-finding</a></li>
<li><a href="#Calculating-numerical-derivatives" accesskey="2">Calculating numerical derivatives</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Zero_002dfinding">
<div class="nav-panel">
<p>
Next: <a href="#Calculating-numerical-derivatives" accesskey="n" rel="next">Calculating numerical derivatives</a>, Previous: <a href="#Evaluating-R-expressions-from-C" accesskey="p" rel="prev">Evaluating R expressions from C</a>, Up: <a href="#Evaluating-R-expressions-from-C" accesskey="u" rel="up">Evaluating R expressions from C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Zero_002dfinding-1"><span>5.11.1 Zero-finding<a class="copiable-link" href="#Zero_002dfinding-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Zero_002dfinding"></a>

<p>In this section we re-work the example of Becker, Chambers &amp;
Wilks (1988, pp.~205&ndash;10) on finding a zero of a univariate
function.  The R code and an example are
</p>
<div class="example">
<pre class="example-preformatted">zero &lt;- function(f, guesses, tol = 1e-7) {
    f.check &lt;- function(x) {
        x &lt;- f(x)
        if(!is.numeric(x)) stop(&quot;Need a numeric result&quot;)
        as.double(x)
    }
    .Call(&quot;zero&quot;, body(f.check), as.double(guesses), as.double(tol),
          new.env())
}

cube1 &lt;- function(x) (x^2 + 1) * (x - 1.5)
zero(cube1, c(0, 5))
</pre></div>

<p>where this time we do the coercion and error-checking in the R code.
The C code is
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">SEXP mkans(double x)
{
    // no need for PROTECT() here, as REAL(.) does not allocate:
    SEXP ans = allocVector(REALSXP, 1);
    REAL(ans)[0] = x;
    return ans;
}
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">double feval(double x, SEXP f, SEXP rho)
{
    // a version with (too) much PROTECT()ion .. &quot;better safe than sorry&quot;
    SEXP symbol, value;
    PROTECT(symbol = install(&quot;x&quot;));
    PROTECT(value = mkans(x));
    defineVar(symbol, value, rho);
    UNPROTECT(2);
    return(REAL(eval(f, rho))[0]);
}
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">SEXP zero(SEXP f, SEXP guesses, SEXP stol, SEXP rho)
{
    double x0 = REAL(guesses)[0], x1 = REAL(guesses)[1],
           tol = REAL(stol)[0];
    double f0, f1, fc, xc;
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">    if(tol &lt;= 0.0) error(&quot;non-positive tol value&quot;);
    f0 = feval(x0, f, rho); f1 = feval(x1, f, rho);
    if(f0 == 0.0) return mkans(x0);
    if(f1 == 0.0) return mkans(x1);
    if(f0*f1 &gt; 0.0) error(&quot;x[0] and x[1] have the same sign&quot;);
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">    for(;;) {
        xc = 0.5*(x0+x1);
        if(fabs(x0-x1) &lt; tol) return  mkans(xc);
        fc = feval(xc, f, rho);
        if(fc == 0) return  mkans(xc);
        if(f0*fc &gt; 0.0) {
            x0 = xc; f0 = fc;
        } else {
            x1 = xc; f1 = fc;
        }
    }
}
</pre></div></div>

<hr>
</div>
<div class="subsection-level-extent" id="Calculating-numerical-derivatives">
<div class="nav-panel">
<p>
Previous: <a href="#Zero_002dfinding" accesskey="p" rel="prev">Zero-finding</a>, Up: <a href="#Evaluating-R-expressions-from-C" accesskey="u" rel="up">Evaluating R expressions from C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Calculating-numerical-derivatives-1"><span>5.11.2 Calculating numerical derivatives<a class="copiable-link" href="#Calculating-numerical-derivatives-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Numerical-derivatives"></a>

<p>We will use a longer example (by Saikat DebRoy) to illustrate the use of
evaluation and <code class="code">.External</code>.  This calculates numerical derivatives,
something that could be done as effectively in interpreted R code but
may be needed as part of a larger C calculation.
</p>
<p>An interpreted R version and an example are
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">numeric.deriv &lt;- function(expr, theta, rho=sys.frame(sys.parent()))
{
    eps &lt;- sqrt(.Machine$double.eps)
    ans &lt;- eval(substitute(expr), rho)
    grad &lt;- matrix(, length(ans), length(theta),
                   dimnames=list(NULL, theta))
    for (i in seq_along(theta)) {
        old &lt;- get(theta[i], envir=rho)
        delta &lt;- eps * max(1, abs(old))
        assign(theta[i], old+delta, envir=rho)
        ans1 &lt;- eval(substitute(expr), rho)
        assign(theta[i], old, envir=rho)
        grad[, i] &lt;- (ans1 - ans)/delta
    }
    attr(ans, &quot;gradient&quot;) &lt;- grad
    ans
}
omega &lt;- 1:5; x &lt;- 1; y &lt;- 2
numeric.deriv(sin(omega*x*y), c(&quot;x&quot;, &quot;y&quot;))
</pre></div></div>

<p>where <code class="code">expr</code> is an expression, <code class="code">theta</code> a character vector of
variable names and <code class="code">rho</code> the environment to be used.
</p>
<p>For the compiled version the call from R will be
</p>
<div class="example">
<pre class="example-preformatted">.External(&quot;numeric_deriv&quot;, <var class="var">expr</var>, <var class="var">theta</var>, <var class="var">rho</var>)
</pre></div>

<p>with example usage
</p>
<div class="example">
<pre class="example-preformatted">.External(&quot;numeric_deriv&quot;, quote(sin(omega*x*y)),
          c(&quot;x&quot;, &quot;y&quot;), .GlobalEnv)
</pre></div>

<p>Note the need to quote the expression to stop it being evaluated in the
caller.
</p>
<p>Here is the complete C code which we will explain section by section.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt; 
#include &lt;Rinternals.h&gt;
#include &lt;float.h&gt; /* for DBL_EPSILON */

SEXP numeric_deriv(SEXP args)
{
    SEXP theta, expr, rho, ans, ans1, gradient, par, dimnames;
    double tt, xx, delta, eps = sqrt(DBL_EPSILON), *rgr, *rans;
    int i, start;
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">    expr = CADR(args);
    if(!isString(theta = CADDR(args)))
        error(&quot;theta should be of type character&quot;);
    if(!isEnvironment(rho = CADDDR(args)))
        error(&quot;rho should be an environment&quot;);
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">    ans = PROTECT(coerceVector(eval(expr, rho), REALSXP));
    gradient = PROTECT(allocMatrix(REALSXP, LENGTH(ans), LENGTH(theta)));
    rgr = REAL(gradient); rans = REAL(ans);
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">    for(i = 0, start = 0; i &lt; LENGTH(theta); i++, start += LENGTH(ans)) {
        par = PROTECT(findVar(installChar(STRING_ELT(theta, i)), rho));
        tt = REAL(par)[0];
        xx = fabs(tt);
        delta = (xx &lt; 1) ? eps : xx*eps;
        REAL(par)[0] += delta;
        ans1 = PROTECT(coerceVector(eval(expr, rho), REALSXP));
        for(int j = 0; j &lt; LENGTH(ans); j++)
            rgr[j + start] = (REAL(ans1)[j] - rans[j])/delta;
        REAL(par)[0] = tt;
        UNPROTECT(2); /* par, ans1 */
    }
</pre></div><pre class="example-preformatted">

</pre><div class="group"><pre class="example-preformatted">    dimnames = PROTECT(allocVector(VECSXP, 2));
    SET_VECTOR_ELT(dimnames, 1,  theta);
    dimnamesgets(gradient, dimnames);
    setAttrib(ans, install(&quot;gradient&quot;), gradient);
    UNPROTECT(3); /* ans  gradient  dimnames */
    return ans;
}
</pre></div></div>

<p>The code to handle the arguments is
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">    expr = CADR(args);
    if(!isString(theta = CADDR(args)))
        error(&quot;theta should be of type character&quot;);
    if(!isEnvironment(rho = CADDDR(args)))
        error(&quot;rho should be an environment&quot;);
</pre></div></div>

<p>Note that we check for correct types of <code class="code">theta</code> and <code class="code">rho</code> but
do not check the type of <code class="code">expr</code>.  That is because <code class="code">eval</code> can
handle many types of R objects other than <code class="code">EXPRSXP</code>.  There is
no useful coercion we can do, so we stop with an error message if the
arguments are not of the correct mode.
</p>
<p>The first step in the code is to evaluate the expression in the
environment <code class="code">rho</code>, by
</p>
<div class="example">
<pre class="example-preformatted">    ans = PROTECT(coerceVector(eval(expr, rho), REALSXP));
</pre></div>

<p>We then allocate space for the calculated derivative by
</p>
<div class="example">
<pre class="example-preformatted">    gradient = PROTECT(allocMatrix(REALSXP, LENGTH(ans), LENGTH(theta)));
</pre></div>

<p>The first argument to <code class="code">allocMatrix</code> gives the <code class="code">SEXPTYPE</code> of
the matrix: here we want it to be <code class="code">REALSXP</code>.  The other two
arguments are the numbers of rows and columns.  (Note that <code class="code">LENGTH</code>
is intended to be used for vectors: <code class="code">length</code> is more generally
applicable.)
<a class="index-entry-id" id="index-allocMatrix"></a>
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">    for(i = 0, start = 0; i &lt; LENGTH(theta); i++, start += LENGTH(ans)) {
        par = PROTECT(findVar(installChar(STRING_ELT(theta, i)), rho));
</pre></div></div>

<p>Here, we are entering a for loop.  We loop through each of the
variables.  In the <code class="code">for</code> loop, we first create a symbol
corresponding to the <code class="code">i</code>-th element of the <code class="code">STRSXP</code>
<code class="code">theta</code>.  Here, <code class="code">STRING_ELT(theta, i)</code> accesses the
<code class="code">i</code>-th element of the <code class="code">STRSXP</code> <code class="code">theta</code>.  Macro
<code class="code">CHAR()</code> extracts the actual character
representation<a class="footnote" id="DOCF160" href="#FOOT160"><sup>160</sup></a> of it: it returns a pointer.  We then
install the name and use <code class="code">findVar</code> to find its value.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">        tt = REAL(par)[0];
        xx = fabs(tt);
        delta = (xx &lt; 1) ? eps : xx*eps;
        REAL(par)[0] += delta;
        ans1 = PROTECT(coerceVector(eval(expr, rho), REALSXP));
</pre></div></div>

<p>We first extract the real value of the parameter, then calculate
<code class="code">delta</code>, the increment to be used for approximating the numerical
derivative.  Then we change the value stored in <code class="code">par</code> (in
environment <code class="code">rho</code>) by <code class="code">delta</code> and evaluate <code class="code">expr</code> in
environment <code class="code">rho</code> again.  Because we are directly dealing with
original R memory locations here, R does the evaluation for the
changed parameter value.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">        for(int j = 0; j &lt; LENGTH(ans); j++)
            rgr[j + start] = (REAL(ans1)[j] - rans[j])/delta;
        REAL(par)[0] = tt;
        UNPROTECT(2);
    }
</pre></div></div>

<p>Now, we compute the <code class="code">i</code>-th column of the gradient matrix.  Note how
it is accessed: R stores matrices by column (like Fortran).
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">    dimnames = PROTECT(allocVector(VECSXP, 2));
    SET_VECTOR_ELT(dimnames, 1, theta);
    dimnamesgets(gradient, dimnames);
    setAttrib(ans, install(&quot;gradient&quot;), gradient);
    UNPROTECT(3);
    return ans;
}
</pre></div></div>

<p>First we add column names to the gradient matrix.  This is done by
allocating a list (a <code class="code">VECSXP</code>) whose first element, the row names,
is <code class="code">NULL</code> (the default) and the second element, the column names,
is set as <code class="code">theta</code>.  This list is then assigned as the attribute
having the symbol <code class="code">R_DimNamesSymbol</code>.  Finally we set the gradient
matrix as the gradient attribute of <code class="code">ans</code>, unprotect the remaining
protected locations and return the answer <code class="code">ans</code>.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Parsing-R-code-from-C">
<div class="nav-panel">
<p>
Next: <a href="#External-pointers-and-weak-references" accesskey="n" rel="next">External pointers and weak references</a>, Previous: <a href="#Evaluating-R-expressions-from-C" accesskey="p" rel="prev">Evaluating R expressions from C</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Parsing-R-code-from-C-1"><span>5.12 Parsing R code from C<a class="copiable-link" href="#Parsing-R-code-from-C-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Parsing-R-code-from-C"></a>

<p>Suppose an R extension want to accept an R expression from the
user and evaluate it.  The previous section covered evaluation, but the
expression will be entered as text and needs to be parsed first.  A
small part of R&rsquo;s parse interface is declared in header file
<samp class="file">R_ext/Parse.h</samp><a class="footnote" id="DOCF161" href="#FOOT161"><sup>161</sup></a>.
</p>
<p>An example of the usage can be found in the (example) Windows package
<strong class="strong">windlgs</strong> included in the R source tree.  The essential part is
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt;
#include &lt;Rinternals.h&gt;
#include &lt;R_ext/Parse.h&gt;

SEXP menu_ttest3()
{
    char cmd[256];
    SEXP cmdSexp, cmdexpr, ans = R_NilValue;
    ParseStatus status;
   ...
    if(done == 1) {
        cmdSexp = PROTECT(allocVector(STRSXP, 1));
        SET_STRING_ELT(cmdSexp, 0, mkChar(cmd));
        cmdexpr = PROTECT(R_ParseVector(cmdSexp, -1, &amp;status, R_NilValue));
        if (status != PARSE_OK) {
            UNPROTECT(2);
            error(&quot;invalid call %s&quot;, cmd);
        }
        /* Loop is needed here as EXPSEXP will be of length &gt; 1 */
        for(int i = 0; i &lt; length(cmdexpr); i++)
            ans = eval(VECTOR_ELT(cmdexpr, i), R_GlobalEnv);
        UNPROTECT(2);
    }
    return ans;
}
</pre></div></div>
<p>Note that a single line of text may give rise to more than one R
expression.
</p>
<a class="index-entry-id" id="index-R_005fParseVector"></a>
<p><code class="code">R_ParseVector</code> is essentially the code used to implement
<code class="code">parse(text=)</code> at R level.  The first argument is a character
vector (corresponding to <code class="code">text</code>) and the second the maximal
number of expressions to parse (corresponding to <code class="code">n</code>).  The third
argument is a pointer to a variable of an enumeration type, and it is
normal (as <code class="code">parse</code> does) to regard all values other than
<code class="code">PARSE_OK</code> as an error.  Other values which might be returned are
<code class="code">PARSE_INCOMPLETE</code> (an incomplete expression was found) and
<code class="code">PARSE_ERROR</code> (a syntax error), in both cases the value returned
being <code class="code">R_NilValue</code>. The fourth argument is a length one character
vector to be used as a filename in error messages, a <code class="code">srcfile</code>
object or the R <code class="code">NULL</code> object (as in the example above). If a
<code class="code">srcfile</code> object was used, a <code class="code">srcref</code> attribute would be
attached to the result, containing a list of <code class="code">srcref</code> objects of
the same length as the expression, to allow it to be echoed with its
original formatting.
</p>

<ul class="mini-toc">
<li><a href="#Accessing-source-references" accesskey="1">Accessing source references</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Accessing-source-references">
<div class="nav-panel">
<p>
Previous: <a href="#Parsing-R-code-from-C" accesskey="p" rel="prev">Parsing R code from C</a>, Up: <a href="#Parsing-R-code-from-C" accesskey="u" rel="up">Parsing R code from C</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Accessing-source-references-1"><span>5.12.1 Accessing source references<a class="copiable-link" href="#Accessing-source-references-1"> &para;</a></span></h4>

<p>The source references added by the parser are recorded by R&rsquo;s evaluator
as it evaluates code. Two functions
make these available to debuggers running C code:
<a class="index-entry-id" id="index-R_005fSrcref"></a>
<a class="index-entry-id" id="index-R_005fGetCurrentSrcref"></a>
<a class="index-entry-id" id="index-R_005fGetSrcFilename"></a>
</p>
<div class="example">
<pre class="example-preformatted">SEXP R_GetCurrentSrcref(int skip);
</pre></div>

<p>This function checks <code class="code">R_Srcref</code> and the current evaluation stack
for entries that contain source reference information.  The
<code class="code">skip</code> argument tells how many source references to skip before
returning the <code class="code">SEXP</code> of the <code class="code">srcref</code> object, counting from
the top of the stack.  If <code class="code">skip &lt; 0</code>, <code class="code">abs(skip)</code> locations
are counted up from the bottom of the stack. If too few or no source
references are found, <code class="code">NULL</code> is returned.
</p>
<div class="example">
<pre class="example-preformatted">SEXP R_GetSrcFilename(SEXP srcref);
</pre></div>

<p>This function extracts the filename from the source reference for
display, returning a length 1 character vector containing the
filename.  If no name is found, <code class="code">&quot;&quot;</code> is returned.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="External-pointers-and-weak-references">
<div class="nav-panel">
<p>
Next: <a href="#Vector-accessor-functions" accesskey="n" rel="next">Vector accessor functions</a>, Previous: <a href="#Parsing-R-code-from-C" accesskey="p" rel="prev">Parsing R code from C</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="External-pointers-and-weak-references-1"><span>5.13 External pointers and weak references<a class="copiable-link" href="#External-pointers-and-weak-references-1"> &para;</a></span></h3>

<p>The <code class="code">SEXPTYPE</code>s <code class="code">EXTPTRSXP</code> and <code class="code">WEAKREFSXP</code> can be
encountered at R level, but are created in C code.
</p>
<a class="index-entry-id" id="index-external-pointer"></a>
<p>External pointer <code class="code">SEXP</code>s are intended to handle references to C
structures such as &lsquo;handles&rsquo;, and are used for this purpose in package
<a class="url" href="https://CRAN.R-project.org/package=RODBC"><strong class="strong">RODBC</strong></a> for example.  They are unusual in their copying semantics in
that when an R object is copied, the external pointer object is not
duplicated.  (For this reason external pointers should only be used as
part of an object with normal semantics, for example an attribute or an
element of a list.)
</p>
<p>An external pointer is created by
</p>
<div class="example">
<pre class="example-preformatted">SEXP R_MakeExternalPtr(void *p, SEXP tag, SEXP prot);
</pre></div>
<a class="index-entry-id" id="index-R_005fMakeExternalPtr"></a>

<p>where <code class="code">p</code> is the pointer (and hence this cannot portably be a
function pointer), and <code class="code">tag</code> and <code class="code">prot</code> are references to
ordinary R objects which will remain in existence (be protected from
garbage collection) for the lifetime of the external pointer object.  A
useful convention is to use the <code class="code">tag</code> field for some form of type
identification and the <code class="code">prot</code> field for protecting the memory that
the external pointer represents, if that memory is allocated from the
R heap.  Both <code class="code">tag</code> and <code class="code">prot</code> can be <code class="code">R_NilValue</code>,
and often are.
</p>
<p>An alternative way to create an external pointer from a function pointer
is
</p>
<div class="example">
<pre class="example-preformatted">typedef void * (*R_DL_FUNC)();
SEXP R_MakeExternalPtrFn(R_DL_FUNC p, SEXP tag, SEXP prot);
</pre></div>
<a class="index-entry-id" id="index-R_005fMakeExternalPtrFn"></a>


<p>The elements of an external pointer can be accessed and set <em class="emph">via</em>
</p>
<div class="example">
<pre class="example-preformatted">void *R_ExternalPtrAddr(SEXP s);
DL_FUNC R_ExternalPtrAddrFn(SEXP s);
SEXP R_ExternalPtrTag(SEXP s);
SEXP R_ExternalPtrProtected(SEXP s);
void R_ClearExternalPtr(SEXP s);
void R_SetExternalPtrAddr(SEXP s, void *p);
void R_SetExternalPtrTag(SEXP s, SEXP tag);
void R_SetExternalPtrProtected(SEXP s, SEXP p);
</pre></div>
<a class="index-entry-id" id="index-R_005fExternalPtrAddr"></a>
<a class="index-entry-id" id="index-R_005fExternalPtrAddrFn"></a>
<a class="index-entry-id" id="index-R_005fExternalPtrTag"></a>
<a class="index-entry-id" id="index-R_005fExternalPtrProtected"></a>
<a class="index-entry-id" id="index-R_005fClearExternalPtr"></a>
<a class="index-entry-id" id="index-R_005fSetExternalPtrAddr"></a>
<a class="index-entry-id" id="index-R_005fSetExternalPtrTag"></a>
<a class="index-entry-id" id="index-R_005fSetExternalPtrProtected"></a>


<p>Clearing a pointer sets its value to the C <code class="code">NULL</code> pointer.
</p>
<a class="index-entry-id" id="index-finalizer"></a>
<p>An external pointer object can have a <em class="emph">finalizer</em>, a piece of code
to be run when the object is garbage collected.  This can be R code
or C code, and the various interfaces are, respectively.
</p>
<div class="example">
<pre class="example-preformatted">void R_RegisterFinalizer(SEXP s, SEXP fun);
void R_RegisterFinalizerEx(SEXP s, SEXP fun, Rboolean onexit);

typedef void (*R_CFinalizer_t)(SEXP);
void R_RegisterCFinalizer(SEXP s, R_CFinalizer_t fun);
void R_RegisterCFinalizerEx(SEXP s, R_CFinalizer_t fun, Rboolean onexit);
</pre></div>
<a class="index-entry-id" id="index-R_005fRegisterFinalizer"></a>
<a class="index-entry-id" id="index-R_005fRegisterCFinalizer"></a>
<a class="index-entry-id" id="index-R_005fRegisterFinalizerEx"></a>
<a class="index-entry-id" id="index-R_005fRegisterCFinalizerEx"></a>

<p>The R function indicated by <code class="code">fun</code> should be a function of a
single argument, the object to be finalized.  R does not perform a
garbage collection when shutting down, and the <code class="code">onexit</code> argument of
the extended forms can be used to ask that the finalizer be run during a
normal shutdown of the R session.  It is suggested that it is good
practice to clear the pointer on finalization.
</p>
<p>The only R level function for interacting with external pointers is
<code class="code">reg.finalizer</code> which can be used to set a finalizer.
</p>
<p>It is probably not a good idea to allow an external pointer to be
<code class="code">save</code>d and then reloaded, but if this happens the pointer will be
set to the C <code class="code">NULL</code> pointer.
</p>
<p>Finalizers can be run at many places in the code base and much of it,
including the R interpreter, is not re-entrant.  So great care is
needed in choosing the code to be run in a finalizer.  Finalizers are
marked to be run at garbage collection but only run at a somewhat safe
point thereafter.
</p>
<a class="index-entry-id" id="index-weak-reference"></a>
<p>Weak references are used to allow the programmer to maintain information
on entities without preventing the garbage collection of the entities
once they become unreachable.
</p>
<p>A weak reference contains a key and a value.  The value is reachable is
if it either reachable directly or <em class="emph">via</em> weak references with reachable
keys.  Once a value is determined to be unreachable during garbage
collection, the key and value are set to <code class="code">R_NilValue</code> and the
finalizer will be run later in the garbage collection.
</p>
<p>Weak reference objects are created by one of
</p>
<div class="example">
<pre class="example-preformatted">SEXP R_MakeWeakRef(SEXP key, SEXP val, SEXP fin, Rboolean onexit);
SEXP R_MakeWeakRefC(SEXP key, SEXP val, R_CFinalizer_t fin,
                    Rboolean onexit);
</pre></div>
<a class="index-entry-id" id="index-R_005fMakeWeakRef"></a>
<a class="index-entry-id" id="index-R_005fMakeWeakRefC"></a>

<p>where the R or C finalizer are specified in exactly the same way as
for an external pointer object (whose finalization interface is
implemented <em class="emph">via</em> weak references).
</p>
<p>The parts can be accessed <em class="emph">via</em>
</p>
<div class="example">
<pre class="example-preformatted">SEXP R_WeakRefKey(SEXP w);
SEXP R_WeakRefValue(SEXP w);
void R_RunWeakRefFinalizer(SEXP w);
</pre></div>
<a class="index-entry-id" id="index-R_005fWeakRefKey"></a>
<a class="index-entry-id" id="index-R_005fWeakRefValue"></a>
<a class="index-entry-id" id="index-R_005fRunWeakRefFinalizer"></a>

<p>A toy example of the use of weak references can be found at
<a class="uref" href="https://homepage.stat.uiowa.edu/~luke/R/references/weakfinex.html">https://homepage.stat.uiowa.edu/~luke/R/references/weakfinex.html</a>,
but that is used to add finalizers to external pointers which can now be
done more directly.  At the time of writing no <abbr class="acronym">CRAN</abbr> or
Bioconductor package uses weak references.
</p>


<ul class="mini-toc">
<li><a href="#An-external-pointer-example" accesskey="1">An example</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="An-external-pointer-example">
<div class="nav-panel">
<p>
Previous: <a href="#External-pointers-and-weak-references" accesskey="p" rel="prev">External pointers and weak references</a>, Up: <a href="#External-pointers-and-weak-references" accesskey="u" rel="up">External pointers and weak references</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="An-example-2"><span>5.13.1 An example<a class="copiable-link" href="#An-example-2"> &para;</a></span></h4>

<p>Package <a class="url" href="https://CRAN.R-project.org/package=RODBC"><strong class="strong">RODBC</strong></a> uses external pointers to maintain its
<em class="emph">channels</em>, connections to databases.  There can be several
connections open at once, and the status information for each is stored
in a C structure (pointed to by <code class="code">thisHandle</code> in the code extract
below) that is returned <em class="emph">via</em> an external pointer as part of the
<strong class="strong">RODBC</strong> 
&lsquo;channel&rsquo; (as the <code class="code">&quot;handle_ptr&quot;</code> attribute).  The external pointer
is created by
</p>
<div class="example">
<pre class="example-preformatted">    SEXP ans, ptr;
    ans = PROTECT(allocVector(INTSXP, 1));
    ptr = R_MakeExternalPtr(thisHandle, install(&quot;RODBC_channel&quot;), R_NilValue);
    PROTECT(ptr);
    R_RegisterCFinalizerEx(ptr, chanFinalizer, TRUE);
            ...
    /* return the channel no */
    INTEGER(ans)[0] = nChannels;
    /* and the connection string as an attribute */
    setAttrib(ans, install(&quot;connection.string&quot;), constr);
    setAttrib(ans, install(&quot;handle_ptr&quot;), ptr);
    UNPROTECT(3);
    return ans;
</pre></div>

<p>Note the symbol given to identify the usage of the external pointer, and
the use of the finalizer.  Since the final argument when registering the
finalizer is <code class="code">TRUE</code>, the finalizer will be run at the end of the
R session (unless it crashes).  This is used to close and clean up
the connection to the database.  The finalizer code is simply
</p>
<div class="example">
<pre class="example-preformatted">static void chanFinalizer(SEXP ptr)
{
    if(!R_ExternalPtrAddr(ptr)) return;
    inRODBCClose(R_ExternalPtrAddr(ptr));
    R_ClearExternalPtr(ptr); /* not really needed */
}
</pre></div>

<p>Clearing the pointer and checking for a <code class="code">NULL</code> pointer avoids any
possibility of attempting to close an already-closed channel.
</p>
<p>R&rsquo;s connections provide another example of using external pointers,
in that case purely to be able to use a finalizer to close and destroy the
connection if it is no longer is use.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Vector-accessor-functions">
<div class="nav-panel">
<p>
Next: <a href="#Character-encoding-issues" accesskey="n" rel="next">Character encoding issues</a>, Previous: <a href="#External-pointers-and-weak-references" accesskey="p" rel="prev">External pointers and weak references</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Vector-accessor-functions-1"><span>5.14 Vector accessor functions<a class="copiable-link" href="#Vector-accessor-functions-1"> &para;</a></span></h3>

<p>The vector accessors like <code class="code">REAL</code>, <code class="code">INTEGER</code>, <code class="code">LOGICAL</code>,
<code class="code">RAW</code>, <code class="code">COMPLEX</code>, and <code class="code">VECTOR_ELT</code> are <em class="emph">functions</em>
when used in R extensions.  (For efficiency they may be macros or
inline functions when used in the R source code, apart from
<code class="code">SET_STRING_ELT</code> and <code class="code">SET_VECTOR_ELT</code> which are always
functions.)
<a class="index-entry-id" id="index-VECTOR_005fELT"></a>
<a class="index-entry-id" id="index-SET_005fVECTOR_005fELT"></a>
<a class="index-entry-id" id="index-REAL"></a>
<a class="index-entry-id" id="index-INTEGER"></a>
<a class="index-entry-id" id="index-LOGICAL"></a>
<a class="index-entry-id" id="index-RAW"></a>
<a class="index-entry-id" id="index-COMPLEX"></a>
</p>
<p>The accessor functions check that they are being used on an appropriate
type of <code class="code">SEXP</code>.
</p>
<p>Formerly it was possible for packages to obtain internal versions of
some accessors by defining &lsquo;<samp class="samp">USE_RINTERNALS</samp>&rsquo; before including
<samp class="file">Rinternals.h</samp>. This is no longer the case. Defining
&lsquo;<samp class="samp">USE_RINTERNALS</samp>&rsquo; now has no effect.
</p>

<hr>
</div>
<div class="section-level-extent" id="Character-encoding-issues">
<div class="nav-panel">
<p>
Previous: <a href="#Vector-accessor-functions" accesskey="p" rel="prev">Vector accessor functions</a>, Up: <a href="#System-and-foreign-language-interfaces" accesskey="u" rel="up">System and foreign language interfaces</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Character-encoding-issues-1"><span>5.15 Character encoding issues<a class="copiable-link" href="#Character-encoding-issues-1"> &para;</a></span></h3>

<a class="index-entry-id" id="index-translateChar"></a>
<a class="index-entry-id" id="index-translateCharUTF8"></a>
<p><code class="code">CHARSXP</code>s can be marked as coming from a known encoding (Latin-1
or UTF-8).  This is mainly intended for human-readable output, and most
packages can just treat such <code class="code">CHARSXP</code>s as a whole.  However, if
they need to be interpreted as characters or output at C level then it
would normally be correct to ensure that they are converted to the
encoding of the current locale: this can be done by accessing the data
in the <code class="code">CHARSXP</code> by <code class="code">translateChar</code> rather than by
<code class="code">CHAR</code>.  If re-encoding is needed this allocates memory with
<code class="code">R_alloc</code> which thus persists to the end of the
<code class="code">.Call</code>/<code class="code">.External</code> call unless <code class="code">vmaxset</code> is used
(see <a class="pxref" href="#Transient-storage-allocation">Transient storage allocation</a>).
</p>
<p>There is a similar function <code class="code">translateCharUTF8</code> which converts to
UTF-8: this has the advantage that a faithful translation is almost
always possible (whereas only a few languages can be represented in the
encoding of the current locale unless that is UTF-8).
</p>
<p>Both <code class="code">translateChar</code> and <code class="code">translateCharUTF8</code> will translate
any input, using escapes such as &lsquo;<samp class="samp">&lt;A9&gt;</samp>&rsquo; and &lsquo;<samp class="samp">&lt;U+0093&gt;</samp>&rsquo; to
represent untranslatable parts of the input.
</p>
<a class="index-entry-id" id="index-getCharCE"></a>
<a class="index-entry-id" id="index-mkCharCE"></a>
<p>There is a public interface to the encoding marked on <code class="code">CHARSXPs</code>
<em class="emph">via</em>
</p>
<div class="example">
<pre class="example-preformatted">typedef enum {CE_NATIVE, CE_UTF8, CE_LATIN1, CE_BYTES, CE_SYMBOL, CE_ANY} cetype_t;
cetype_t getCharCE(SEXP);
SEXP mkCharCE(const char *, cetype_t);
</pre></div>

<p>Only <code class="code">CE_UTF8</code> and <code class="code">CE_LATIN1</code> are marked on <code class="code">CHARSXPs</code>
(and so <code class="code">Rf_getCharCE</code> will only return one of the first three),
and these should only be used on non-<abbr class="acronym">ASCII</abbr> strings.  Value
<code class="code">CE_BYTES</code> is used to make <code class="code">CHARSXP</code>s which should be regarded
as a set of bytes and not translated.  Value <code class="code">CE_SYMBOL</code> is used
internally to indicate Adobe Symbol encoding.  Value <code class="code">CE_ANY</code> is
used to indicate a character string that will not need re-encoding &ndash;
this is used for character strings known to be in <abbr class="acronym">ASCII</abbr>, and
can also be used as an input parameter where the intention is that the
string is treated as a series of bytes.  (See the comments under
<code class="code">mkChar</code> about the length of input allowed.)
</p>
<p>Function
</p>
<a class="index-entry-id" id="index-reEnc"></a>
<div class="example">
<pre class="example-preformatted">const char *reEnc(const char *x, cetype_t ce_in, cetype_t ce_out,
                  int subst);
</pre></div>

<p>can be used to re-encode character strings: like <code class="code">translateChar</code> it
returns a string allocated by <code class="code">R_alloc</code>.  This can translate from
<code class="code">CE_SYMBOL</code> to <code class="code">CE_UTF8</code>, but not conversely.  Argument
<code class="code">subst</code> controls what to do with untranslatable characters or
invalid input: this is done byte-by-byte with <code class="code">1</code> indicates to
output hex of the form <code class="code">&lt;a0&gt;</code>, and <code class="code">2</code> to replace by <code class="code">.</code>,
with any other value causing the byte to produce no output.
</p>
<a class="index-entry-id" id="index-mkCharLenCE"></a>
<p>There is also
</p>
<div class="example">
<pre class="example-preformatted">SEXP mkCharLenCE(const char *, int, cetype_t);
</pre></div>

<p>to create marked character strings of a given length.
</p>

<hr>
</div>
</div>
<div class="chapter-level-extent" id="The-R-API">
<div class="nav-panel">
<p>
Next: <a href="#Generic-functions-and-methods" accesskey="n" rel="next">Generic functions and methods</a>, Previous: <a href="#System-and-foreign-language-interfaces" accesskey="p" rel="prev">System and foreign language interfaces</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="chapter" id="The-R-API_003a-entry-points-for-C-code"><span>6 The R <abbr class="acronym">API</abbr>: entry points for C code<a class="copiable-link" href="#The-R-API_003a-entry-points-for-C-code"> &para;</a></span></h2>


<p>There are a large number of entry points in the R executable/DLL that
can be called from C code (and some that can be called from Fortran
code).  Only those documented here are stable enough that they will only
be changed with considerable notice.
</p>
<p>The recommended procedure to use these is to include the header file
<samp class="file">R.h</samp> in your C code by
</p>
<div class="example">
<pre class="example-preformatted">#include &lt;R.h&gt;
</pre></div>

<p>This will include several other header files from the directory
<samp class="file"><var class="var">R_INCLUDE_DIR</var>/R_ext</samp>, and there are other header files
there that can be included too, but many of the features they contain
should be regarded as undocumented and unstable.
</p>
<p>Most of these header files, including all those included by <samp class="file">R.h</samp>,
can be used from C++ code.
</p>
<blockquote class="quotation">
<p><b class="b">Note:</b> Because R re-maps many of its external names to avoid clashes with
system or user code, it is <em class="emph">essential</em> to include the appropriate
header files when using these entry points.
</p></blockquote>

<p>This remapping can cause problems<a class="footnote" id="DOCF162" href="#FOOT162"><sup>162</sup></a>,
and can be eliminated by defining <code class="code">R_NO_REMAP</code> (before including
any R headers) and prepending &lsquo;<samp class="samp">Rf_</samp>&rsquo; to <em class="emph">all</em> the function
names used from <samp class="file">Rinternals.h</samp> and <samp class="file">R_ext/Error.h</samp>.  These
problems can usually be avoided by including other headers (such as
system headers and those for external software used by the package)
before any R headers. (Headers from other packages may include R
headers directly or <em class="emph">via</em> inclusion from further packages, and may
define <code class="code">R_NO_REMAP</code> with or without including <samp class="file">Rinternals.h</samp>.)
</p>
<p>We can classify the entry points as
</p>
<dl class="table">
<dt><em class="emph">API</em></dt>
<dd><p>Entry points which are documented in this manual and declared in an
installed header file.  These can be used in distributed packages and
will only be changed after deprecation.
</p>
</dd>
<dt><em class="emph">public</em></dt>
<dd><p>Entry points declared in an installed header file that are exported
on all R platforms but are not documented and subject to change
without notice.
</p>
</dd>
<dt><em class="emph">private</em></dt>
<dd><p>Entry points that are used when building R and exported on all R
platforms but are not declared in the installed header files.
Do not use these in distributed code.
</p>
</dd>
<dt><em class="emph">hidden</em></dt>
<dd><p>Entry points that are where possible (Windows and some modern Unix-alike
compilers/loaders when using R as a shared library) not exported.
</p></dd>
</dl>

<ul class="mini-toc">
<li><a href="#Memory-allocation" accesskey="1">Memory allocation</a></li>
<li><a href="#Error-signaling" accesskey="2">Error signaling</a></li>
<li><a href="#Random-numbers" accesskey="3">Random number generation</a></li>
<li><a href="#Missing-and-IEEE-values" accesskey="4">Missing and <abbr class="acronym">IEEE</abbr> special values</a></li>
<li><a href="#Printing" accesskey="5">Printing</a></li>
<li><a href="#Calling-C-from-Fortran-and-vice-versa" accesskey="6">Calling C from Fortran and vice versa</a></li>
<li><a href="#Numerical-analysis-subroutines" accesskey="7">Numerical analysis subroutines</a></li>
<li><a href="#Optimization" accesskey="8">Optimization</a></li>
<li><a href="#Integration" accesskey="9">Integration</a></li>
<li><a href="#Utility-functions">Utility functions</a></li>
<li><a href="#Re_002dencoding">Re-encoding</a></li>
<li><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></li>
<li><a href="#Allowing-interrupts">Allowing interrupts</a></li>
<li><a href="#Platform-and-version-information">Platform and version information</a></li>
<li><a href="#Inlining-C-functions">Inlining C functions</a></li>
<li><a href="#Controlling-visibility">Controlling visibility</a></li>
<li><a href="#Standalone-Mathlib">Using these functions in your own C code</a></li>
<li><a href="#Organization-of-header-files">Organization of header files</a></li>
</ul>
<hr>
<div class="section-level-extent" id="Memory-allocation">
<div class="nav-panel">
<p>
Next: <a href="#Error-signaling" accesskey="n" rel="next">Error signaling</a>, Previous: <a href="#The-R-API" accesskey="p" rel="prev">The R <abbr class="acronym">API</abbr>: entry points for C code</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Memory-allocation-1"><span>6.1 Memory allocation<a class="copiable-link" href="#Memory-allocation-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Memory-allocation-from-C"></a>


<p>There are two types of memory allocation available to the C programmer,
one in which R manages the clean-up and the other in which user
has full control (and responsibility).
</p>
<p>These functions are declared in header <samp class="file">R_ext/RS.h</samp> which is
included by <samp class="file">R.h</samp>.
</p>
<ul class="mini-toc">
<li><a href="#Transient-storage-allocation" accesskey="1">Transient storage allocation</a></li>
<li><a href="#User_002dcontrolled-memory" accesskey="2">User-controlled memory</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Transient-storage-allocation">
<div class="nav-panel">
<p>
Next: <a href="#User_002dcontrolled-memory" accesskey="n" rel="next">User-controlled memory</a>, Previous: <a href="#Memory-allocation" accesskey="p" rel="prev">Memory allocation</a>, Up: <a href="#Memory-allocation" accesskey="u" rel="up">Memory allocation</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Transient-storage-allocation-1"><span>6.1.1 Transient storage allocation<a class="copiable-link" href="#Transient-storage-allocation-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-R_005falloc"></a>
<a class="index-entry-id" id="index-R_005fallocLD"></a>
<a class="index-entry-id" id="index-S_005falloc"></a>
<a class="index-entry-id" id="index-S_005frealloc"></a>
<a class="index-entry-id" id="index-vmaxget"></a>
<a class="index-entry-id" id="index-vmaxset"></a>
<a class="index-entry-id" id="index-nrows"></a>

<p>Here R will reclaim the memory at the end of the call to <code class="code">.C</code>,
<code class="code">.Call</code> or <code class="code">.External</code>.  Use
</p>
<div class="example">
<pre class="example-preformatted">char *R_alloc(size_t <var class="var">n</var>, int <var class="var">size</var>)
</pre></div>

<p>which allocates <var class="var">n</var> units of <var class="var">size</var> bytes each.  A typical usage
(from package <strong class="strong">stats</strong>) is
</p>
<div class="example">
<pre class="example-preformatted">x = (int *) R_alloc(nrows(merge)+2, sizeof(int));
</pre></div>

<p>(<code class="code">size_t</code> is defined in <samp class="file">stddef.h</samp> which the header defining
<code class="code">R_alloc</code> includes.)
</p>
<p>There is a similar call, <code class="code">S_alloc</code> (named for compatibility with older
versions of S) which zeroes the memory allocated,
</p>
<div class="example">
<pre class="example-preformatted">char *S_alloc(long <var class="var">n</var>, int <var class="var">size</var>)
</pre></div>

<p>and
</p>
<div class="example">
<pre class="example-preformatted">char *S_realloc(char *<var class="var">p</var>, long <var class="var">new</var>, long <var class="var">old</var>, int <var class="var">size</var>)
</pre></div>

<p>which (for <code class="code"><var class="var">new</var> &gt; <var class="var">old</var></code>) changes the allocation size
from <var class="var">old</var> to <var class="var">new</var> units, and zeroes the additional units.  NB:
these calls are best avoided as <code class="code">long</code> is insufficient for large
memory allocations on 64-bit Windows (where it is limited to 2^31-1
bytes).
</p>
<p>This memory is taken from the heap, and released at the end of the
<code class="code">.C</code>, <code class="code">.Call</code> or <code class="code">.External</code> call.  Users can also manage
it, by noting the current position with a call to <code class="code">vmaxget</code> and
subsequently clearing memory allocated by a call to <code class="code">vmaxset</code>. An
example might be
</p>
<div class="example">
<pre class="example-preformatted">void *vmax = vmaxget()
// a loop involving the use of R_alloc at each iteration
vmaxset(vmax)
</pre></div>

<p>This is only recommended for experts.
</p>
<p>Note that this memory will be freed on error or user interrupt
(if allowed: see <a class="pxref" href="#Allowing-interrupts">Allowing interrupts</a>).
</p>
<p>The memory returned is only guaranteed to be aligned as required for
<code class="code">double</code> pointers: take precautions if casting to a pointer which
needs more.  There is also
</p>
<div class="example">
<pre class="example-preformatted">long double *R_allocLD(size_t <var class="var">n</var>)
</pre></div>

<p>which is guaranteed to have the 16-byte alignment needed for <code class="code">long
double</code> pointers on some platforms.
</p>

<p>These functions should only be used in code called by <code class="code">.C</code> etc,
never from front-ends.  They are not thread-safe.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="User_002dcontrolled-memory">
<div class="nav-panel">
<p>
Previous: <a href="#Transient-storage-allocation" accesskey="p" rel="prev">Transient storage allocation</a>, Up: <a href="#Memory-allocation" accesskey="u" rel="up">Memory allocation</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="User_002dcontrolled-memory-1"><span>6.1.2 User-controlled memory<a class="copiable-link" href="#User_002dcontrolled-memory-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-R_005fCalloc"></a>
<a class="index-entry-id" id="index-R_005fRealloc"></a>
<a class="index-entry-id" id="index-R_005fFree"></a>

<p>The other form of memory allocation is an interface to <code class="code">malloc</code>,
the interface providing R error signaling.  This memory lasts until
freed by the user and is additional to the memory allocated for the R
workspace.
</p>
<p>The interface macros are
</p>
<div class="example">
<div class="group"><pre class="example-preformatted"><var class="var">type</var>* R_Calloc(size_t <var class="var">n</var>, <var class="var">type</var>)
<var class="var">type</var>* R_Realloc(<var class="var">any</var> *<var class="var">p</var>, size_t <var class="var">n</var>, <var class="var">type</var>)
void R_Free(<var class="var">any</var> *<var class="var">p</var>)
</pre></div></div>

<p>providing analogues of <code class="code">calloc</code>, <code class="code">realloc</code> and <code class="code">free</code>.
If there is an error during allocation it is handled by R, so if
these return the memory has been successfully allocated or freed.
<code class="code">R_Free</code> will set the pointer <var class="var">p</var> to <code class="code">NULL</code>.  (Some but not
all versions of S did so.)
</p>
<p>Users should arrange to <code class="code">R_Free</code> this memory when no longer needed,
including on error or user interrupt.  This can often be done most
conveniently from an <code class="code">on.exit</code> action in the calling R function
&ndash; see <code class="code">pwilcox</code> for an example.
</p>
<p>Do not assume that memory allocated by <code class="code">R_Calloc</code>/<code class="code">R_Realloc</code>
comes from the same pool as used by <code class="code">malloc</code>:<a class="footnote" id="DOCF163" href="#FOOT163"><sup>163</sup></a> in particular do not use
<code class="code">free</code> or <code class="code">strdup</code> with it.
</p>
<p>Memory obtained by these macros should be aligned in the same way as
<code class="code">malloc</code>, that is &lsquo;suitably aligned for any kind of variable&rsquo;.
</p>
<a class="index-entry-id" id="index-Calloc"></a>
<a class="index-entry-id" id="index-Realloc"></a>
<a class="index-entry-id" id="index-Free"></a>
<p>Historically the macros <code class="code">Calloc</code>, <code class="code">Free</code> and <code class="code">Realloc</code>
were used, and these remain available unless  <code class="code">STRICT_R_HEADERS</code>
was defined prior to the inclusion of the header.
</p>
<a class="index-entry-id" id="index-CallocCharBuf"></a>
<a class="index-entry-id" id="index-Memcpy"></a>
<a class="index-entry-id" id="index-Memzero"></a>
<div class="example">
<div class="group"><pre class="example-preformatted">char * CallocCharBuf(size_t <var class="var">n</var>)
void * Memcpy(<var class="var">q</var>, <var class="var">p</var>, <var class="var">n</var>)
void * Memzero(<var class="var">p</var>, <var class="var">n</var>)
</pre></div></div>
<p><code class="code">CallocCharBuf(n)</code> is shorthand for <code class="code">R_Calloc(n+1, char)</code> to allow
for the <code class="code">nul</code> terminator.  <code class="code">Memcpy</code> and <code class="code">Memzero</code> take
<code class="code">n</code> items from array <code class="code">p</code> and copy them to array <code class="code">q</code> or
zero them respectively.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Error-signaling">
<div class="nav-panel">
<p>
Next: <a href="#Random-numbers" accesskey="n" rel="next">Random number generation</a>, Previous: <a href="#Memory-allocation" accesskey="p" rel="prev">Memory allocation</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Error-signaling-1"><span>6.2 Error signaling<a class="copiable-link" href="#Error-signaling-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Error-signaling-from-C"></a>

<p>The basic error signaling routines are the equivalents of <code class="code">stop</code> and
<code class="code">warning</code> in R code, and use the same interface.
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">void error(const char * <var class="var">format</var>, ...);
void warning(const char * <var class="var">format</var>, ...);
void errorcall(SEXP <var class="var">call</var>, const char * <var class="var">format</var>, ...);
void warningcall(SEXP <var class="var">call</var>, const char * <var class="var">format</var>, ...);
void warningcall_immediate(SEXP <var class="var">call</var>, const char * <var class="var">format</var>, ...);
</pre></div></div>
<a class="index-entry-id" id="index-error"></a>
<a class="index-entry-id" id="index-warning"></a>
<a class="index-entry-id" id="index-errorcall"></a>
<a class="index-entry-id" id="index-warningcall"></a>
<a class="index-entry-id" id="index-warningcall_005fimmediate"></a>

<p>These have the same call sequences as calls to <code class="code">printf</code>, but in the
simplest case can be called with a single character string argument
giving the error message. (Don&rsquo;t do this if the string contains &lsquo;<samp class="samp">%</samp>&rsquo;
or might otherwise be interpreted as a format.)
</p>
<p>These are defined in header <samp class="file">R_ext/Error.h</samp> included by
<samp class="file">R.h</samp>.
</p>

<ul class="mini-toc">
<li><a href="#Error-signaling-from-Fortran" accesskey="1">Error signaling from Fortran</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Error-signaling-from-Fortran">
<div class="nav-panel">
<p>
Previous: <a href="#Error-signaling" accesskey="p" rel="prev">Error signaling</a>, Up: <a href="#Error-signaling" accesskey="u" rel="up">Error signaling</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Error-signaling-from-Fortran-1"><span>6.2.1 Error signaling from Fortran<a class="copiable-link" href="#Error-signaling-from-Fortran-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Error-signaling-from-Fortran"></a>

<p>There are two interface function provided to call <code class="code">error</code> and
<code class="code">warning</code> from Fortran code, in each case with a simple character
string argument.  They are defined as
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">subroutine rexit(<var class="var">message</var>)
subroutine rwarn(<var class="var">message</var>)
</pre></div></div>

<p>Messages of more than 255 characters are truncated, with a warning.
</p>

<hr>
</div>
</div>
<div class="section-level-extent" id="Random-numbers">
<div class="nav-panel">
<p>
Next: <a href="#Missing-and-IEEE-values" accesskey="n" rel="next">Missing and <abbr class="acronym">IEEE</abbr> special values</a>, Previous: <a href="#Error-signaling" accesskey="p" rel="prev">Error signaling</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Random-number-generation"><span>6.3 Random number generation<a class="copiable-link" href="#Random-number-generation"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Random-numbers-in-C"></a>
<a class="index-entry-id" id="index-unif_005frand"></a>
<a class="index-entry-id" id="index-norm_005frand"></a>
<a class="index-entry-id" id="index-exp_005frand"></a>
<a class="index-entry-id" id="index-R_005funif_005findex"></a>
<a class="index-entry-id" id="index-GetRNGstate"></a>
<a class="index-entry-id" id="index-PutRNGstate"></a>
<a class="index-entry-id" id="index-_002eRandom_002eseed"></a>

<p>The interface to R&rsquo;s internal random number generation routines is
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">double unif_rand();
double norm_rand();
double exp_rand();
double R_unif_index(double);
</pre></div></div>

<p>giving one uniform, normal or exponential pseudo-random variate.
However, before these are used, the user must call
</p>
<div class="example">
<pre class="example-preformatted">GetRNGstate();
</pre></div>

<p>and after all the required variates have been generated, call
</p>
<div class="example">
<pre class="example-preformatted">PutRNGstate();
</pre></div>

<p>These essentially read in (or create) <code class="code">.Random.seed</code> and write it
out after use.
</p>
<p>These are defined in header <samp class="file">R_ext/Random.h</samp>.
</p>
<p>The random number generator is private to R; there is no way to
select the kind of RNG nor set the seed except by evaluating calls to the
R functions.
</p>
<p>The C code behind R&rsquo;s <code class="code">r<var class="var">xxx</var></code> functions can be accessed by
including the header file <samp class="file">Rmath.h</samp>; See <a class="xref" href="#Distribution-functions">Distribution functions</a>.
Those calls should also be preceded and followed by calls to
<code class="code">GetRNGstate</code> and <code class="code">PutRNGstate</code>.
</p>

<ul class="mini-toc">
<li><a href="#Random_002dnumber-generation-from-Fortran" accesskey="1">Random-number generation from Fortran</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Random_002dnumber-generation-from-Fortran">
<div class="nav-panel">
<p>
Previous: <a href="#Random-numbers" accesskey="p" rel="prev">Random number generation</a>, Up: <a href="#Random-numbers" accesskey="u" rel="up">Random number generation</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Random_002dnumber-generation-from-Fortran-1"><span>6.3.1 Random-number generation from Fortran<a class="copiable-link" href="#Random_002dnumber-generation-from-Fortran-1"> &para;</a></span></h4>

<p>It was explained earlier that Fortran random-number generators should
not be used in R packages, not least as packages cannot safely
initialize them.  Rather a package should call R&rsquo;s built in
generators: one way to do so is to use C wrappers like
</p><div class="example">
<pre class="example-preformatted">#include &lt;R_ext/RS.h&gt;
#include &lt;R_ext/Random.h&gt;

void F77_SUB(getRNGseed)(void) {
    GetRNGstate();
}
void F77_SUB(putRNGseed)(void) {
    PutRNGstate();
}
double F77_SUB(unifRand)(void) {
    return(unif_rand());
}
</pre></div>
<p>called from Fortran code like
</p><div class="example">
<pre class="example-preformatted">      ...
      double precision X
      call getRNGseed()
      X = unifRand()
      ...
      call putRNGseed()
</pre></div>

<p>Alternatively one could use Fortran 2003&rsquo;s <code class="code">iso_c_binding</code> module
by something like (fixed-form Fortran 90 code):
</p><div class="example">
<pre class="example-preformatted">      module rngfuncs
        use iso_c_binding
        interface
          double precision
     *      function unifRand() bind(C, name = &quot;unif_rand&quot;)
          end function unifRand

          subroutine getRNGseed() bind(C, name = &quot;GetRNGstate&quot;)
          end subroutine getRNGseed

          subroutine putRNGseed() bind(C, name = &quot;PutRNGstate&quot;)
          end subroutine putRNGseed
        end interface
      end module
      
      subroutine testit
      use rngfuncs
      double precision X
      call getRNGseed()
      X = unifRand()
      print *, X
      call putRNGSeed()
      end
</pre></div>


<hr>
</div>
</div>
<div class="section-level-extent" id="Missing-and-IEEE-values">
<div class="nav-panel">
<p>
Next: <a href="#Printing" accesskey="n" rel="next">Printing</a>, Previous: <a href="#Random-numbers" accesskey="p" rel="prev">Random number generation</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Missing-and-IEEE-special-values"><span>6.4 Missing and <abbr class="acronym">IEEE</abbr> special values<a class="copiable-link" href="#Missing-and-IEEE-special-values"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Missing-values-1"></a>
<a class="index-entry-id" id="index-IEEE-special-values-1"></a>
<a class="index-entry-id" id="index-ISNA-1"></a>
<a class="index-entry-id" id="index-ISNAN-1"></a>
<a class="index-entry-id" id="index-R_005fFINITE"></a>
<a class="index-entry-id" id="index-R_005fIsNaN"></a>
<a class="index-entry-id" id="index-R_005fPosInf"></a>
<a class="index-entry-id" id="index-R_005fNegInf"></a>
<a class="index-entry-id" id="index-NA_005fREAL"></a>

<p>A set of functions is provided to test for <code class="code">NA</code>, <code class="code">Inf</code>,
<code class="code">-Inf</code> and <code class="code">NaN</code>.  These functions are accessed <em class="emph">via</em> macros:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">ISNA(<var class="var">x</var>)        <span class="r">True for R&rsquo;s <code class="code">NA</code> only</span>
ISNAN(<var class="var">x</var>)       <span class="r">True for R&rsquo;s <code class="code">NA</code> and <abbr class="acronym">IEEE</abbr> <code class="code">NaN</code></span>
R_FINITE(<var class="var">x</var>)    <span class="r">False for <code class="code">Inf</code>, <code class="code">-Inf</code>, <code class="code">NA</code>, <code class="code">NaN</code></span>
</pre></div></div>

<p>and <em class="emph">via</em> function <code class="code">R_IsNaN</code> which is true for <code class="code">NaN</code> but not
<code class="code">NA</code>.
</p>
<p>Do use <code class="code">R_FINITE</code> rather than <code class="code">isfinite</code> or <code class="code">finite</code>; the
latter is often mendacious and <code class="code">isfinite</code> is only available on a
some platforms, on which <code class="code">R_FINITE</code> is a macro expanding to
<code class="code">isfinite</code>.
</p>
<p>Currently in C code <code class="code">ISNAN</code> is a macro calling <code class="code">isnan</code>.
(Since this gives problems on some C++ systems, if the R headers is
called from C++ code a function call is used.)
</p>
<p>You can check for <code class="code">Inf</code> or <code class="code">-Inf</code> by testing equality to
<code class="code">R_PosInf</code> or <code class="code">R_NegInf</code>, and set (but not test) an <code class="code">NA</code>
as <code class="code">NA_REAL</code>.
</p>
<p>All of the above apply to <em class="emph">double</em> variables only.  For integer
variables there is a variable accessed by the macro <code class="code">NA_INTEGER</code>
which can used to set or test for missingness.
</p>
<p>These are defined in header <samp class="file">R_ext/Arith.h</samp> included by <samp class="file">R.h</samp>.
</p>
<hr>
</div>
<div class="section-level-extent" id="Printing">
<div class="nav-panel">
<p>
Next: <a href="#Calling-C-from-Fortran-and-vice-versa" accesskey="n" rel="next">Calling C from Fortran and vice versa</a>, Previous: <a href="#Missing-and-IEEE-values" accesskey="p" rel="prev">Missing and <abbr class="acronym">IEEE</abbr> special values</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Printing-1"><span>6.5 Printing<a class="copiable-link" href="#Printing-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Printing-from-C"></a>
<a class="index-entry-id" id="index-Rprintf"></a>
<a class="index-entry-id" id="index-REprintf"></a>
<a class="index-entry-id" id="index-Rvprintf"></a>
<a class="index-entry-id" id="index-REvprintf"></a>

<p>The most useful function for printing from a C routine compiled into
R is <code class="code">Rprintf</code>.  This is used in exactly the same way as
<code class="code">printf</code>, but is guaranteed to write to R&rsquo;s output (which might
be a <abbr class="acronym">GUI</abbr> console rather than a file, and can be re-directed by
<code class="code">sink</code>).  It is wise to write complete lines (including the
<code class="code">&quot;\n&quot;</code>) before returning to R.  It is defined in
<samp class="file">R_ext/Print.h</samp>.
</p>
<p>The function <code class="code">REprintf</code> is similar but writes on the error stream
(<code class="code">stderr</code>) which may or may not be different from the standard
output stream.
</p>
<p>Functions <code class="code">Rvprintf</code> and <code class="code">REvprintf</code> are analogues using the
<code class="code">vprintf</code> interface.  Because that is a C99<a class="footnote" id="DOCF164" href="#FOOT164"><sup>164</sup></a> interface, they are only defined by <samp class="file">R_ext/Print.h</samp> in C++
code if the macro <code class="code">R_USE_C99_IN_CXX</code> is defined before it is
included or (as from R 4.0.0) a C++11 compiler is used.
</p>
<p>Another circumstance when it may be important to use these functions is
when using parallel computation on a cluster of computational nodes, as
their output will be re-directed/logged appropriately.
</p>

<ul class="mini-toc">
<li><a href="#Printing-from-Fortran" accesskey="1">Printing from Fortran</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Printing-from-Fortran">
<div class="nav-panel">
<p>
Previous: <a href="#Printing" accesskey="p" rel="prev">Printing</a>, Up: <a href="#Printing" accesskey="u" rel="up">Printing</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Printing-from-Fortran-1"><span>6.5.1 Printing from Fortran<a class="copiable-link" href="#Printing-from-Fortran-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Printing-from-Fortran"></a>

<p>On many systems Fortran <code class="code">write</code> and <code class="code">print</code> statements can be
used, but the output may not interleave well with that of C, and may be
invisible on <abbr class="acronym">GUI</abbr> interfaces.  They are not portable and best
avoided.
</p>
<p>Some subroutines are provided to ease the output of information from
Fortran code.
</p>
<a class="index-entry-id" id="index-dblepr"></a>
<a class="index-entry-id" id="index-realpr"></a>
<a class="index-entry-id" id="index-intpr"></a>
<div class="example">
<div class="group"><pre class="example-preformatted">subroutine dblepr(<var class="var">label</var>, <var class="var">nchar</var>, <var class="var">data</var>, <var class="var">ndata</var>)
subroutine realpr(<var class="var">label</var>, <var class="var">nchar</var>, <var class="var">data</var>, <var class="var">ndata</var>)
subroutine intpr (<var class="var">label</var>, <var class="var">nchar</var>, <var class="var">data</var>, <var class="var">ndata</var>)
</pre></div></div>

<p>and from R&nbsp;4.0.0,
<a class="index-entry-id" id="index-labelpr"></a>
<a class="index-entry-id" id="index-dblepr1"></a>
<a class="index-entry-id" id="index-realpr1"></a>
<a class="index-entry-id" id="index-intpr1"></a>
</p><div class="example">
<div class="group"><pre class="example-preformatted">subroutine labelpr(<var class="var">label</var>, <var class="var">nchar</var>)
subroutine dblepr1(<var class="var">label</var>, <var class="var">nchar</var>, <var class="var">var</var>)
subroutine realpr1(<var class="var">label</var>, <var class="var">nchar</var>, <var class="var">var</var>)
subroutine intpr1 (<var class="var">label</var>, <var class="var">nchar</var>, <var class="var">var</var>)
</pre></div></div>

<p>Here <var class="var">label</var> is a character label of up to 255 characters,
<var class="var">nchar</var> is its length (which can be <code class="code">-1</code> if the whole label is
to be used), <var class="var">data</var> is an array of length at least <var class="var">ndata</var> of
the appropriate type (<code class="code">double precision</code>, <code class="code">real</code> and
<code class="code">integer</code> respectively) and <var class="var">var</var> is a (scalar) variable.
These routines print the label on one line and then print <var class="var">data</var> or
<var class="var">var</var> as if it were an R vector on subsequent line(s).  Note that
some compilers will give an error or warning unless <var class="var">data</var> is an
array: others will accept a scalar when <var class="var">ndata</var> has value one or
zero.  <strong class="strong">NB:</strong> There is no check on the type of <var class="var">data</var> or
<var class="var">var</var>, so using <code class="code">real</code> (including a real constant) instead of
<code class="code">double precision</code> will give incorrect answers.
</p>
<p><code class="code">intpr</code> works with zero <var class="var">ndata</var> so can be used to print a
label in earlier versions of R.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Calling-C-from-Fortran-and-vice-versa">
<div class="nav-panel">
<p>
Next: <a href="#Numerical-analysis-subroutines" accesskey="n" rel="next">Numerical analysis subroutines</a>, Previous: <a href="#Printing" accesskey="p" rel="prev">Printing</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Calling-C-from-Fortran-and-vice-versa-1"><span>6.6 Calling C from Fortran and vice versa<a class="copiable-link" href="#Calling-C-from-Fortran-and-vice-versa-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Calling-C-from-Fortran-and-vice-versa"></a>

<p>Naming conventions for symbols generated by Fortran differ by platform:
it is not safe to assume that Fortran names appear to C with a trailing
underscore.  To help cover up the platform-specific differences there is
a set of macros<a class="footnote" id="DOCF165" href="#FOOT165"><sup>165</sup></a> that should be used.
</p>
<dl class="table">
<dt><code class="code">F77_SUB(<var class="var">name</var>)</code></dt>
<dd><p>to define a function in C to be called from Fortran
</p></dd>
<dt><code class="code">F77_NAME(<var class="var">name</var>)</code></dt>
<dd><p>to declare a Fortran routine in C before use
</p></dd>
<dt><code class="code">F77_CALL(<var class="var">name</var>)</code></dt>
<dd><p>to call a Fortran routine from C
</p></dd>
<dt><code class="code">F77_COMDECL(<var class="var">name</var>)</code></dt>
<dd><p>to declare a Fortran common block in C
</p></dd>
<dt><code class="code">F77_COM(<var class="var">name</var>)</code></dt>
<dd><p>to access a Fortran common block from C
</p></dd>
</dl>

<p>On most current platforms these are all the same, but it is unwise to
rely on this.  Note that names containing underscores were not legal in
Fortran 77, and are not portably handled by the above macros.  (Also,
all Fortran names for use by R are lower case, but this is not
enforced by the macros.)
</p>
<p>For example, suppose we want to call R&rsquo;s normal random numbers from
Fortran.  We need a C wrapper along the lines of
</p>
<a class="index-entry-id" id="index-Random-numbers-in-Fortran"></a>
<div class="example">
<div class="group"><pre class="example-preformatted">#include &lt;R.h&gt;

void F77_SUB(rndstart)(void) { GetRNGstate(); }
void F77_SUB(rndend)(void) { PutRNGstate(); }
double F77_SUB(normrnd)(void) { return norm_rand(); }
</pre></div></div>

<p>to be called from Fortran as in
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">      subroutine testit()
      double precision normrnd, x
      call rndstart()
      x = normrnd()
      call dblepr(&quot;X was&quot;, 5, x, 1)
      call rndend()
      end
</pre></div></div>

<p>Note that this is not guaranteed to be portable, for the return
conventions might not be compatible between the C and Fortran compilers
used.  (Passing values <em class="emph">via</em> arguments is safer.)
</p>
<p>The standard packages, for example <strong class="strong">stats</strong>, are a rich source of
further examples.
</p>
<p>Where supported, <em class="emph">link time optimization</em> provides a reliable way
to check the consistency of calls to C from Fortran or <em class="emph">vice
versa</em>.
See <a class="xref" href="#Using-Link_002dtime-Optimization">Using Link-time Optimization</a>.
One place where this occurs is the registration of <code class="code">.Fortran</code> calls
in C code (see <a class="pxref" href="#Registering-native-routines">Registering native routines</a>).  For example
</p><div class="example">
<pre class="example-preformatted">init.c:10:13: warning: type of ‘vsom_’ does not match original
 declaration [-Wlto-type-mismatch]
  extern void F77_NAME(vsom)(void *, void *, void *, void *, 
    void *, void *, void *, void *, void *);
vsom.f90:20:33: note: type mismatch in parameter 9
   subroutine vsom(neurons,dt,dtrows,dtcols,xdim,ydim,alpha,train)
vsom.f90:20:33: note: ‘vsom’ was previously declared here
</pre></div>
<p>shows that a subroutine has been registered with 9 arguments (as that is
what the <code class="code">.Fortran</code> call used) but only has 8.
</p>

<ul class="mini-toc">
<li><a href="#Fortran-character-strings" accesskey="1">Fortran character strings</a></li>
<li><a href="#Fortran-LOGICAL" accesskey="2">Fortran LOGICAL</a></li>
<li><a href="#Passing-functions" accesskey="3">Passing functions</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Fortran-character-strings">
<div class="nav-panel">
<p>
Next: <a href="#Fortran-LOGICAL" accesskey="n" rel="next">Fortran LOGICAL</a>, Previous: <a href="#Calling-C-from-Fortran-and-vice-versa" accesskey="p" rel="prev">Calling C from Fortran and vice versa</a>, Up: <a href="#Calling-C-from-Fortran-and-vice-versa" accesskey="u" rel="up">Calling C from Fortran and vice versa</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Fortran-character-strings-1"><span>6.6.1 Fortran character strings<a class="copiable-link" href="#Fortran-character-strings-1"> &para;</a></span></h4>

<p>Passing character strings from C to Fortran or <em class="emph">vice versa</em> is
not portable, but can be done with care.  The internal representations
are different: a character array in C (or C++) is <abbr class="abbr">NUL</abbr>-terminated so its
length can be computed by <code class="code">strlen</code>.  Fortran character arrays are
typically stored as an array of bytes and a length.  This matters when
passing strings from C to Fortran or <em class="emph">vice versa</em>: in many cases
one has been able to get away with passing the string but not the
length.  However, in 2019 this changed for <code class="command">gfortran</code>, starting
with version 9 but backported to versions 7 and 8.  Several months
later, <code class="command">gfortran</code> 9.2 introduced an option
</p><div class="example">
<pre class="example-preformatted">-ftail-call-workaround
</pre></div>
<p>and made it the current default but said it might be withdrawn in future.
</p>
<p>Suppose we want a function to report a message from Fortran to R&rsquo;s
console (one could use <code class="code">labelpr</code>, or <code class="code">intpr</code> with dummy data,
but this might be the basis of a custom reporting function).  Suppose the
equivalent in Fortran would be
</p><div class="example">
<pre class="example-preformatted">      subroutine rmsg(msg)
      character*(*) msg
      print *.msg
      end
</pre></div>
<p>in file <samp class="file">rmsg.f</samp>. Using <code class="command">gfortran</code> 9.2 and later we can
extract the C view by
</p><div class="example">
<pre class="example-preformatted">gfortran -c -fc-prototypes-external rmsg.f
</pre></div>
<p>which gives
</p><div class="example">
<pre class="example-preformatted">void rmsg_ (char *msg, size_t msg_len);
</pre></div>
<p>(where <code class="code">size_t</code> applies to version 8 and later).  We could re-write
that portably in C as
</p><div class="example">
<pre class="example-preformatted">#ifndef USE_FC_LEN_T
# define USE_FC_LEN_T
#endif
#include &lt;Rconfig.h&gt; // included by R.h, so define USE_FC_LEN_T early

void F77_NAME(rmsg)(char *msg, FC_LEN_T msg_len)
{
    char cmsg[msg_len+1];
    strncpy(cmsg, msg, msg_len);
    cmsg[msg_len] = ‘\0’; // nul-terminate the string, to be sure
    // do something with ‘cmsg’ 
}
</pre></div>
<p>in code depending on <code class="code">R(&gt;= 3.6.2)</code>.  For earlier versions of R we
could just assume that <code class="code">msg</code> is <abbr class="abbr">NUL</abbr>-terminated (not guaranteed, but
people have been getting away with it for many years), so the complete C
side might be
</p><div class="example">
<pre class="example-preformatted">#ifndef USE_FC_LEN_T
# define USE_FC_LEN_T
#endif
#include &lt;Rconfig.h&gt;

#ifdef FC_LEN_T
void F77_NAME(rmsg)(char *msg, FC_LEN_T msg_len)
{
    char cmsg[msg_len+1];
    strncpy(cmsg, msg, msg_len);
    cmsg[msg_len] = ‘\0’;
    // do something with ‘cmsg’ 
}
#else
void F77_NAME(rmsg)(char *msg)
{
    // do something with ‘msg’ 
}
#endif
</pre></div>
<p>(<code class="code">USE_FC_LEN_T</code> is the default as from R 4.3.0.)
</p>

<p>An alternative is to use Fortran 2003 features to set up the Fortran
routine to pass a C-compatible character string.  We could use something
like
</p><div class="example">
<pre class="example-preformatted">      module cfuncs
        use iso_c_binding, only: c_char, c_null_char
        interface
          subroutine cmsg(msg) bind(C, name = ‘cmsg’)
            use iso_c_binding, only: c_char
            character(kind = c_char):: msg(*)
          end subroutine cmsg
        end interface
      end module

      subroutine rmsg(msg)
        use cfuncs
        character(*) msg
        call cmsg(msg//c_null_char) ! need to concatenate a nul terminator
      end subroutine rmsg
</pre></div>
<p>where the C side is simply
</p><div class="example">
<pre class="example-preformatted">void cmsg(const char *msg)
{
    // do something with nul-terminated string ‘msg’
}
</pre></div>

<p>If you use <code class="code">bind</code> to a C function as here, the only way to check
that the bound definition is correct is to compile the package with <abbr class="abbr">LTO</abbr>
(which requires compatible C and Fortran compilers, usually
<code class="command">gcc</code> and <code class="command">gfortran</code>).
</p>
<p>Passing a variable-length string from C to Fortran is trickier, but
<a class="uref" href="https://www.intel.com/content/www/us/en/docs/fortran-compiler/developer-guide-reference/2023-0/bind-c.html">https://www.intel.com/content/www/us/en/docs/fortran-compiler/developer-guide-reference/2023-0/bind-c.html</a>
provides a recipe.  However, all the uses in BLAS and LAPACK are of a
single character, and for these we can write a wrapper in Fortran
along the lines of
</p><div class="example">
<pre class="example-preformatted">      subroutine c_dgemm(transa, transb, m, n, k, alpha,
     +     a, lda, b, ldb, beta, c, ldc)
     +     bind(C, name = ‘Cdgemm’)
        use iso_c_binding, only : c_char, c_int, c_double
        character(c_char), intent(in) :: transa, transb
        integer(c_int), intent(in) :: m, n, k, lda, ldb, ldc
        real(c_double), intent(in) :: alpha, beta, a(lda, *), b(ldb, *)
        real(c_double), intent(out) ::  c(ldc, *)
        call dgemm(transa, transb, m, n, k, alpha,
     +             a, lda, b, ldb, beta, c, ldc)
      end subroutine c_dgemm
</pre></div>
<p>which is then called from C with declaration
</p><div class="example">
<pre class="example-preformatted">void
Cdgemm(const char *transa, const char *transb, const int *m,
       const int *n, const int *k, const double *alpha,
       const double *a, const int *lda, const double *b, const int *ldb,
       const double *beta, double *c, const int *ldc);
</pre></div>

<p>Alternatively, do as R does as from version 3.6.2 and pass
the character length(s) from C to Fortran. A portable way to do this is
</p><div class="example">
<pre class="example-preformatted">// before any R headers, or define in PKG_CPPFLAGS
#ifndef  USE_FC_LEN_T
# define USE_FC_LEN_T
#endif
#include &lt;Rconfig.h&gt;
#include &lt;R_ext/BLAS.h&gt;
#ifndef FCONE
# define FCONE
#endif
...
        F77_CALL(dgemm)(&quot;N&quot;, &quot;T&quot;, &amp;nrx, &amp;ncy, &amp;ncx, &amp;one, x, 
                        &amp;nrx, y, &amp;nry, &amp;zero, z, &amp;nrx FCONE FCONE);
</pre></div>
<p>(Note there is no comma before or between the <code class="code">FCONE</code> invocations.)
It is strongly recommended that packages which call from C/C++
BLAS/LAPACK routines with character arguments adopt this approach:
packages not using will fail to install as from R 4.3.0.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Fortran-LOGICAL">
<div class="nav-panel">
<p>
Next: <a href="#Passing-functions" accesskey="n" rel="next">Passing functions</a>, Previous: <a href="#Fortran-character-strings" accesskey="p" rel="prev">Fortran character strings</a>, Up: <a href="#Calling-C-from-Fortran-and-vice-versa" accesskey="u" rel="up">Calling C from Fortran and vice versa</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Fortran-LOGICAL-1"><span>6.6.2 Fortran LOGICAL<a class="copiable-link" href="#Fortran-LOGICAL-1"> &para;</a></span></h4>

<p>Passing Fortran LOGICAL variables to/from C/C++ is potentially
compiler-dependent.  Fortran compilers have long used a 32-bit integer
type so it is pretty portable to use <code class="code">int *</code> on the C/C++ side.
However, recent versions of <code class="command">gfortran</code> <em class="emph">via</em> the option
<samp class="option">-fc-prototypes-external</samp> say the C equivalent is
<code class="code">int_least32_t *</code>: &lsquo;Link-Time Optimization&rsquo; will report <code class="code">int
*</code> as a mismatch. It is possible to use <code class="code">iso_c_binding</code> in Fortran
2003 to map LOGICAL variables to the C99 type <code class="code">_Bool</code>, but it is
usually simpler to pass integers to and fro.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Passing-functions">
<div class="nav-panel">
<p>
Previous: <a href="#Fortran-LOGICAL" accesskey="p" rel="prev">Fortran LOGICAL</a>, Up: <a href="#Calling-C-from-Fortran-and-vice-versa" accesskey="u" rel="up">Calling C from Fortran and vice versa</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Passing-functions-1"><span>6.6.3 Passing functions<a class="copiable-link" href="#Passing-functions-1"> &para;</a></span></h4>

<p>A number of packages call C functions passed as arguments to Fortran
code along the lines of
</p>
<div class="example">
<pre class="example-preformatted">c         subroutine fcn(m,n,x,fvec,iflag)
c         integer m,n,iflag
c         double precision x(n),fvec(m)
...
      subroutine lmdif(fcn, ...
</pre></div>

<p>where the C declaration and call are
</p>
<div class="example">
<pre class="example-preformatted">void fcn_lmdif(int *m, int *n, double *par, double *fvec, int *iflag);

void F77_NAME(lmdif)(void (*fcn_lmdif)(int *m, int *n, double *par,
                                       double *fvec, int *iflag), ...

F77_CALL(lmdif)(&amp;fcn_lmdif, ...
</pre></div>

<p>This works on most platforms but depends on the C and Fortran compilers
agreeing on calling conventions: this have been seen to fail.  The most
portable solution seems to be to convert the Fortran code to C, perhaps
using <code class="command">f2c</code>.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Numerical-analysis-subroutines">
<div class="nav-panel">
<p>
Next: <a href="#Optimization" accesskey="n" rel="next">Optimization</a>, Previous: <a href="#Calling-C-from-Fortran-and-vice-versa" accesskey="p" rel="prev">Calling C from Fortran and vice versa</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Numerical-analysis-subroutines-1"><span>6.7 Numerical analysis subroutines<a class="copiable-link" href="#Numerical-analysis-subroutines-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Numerical-analysis-subroutines-from-C"></a>

<p>R contains a large number of mathematical functions for its own use,
for example numerical linear algebra computations and special functions.
</p>
<p>The header files <samp class="file">R_ext/BLAS.h</samp>, <samp class="file">R_ext/Lapack.h</samp> and
<samp class="file">R_ext/Linpack.h</samp> contains declarations of the BLAS, LAPACK and
LINPACK linear algebra functions included in R.  These are expressed
as calls to Fortran subroutines, and they will also be usable from
users&rsquo; Fortran code.  Although not part of the official <abbr class="acronym">API</abbr>,
this set of subroutines is unlikely to change (but might be
supplemented).
</p>
<p>The header file <samp class="file">Rmath.h</samp> lists many other functions that are
available and documented in the following subsections. Many of these are
C interfaces to the code behind R functions, so the R function
documentation may give further details.
</p>

<ul class="mini-toc">
<li><a href="#Distribution-functions" accesskey="1">Distribution functions</a></li>
<li><a href="#Mathematical-functions" accesskey="2">Mathematical functions</a></li>
<li><a href="#Numerical-Utilities" accesskey="3">Numerical Utilities</a></li>
<li><a href="#Mathematical-constants" accesskey="4">Mathematical constants</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Distribution-functions">
<div class="nav-panel">
<p>
Next: <a href="#Mathematical-functions" accesskey="n" rel="next">Mathematical functions</a>, Previous: <a href="#Numerical-analysis-subroutines" accesskey="p" rel="prev">Numerical analysis subroutines</a>, Up: <a href="#Numerical-analysis-subroutines" accesskey="u" rel="up">Numerical analysis subroutines</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Distribution-functions-1"><span>6.7.1 Distribution functions<a class="copiable-link" href="#Distribution-functions-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-Distribution-functions-from-C"></a>

<p>The routines used to calculate densities, cumulative distribution
functions and quantile functions for the standard statistical
distributions are available as entry points.
</p>
<p>The arguments for the entry points follow the pattern of those for the
normal distribution:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">double dnorm(double <var class="var">x</var>, double <var class="var">mu</var>, double <var class="var">sigma</var>, int <var class="var">give_log</var>);
double pnorm(double <var class="var">x</var>, double <var class="var">mu</var>, double <var class="var">sigma</var>, int <var class="var">lower_tail</var>,
             int <var class="var">give_log</var>);
double qnorm(double <var class="var">p</var>, double <var class="var">mu</var>, double <var class="var">sigma</var>, int <var class="var">lower_tail</var>,
             int <var class="var">log_p</var>);
double rnorm(double <var class="var">mu</var>, double <var class="var">sigma</var>);
</pre></div></div>

<p>That is, the first argument gives the position for the density and CDF
and probability for the quantile function, followed by the
distribution&rsquo;s parameters.  Argument <var class="var">lower_tail</var> should be
<code class="code">TRUE</code> (or <code class="code">1</code>) for normal use, but can be <code class="code">FALSE</code> (or
<code class="code">0</code>) if the probability of the upper tail is desired or specified.
</p>
<p>Finally, <var class="var">give_log</var> should be non-zero if the result is required on
log scale, and <var class="var">log_p</var> should be non-zero if <var class="var">p</var> has been
specified on log scale.
</p>
<p>Note that you directly get the cumulative (or &ldquo;integrated&rdquo;)
<em class="emph">hazard</em> function, H(t) = - log(1 -
F(t)), by using
</p>
<div class="example">
<pre class="example-preformatted">- p<var class="var">dist</var>(t, ..., /*lower_tail = */ FALSE, /* give_log = */ TRUE)
</pre></div>

<p>or shorter (and more cryptic) <code class="code">- p<var class="var">dist</var>(t, ..., 0, 1)</code>.
<a class="index-entry-id" id="index-cumulative-hazard"></a>
</p>
<p>The random-variate generation routine <code class="code">rnorm</code> returns one normal
variate. See <a class="xref" href="#Random-numbers">Random number generation</a>, for the protocol in using the
random-variate routines.
<a class="index-entry-id" id="index-Random-numbers-in-C-1"></a>
</p>
<p>Note that these argument sequences are (apart from the names and that
<code class="code">rnorm</code> has no <var class="var">n</var>) mainly the same as the corresponding R
functions of the same name, so the documentation of the R functions
can be used.  Note that the exponential and gamma distributions are
parametrized by <code class="code">scale</code> rather than <code class="code">rate</code>.
</p>

<p>For reference, the following table gives the basic name (to be prefixed
by &lsquo;<samp class="samp">d</samp>&rsquo;, &lsquo;<samp class="samp">p</samp>&rsquo;, &lsquo;<samp class="samp">q</samp>&rsquo; or &lsquo;<samp class="samp">r</samp>&rsquo; apart from the exceptions
noted) and distribution-specific arguments for the complete set of
distributions.
</p>
<blockquote class="quotation">
<table summary="" class="multitable">
<tbody><tr><td width="28%">beta</td><td width="22%"><code class="code">beta</code></td><td width="30%"><code class="code">a</code>, <code class="code">b</code></td></tr>
<tr><td width="28%">non-central beta</td><td width="22%"><code class="code">nbeta</code></td><td width="30%"><code class="code">a</code>, <code class="code">b</code>, <code class="code">ncp</code></td></tr>
<tr><td width="28%">binomial</td><td width="22%"><code class="code">binom</code></td><td width="30%"><code class="code">n</code>, <code class="code">p</code></td></tr>
<tr><td width="28%">Cauchy</td><td width="22%"><code class="code">cauchy</code></td><td width="30%"><code class="code">location</code>, <code class="code">scale</code></td></tr>
<tr><td width="28%">chi-squared</td><td width="22%"><code class="code">chisq</code></td><td width="30%"><code class="code">df</code></td></tr>
<tr><td width="28%">non-central chi-squared</td><td width="22%"><code class="code">nchisq</code></td><td width="30%"><code class="code">df</code>, <code class="code">ncp</code></td></tr>
<tr><td width="28%">exponential</td><td width="22%"><code class="code">exp</code></td><td width="30%"><code class="code">scale</code> (and <strong class="strong">not</strong> <code class="code">rate</code>)</td></tr>
<tr><td width="28%">F</td><td width="22%"><code class="code">f</code></td><td width="30%"><code class="code">n1</code>, <code class="code">n2</code></td></tr>
<tr><td width="28%">non-central F</td><td width="22%"><code class="code">nf</code></td><td width="30%"><code class="code">n1</code>, <code class="code">n2</code>, <code class="code">ncp</code></td></tr>
<tr><td width="28%">gamma</td><td width="22%"><code class="code">gamma</code></td><td width="30%"><code class="code">shape</code>, <code class="code">scale</code></td></tr>
<tr><td width="28%">geometric</td><td width="22%"><code class="code">geom</code></td><td width="30%"><code class="code">p</code></td></tr>
<tr><td width="28%">hypergeometric</td><td width="22%"><code class="code">hyper</code></td><td width="30%"><code class="code">NR</code>, <code class="code">NB</code>, <code class="code">n</code></td></tr>
<tr><td width="28%">logistic</td><td width="22%"><code class="code">logis</code></td><td width="30%"><code class="code">location</code>, <code class="code">scale</code></td></tr>
<tr><td width="28%">lognormal</td><td width="22%"><code class="code">lnorm</code></td><td width="30%"><code class="code">logmean</code>, <code class="code">logsd</code></td></tr>
<tr><td width="28%">negative binomial</td><td width="22%"><code class="code">nbinom</code></td><td width="30%"><code class="code">size</code>, <code class="code">prob</code></td></tr>
<tr><td width="28%">normal</td><td width="22%"><code class="code">norm</code></td><td width="30%"><code class="code">mu</code>, <code class="code">sigma</code></td></tr>
<tr><td width="28%">Poisson</td><td width="22%"><code class="code">pois</code></td><td width="30%"><code class="code">lambda</code></td></tr>
<tr><td width="28%">Student&rsquo;s t</td><td width="22%"><code class="code">t</code></td><td width="30%"><code class="code">n</code></td></tr>
<tr><td width="28%">non-central t</td><td width="22%"><code class="code">nt</code></td><td width="30%"><code class="code">df</code>, <code class="code">delta</code></td></tr>
<tr><td width="28%">Studentized range</td><td width="22%"><code class="code">tukey</code> (*)</td><td width="30%"><code class="code">rr</code>, <code class="code">cc</code>, <code class="code">df</code></td></tr>
<tr><td width="28%">uniform</td><td width="22%"><code class="code">unif</code></td><td width="30%"><code class="code">a</code>, <code class="code">b</code></td></tr>
<tr><td width="28%">Weibull</td><td width="22%"><code class="code">weibull</code></td><td width="30%"><code class="code">shape</code>, <code class="code">scale</code></td></tr>
<tr><td width="28%">Wilcoxon rank sum</td><td width="22%"><code class="code">wilcox</code></td><td width="30%"><code class="code">m</code>, <code class="code">n</code></td></tr>
<tr><td width="28%">Wilcoxon signed rank</td><td width="22%"><code class="code">signrank</code></td><td width="30%"><code class="code">n</code></td></tr>
</tbody>
</table>
</blockquote>

<p>Entries marked with an asterisk only have &lsquo;<samp class="samp">p</samp>&rsquo; and &lsquo;<samp class="samp">q</samp>&rsquo;
functions available, and none of the non-central distributions have
&lsquo;<samp class="samp">r</samp>&rsquo; functions.
</p>
<p>(If remapping is suppressed, the Normal distribution names are
<code class="code">Rf_dnorm4</code>, <code class="code">Rf_pnorm5</code> and <code class="code">Rf_qnorm5</code>.)
</p>
<p>Additionally, a <em class="emph">multivariate</em> RNG for the multinomial distribution is
</p><div class="example">
<pre class="example-preformatted">void rmultinom(int n, double* prob, int K, int* rN)
</pre></div>
<p>where <code class="code">K = length(prob)</code>,
sum(prob[.]) == 1
and <code class="code">rN</code> must point to a length-<code class="code">K</code> integer vector
n1 n2 .. nK where each entry
nj=<code class="code">rN[j]</code> is &ldquo;filled&rdquo; by a random binomial from
Bin(n; prob[j]),
constrained to sum(rN[.]) == n.
</p>
<p>After calls to <code class="code">dwilcox</code>, <code class="code">pwilcox</code> or <code class="code">qwilcox</code> the
function <code class="code">wilcox_free()</code> should be called, and similarly
<code class="code">signrank_free()</code> for the signed rank functions.
<a class="index-entry-id" id="index-wilcox_005ffree"></a>
<a class="index-entry-id" id="index-signrank_005ffree"></a>
Since <code class="code">wilcox_free()</code> and <code class="code">signrank_free()</code> were only added to
<samp class="file">Rmath.h</samp> in R&nbsp; 4.2.0, their use requires something like
</p><div class="example">
<pre class="example-preformatted">#include &quot;Rmath.h&quot;
#include &quot;Rversion.h&quot;

#if R_VERSION &lt; R_Version(4, 2, 0)
extern void wilcox_free(void);
extern void signrank_free(void);
#endif
</pre></div>

<p>For the negative binomial distribution (&lsquo;<samp class="samp">nbinom</samp>&rsquo;), in addition to the
<code class="code">(size, prob)</code> parametrization, the alternative <code class="code">(size, mu)</code>
parametrization is provided as well by functions &lsquo;<samp class="samp">[dpqr]nbinom_mu()</samp>&rsquo;,
see <kbd class="kbd">?NegBinomial</kbd> in R.
</p>
<p>Functions <code class="code">dpois_raw(x, *)</code> and <code class="code">dbinom_raw(x, *)</code> are versions of the
Poisson and binomial probability mass functions which work continuously in
<code class="code">x</code>, whereas <code class="code">dbinom(x,*)</code> and <code class="code">dpois(x,*)</code> only return non
zero values for integer <code class="code">x</code>.
</p><div class="example">
<div class="group"><pre class="example-preformatted">double dbinom_raw(double x, double n, double p, double q, int give_log)
double dpois_raw (double x, double lambda, int give_log)
</pre></div></div>
<p>Note that <code class="code">dbinom_raw()</code> returns both p and q = 1-p which may be advantageous when one of them is close to 1.
</p>

<hr>
</div>
<div class="subsection-level-extent" id="Mathematical-functions">
<div class="nav-panel">
<p>
Next: <a href="#Numerical-Utilities" accesskey="n" rel="next">Numerical Utilities</a>, Previous: <a href="#Distribution-functions" accesskey="p" rel="prev">Distribution functions</a>, Up: <a href="#Numerical-analysis-subroutines" accesskey="u" rel="up">Numerical analysis subroutines</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Mathematical-functions-1"><span>6.7.2 Mathematical functions<a class="copiable-link" href="#Mathematical-functions-1"> &para;</a></span></h4>

<a class="index-entry-id" id="index-Gamma-function"></a>
<a class="index-entry-id" id="index-Polygamma-functions"></a>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-gammafn"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">gammafn</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-gammafn"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-lgammafn"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">lgammafn</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-lgammafn"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-digamma"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">digamma</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-digamma"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-trigamma"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">trigamma</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-trigamma"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-tetragamma"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">tetragamma</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-tetragamma"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-pentagamma"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">pentagamma</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-pentagamma"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-psigamma"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">psigamma</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">deriv</var>)</code><a class="copiable-link" href="#index-psigamma"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-dpsifn"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">dpsifn</strong> <code class="def-code-arguments">(double <var class="var">x</var>, int <var class="var">n</var>, int <var class="var">kode</var>, int <var class="var">m</var>, double* <var class="var">ans</var>, int* <var class="var">nz</var>, int* <var class="var">ierr</var>)</code><a class="copiable-link" href="#index-dpsifn"> &para;</a></span></dt>
<dd><p>The Gamma function, the natural logarithm of its absolute value and
first four derivatives and the n-th derivative of Psi, the digamma
function, which is the derivative of <code class="code">lgammafn</code>. In other words,
<code class="code">digamma(x)</code> is the same as <code class="code">psigamma(x,0)</code>,
<code class="code">trigamma(x) == psigamma(x,1)</code>, etc.
The underlying workhorse, <code class="code">dpsifn()</code>, is useful, e.g., when several derivatives of
log Gamma=<code class="code">lgammafn</code> are desired.  It computes and
returns in <code class="code">ans[]</code> the length-<var class="var">m</var> sequence 
(-1)^(k+1) / gamma(k+1) * psi(k;x) for
k = n ... n+m-1, where psi(k;x)
is the k-th derivative of Psi(x), i.e.,
<code class="code">psigamma(x,k)</code>.  For more details, see the comments in
<samp class="file">src/nmath/polygamma.c</samp>.
</p></dd></dl>

<a class="index-entry-id" id="index-Beta-function"></a>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-beta"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">beta</strong> <code class="def-code-arguments">(double <var class="var">a</var>, double <var class="var">b</var>)</code><a class="copiable-link" href="#index-beta"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-lbeta"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">lbeta</strong> <code class="def-code-arguments">(double <var class="var">a</var>, double <var class="var">b</var>)</code><a class="copiable-link" href="#index-lbeta"> &para;</a></span></dt>
<dd><p>The (complete) Beta function and its natural logarithm.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-choose"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">choose</strong> <code class="def-code-arguments">(double <var class="var">n</var>, double <var class="var">k</var>)</code><a class="copiable-link" href="#index-choose"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-lchoose"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">lchoose</strong> <code class="def-code-arguments">(double <var class="var">n</var>, double <var class="var">k</var>)</code><a class="copiable-link" href="#index-lchoose"> &para;</a></span></dt>
<dd><p>The number of combinations of <var class="var">k</var> items chosen from <var class="var">n</var> and
the natural logarithm of its absolute value, generalized to arbitrary real
<var class="var">n</var>.  <var class="var">k</var> is rounded to the nearest integer (with a warning if
needed).
</p></dd></dl>

<a class="index-entry-id" id="index-Bessel-functions"></a>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-bessel_005fi"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">bessel_i</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">nu</var>, double <var class="var">expo</var>)</code><a class="copiable-link" href="#index-bessel_005fi"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-bessel_005fj"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">bessel_j</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">nu</var>)</code><a class="copiable-link" href="#index-bessel_005fj"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-bessel_005fk"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">bessel_k</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">nu</var>, double <var class="var">expo</var>)</code><a class="copiable-link" href="#index-bessel_005fk"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-bessel_005fy"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">bessel_y</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">nu</var>)</code><a class="copiable-link" href="#index-bessel_005fy"> &para;</a></span></dt>
<dd><p>Bessel functions of types I, J, K and Y with index <var class="var">nu</var>.  For
<code class="code">bessel_i</code> and <code class="code">bessel_k</code> there is the option to return
exp(-<var class="var">x</var>)&nbsp;I(<var class="var">x</var>;&nbsp;<var class="var">nu</var>)<!-- /@w --> or exp(<var class="var">x</var>)&nbsp;K(<var class="var">x</var>;&nbsp;<var class="var">nu</var>)<!-- /@w --> if <var class="var">expo</var> is 2. (Use <code class="code"><var class="var">expo</var> == 1</code> for unscaled
values.)
</p></dd></dl>


<hr>
</div>
<div class="subsection-level-extent" id="Numerical-Utilities">
<div class="nav-panel">
<p>
Next: <a href="#Mathematical-constants" accesskey="n" rel="next">Mathematical constants</a>, Previous: <a href="#Mathematical-functions" accesskey="p" rel="prev">Mathematical functions</a>, Up: <a href="#Numerical-analysis-subroutines" accesskey="u" rel="up">Numerical analysis subroutines</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Numerical-Utilities-1"><span>6.7.3 Numerical Utilities<a class="copiable-link" href="#Numerical-Utilities-1"> &para;</a></span></h4>
<p>There are a few other numerical utility functions available as entry points.
</p>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fpow"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">R_pow</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">y</var>)</code><a class="copiable-link" href="#index-R_005fpow"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fpow_005fdi"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">R_pow_di</strong> <code class="def-code-arguments">(double <var class="var">x</var>, int <var class="var">i</var>)</code><a class="copiable-link" href="#index-R_005fpow_005fdi"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-pow1p"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">pow1p</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">y</var>)</code><a class="copiable-link" href="#index-pow1p"> &para;</a></span></dt>
<dd><p><code class="code">R_pow(<var class="var">x</var>, <var class="var">y</var>)</code> and <code class="code">R_pow_di(<var class="var">x</var>, <var class="var">i</var>)</code>
compute <code class="code"><var class="var">x</var>^<var class="var">y</var></code> and <code class="code"><var class="var">x</var>^<var class="var">i</var></code>, respectively
using <code class="code">R_FINITE</code> checks and returning the proper result (the same
as R) for the cases where <var class="var">x</var>, <var class="var">y</var> or <var class="var">i</var> are 0 or
missing or infinite or <code class="code">NaN</code>.
</p>
<p><code class="code">pow1p(<var class="var">x</var>, <var class="var">y</var>)</code> computes <code class="code">(1 + <var class="var">x</var>)^<var class="var">y</var></code>, accurately
even for small <var class="var">x</var>, i.e., |x| &lt;&lt; 1. 
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-log1p"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">log1p</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-log1p"> &para;</a></span></dt>
<dd><p>Computes <code class="code">log(1 + <var class="var">x</var>)</code> (<em class="emph">log 1 <b class="b">p</b>lus x</em>), accurately
even for small <var class="var">x</var>, i.e., |x| &lt;&lt; 1.
</p>
<p>This should be provided by your platform, in which case it is not
included in <samp class="file">Rmath.h</samp>, but is (probably) in <samp class="file">math.h</samp> which
<samp class="file">Rmath.h</samp> includes (except under C++, so it may not be declared for
C++98).
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-log1pmx"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">log1pmx</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-log1pmx"> &para;</a></span></dt>
<dd><p>Computes <code class="code">log(1 + <var class="var">x</var>) - <var class="var">x</var></code> (<em class="emph">log 1 <b class="b">p</b>lus x <b class="b">m</b>inus <b class="b">x</b></em>),
accurately even for small <var class="var">x</var>, i.e., |x| &lt;&lt; 1.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-log1pexp"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">log1pexp</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-log1pexp"> &para;</a></span></dt>
<dd><p>Computes <code class="code">log(1 + exp(<var class="var">x</var>))</code> (<em class="emph">log 1 <b class="b">p</b>lus <b class="b">exp</b></em>),
accurately, notably for large <var class="var">x</var>, e.g., x &gt; 720.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-log1mexp"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">log1mexp</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-log1mexp"> &para;</a></span></dt>
<dd><p>Computes <code class="code">log(1 - exp(<var class="var">-x</var>))</code> (<em class="emph">log 1 <b class="b">m</b>inus <b class="b">exp</b></em>),
accurately, carefully for two regions of <var class="var">x</var>, optimally cutting
off at log 2 (= 0.693147..), using
<code class="code">((-x) &gt; -M_LN2 ? log(-expm1(-x)) : log1p(-exp(-x)))</code>.
</p></dd></dl>


<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-expm1"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">expm1</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-expm1"> &para;</a></span></dt>
<dd><p>Computes <code class="code">exp(<var class="var">x</var>) - 1</code> (<em class="emph">exp x <b class="b">m</b>inus 1</em>), accurately
even for small <var class="var">x</var>, i.e., |x| &lt;&lt; 1.
</p>
<p>This should be provided by your platform, in which case it is not
included in <samp class="file">Rmath.h</samp>, but is (probably) in <samp class="file">math.h</samp> which
<samp class="file">Rmath.h</samp> includes (except under C++, so it may not be declared for
C++98).
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-lgamma1p"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">lgamma1p</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-lgamma1p"> &para;</a></span></dt>
<dd><p>Computes <code class="code">log(gamma(<var class="var">x</var> + 1))</code> (<em class="emph">log(gamma(1 <b class="b">p</b>lus x))</em>),
accurately even for small <var class="var">x</var>, i.e., 0 &lt; x &lt; 0.5.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-cospi"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">cospi</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-cospi"> &para;</a></span></dt>
<dd><p>Computes <code class="code">cos(pi * x)</code> (where <code class="code">pi</code> is 3.14159...),
accurately, notably for half integer <var class="var">x</var>.
</p>
<p>This might be provided by your platform<a class="footnote" id="DOCF166" href="#FOOT166"><sup>166</sup></a>, in which case it is not included in <samp class="file">Rmath.h</samp>, but is
in <samp class="file">math.h</samp> which <samp class="file">Rmath.h</samp> includes.  (Ensure that
neither <samp class="file">math.h</samp> nor <samp class="file">cmath</samp> is included before
<samp class="file">Rmath.h</samp> or define
</p><div class="example">
<pre class="example-preformatted">#define __STDC_WANT_IEC_60559_FUNCS_EXT__ 1
</pre></div>
<p>before the first inclusion.)
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-sinpi"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">sinpi</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-sinpi"> &para;</a></span></dt>
<dd><p>Computes <code class="code">sin(pi * x)</code> accurately, notably for (half) integer <var class="var">x</var>.
</p>
<p>This might be provided by your platform, in which case it is not
included in <samp class="file">Rmath.h</samp>, but is in <samp class="file">math.h</samp> which <samp class="file">Rmath.h</samp>
includes (but see the comments for <code class="code">cospi</code>).
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-Rtanpi"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">Rtanpi</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-Rtanpi"> &para;</a></span></dt>
<dd><p>Computes <code class="code">tan(pi * x)</code> accurately, notably for integer <var class="var">x</var>, giving
<var class="var">NaN</var> for half integer <var class="var">x</var> and exactly +1 or -1 for (non half)
quarter integers.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-tanpi"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">tanpi</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-tanpi"> &para;</a></span></dt>
<dd><p>Computes <code class="code">tan(pi * x)</code> accurately for integer <var class="var">x</var> with possibly
platform dependent behavior for half (and quarter) integers.
This might be provided by your platform, in which case it is not included
in <samp class="file">Rmath.h</samp>, but is in <samp class="file">math.h</samp> which <samp class="file">Rmath.h</samp> includes
(but see the comments for <code class="code">cospi</code>).
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-logspace_005fadd"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">logspace_add</strong> <code class="def-code-arguments">(double <var class="var">logx</var>, double <var class="var">logy</var>)</code><a class="copiable-link" href="#index-logspace_005fadd"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-logspace_005fsub"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">logspace_sub</strong> <code class="def-code-arguments">(double <var class="var">logx</var>, double <var class="var">logy</var>)</code><a class="copiable-link" href="#index-logspace_005fsub"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-logspace_005fsum"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">logspace_sum</strong> <code class="def-code-arguments">(const double* <var class="var">logx</var>, int <var class="var">n</var>)</code><a class="copiable-link" href="#index-logspace_005fsum"> &para;</a></span></dt>
<dd><p>Compute the log of a sum or difference from logs of terms, i.e., &ldquo;x +
y&rdquo; as <code class="code">log (exp(<var class="var">logx</var>) + exp(<var class="var">logy</var>))</code> and &ldquo;x - y&rdquo; as
<code class="code">log (exp(<var class="var">logx</var>) - exp(<var class="var">logy</var>))</code>,
and &ldquo;sum_i x[i]&rdquo; as <code class="code">log (sum[i = 1:<var class="var">n</var> exp(<var class="var">logx</var>[i])] )</code>
without causing unnecessary overflows or throwing away too much accuracy.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-imax2"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">imax2</strong> <code class="def-code-arguments">(int <var class="var">x</var>, int <var class="var">y</var>)</code><a class="copiable-link" href="#index-imax2"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-imin2"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">imin2</strong> <code class="def-code-arguments">(int <var class="var">x</var>, int <var class="var">y</var>)</code><a class="copiable-link" href="#index-imin2"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-fmax2"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">fmax2</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">y</var>)</code><a class="copiable-link" href="#index-fmax2"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-fmin2"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">fmin2</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">y</var>)</code><a class="copiable-link" href="#index-fmin2"> &para;</a></span></dt>
<dd><p>Return the larger (<code class="code">max</code>) or smaller (<code class="code">min</code>) of two integer or
double numbers, respectively.  Note that <code class="code">fmax2</code> and <code class="code">fmin2</code>
differ from C99/C++11&rsquo;s <code class="code">fmax</code> and <code class="code">fmin</code> when one of the
arguments is a <code class="code">NaN</code>: these versions return <code class="code">NaN</code>.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-sign"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">sign</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-sign"> &para;</a></span></dt>
<dd><p>Compute the <em class="emph">signum</em> function, where sign(<var class="var">x</var>) is 1, 0, or
<em class="math">-1</em>, when <var class="var">x</var> is positive, 0, or negative, respectively, and
<code class="code">NaN</code> if <code class="code">x</code> is a <code class="code">NaN</code>.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-fsign"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">fsign</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">y</var>)</code><a class="copiable-link" href="#index-fsign"> &para;</a></span></dt>
<dd><p>Performs &ldquo;transfer of sign&rdquo; and is defined as |x| * sign(y).
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-fprec"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">fprec</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">digits</var>)</code><a class="copiable-link" href="#index-fprec"> &para;</a></span></dt>
<dd><p>Returns the value of <var class="var">x</var> rounded to <var class="var">digits</var> decimal digits
(after the decimal point).
</p>
<p>This is the function used by R&rsquo;s <code class="code">signif()</code>.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-fround"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">fround</strong> <code class="def-code-arguments">(double <var class="var">x</var>, double <var class="var">digits</var>)</code><a class="copiable-link" href="#index-fround"> &para;</a></span></dt>
<dd><p>Returns the value of <var class="var">x</var> rounded to <var class="var">digits</var> <em class="emph">significant</em>
decimal digits.
</p>
<p>This is the function used by R&rsquo;s <code class="code">round()</code>.  (Note that C99/C++11
provide a <code class="code">round</code> function but C++98 need not.)
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-ftrunc"><span class="category-def">Function: </span><span><code class="def-type">double</code> <strong class="def-name">ftrunc</strong> <code class="def-code-arguments">(double <var class="var">x</var>)</code><a class="copiable-link" href="#index-ftrunc"> &para;</a></span></dt>
<dd><p>Returns the value of <var class="var">x</var> truncated (to an integer value) towards
zero.
</p></dd></dl>

<hr>
</div>
<div class="subsection-level-extent" id="Mathematical-constants">
<div class="nav-panel">
<p>
Previous: <a href="#Numerical-Utilities" accesskey="p" rel="prev">Numerical Utilities</a>, Up: <a href="#Numerical-analysis-subroutines" accesskey="u" rel="up">Numerical analysis subroutines</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Mathematical-constants-1"><span>6.7.4 Mathematical constants<a class="copiable-link" href="#Mathematical-constants-1"> &para;</a></span></h4>
<a class="index-entry-id" id="index-M_005fE"></a>
<a class="index-entry-id" id="index-M_005fPI"></a>

<p>R has a set of commonly used mathematical constants encompassing
constants defined by POSIX and usually found in headers <samp class="file">math.h</samp>
and <samp class="file">cmath</samp>, as well as further ones that are used in statistical
computations.  These are defined to (at least) 30 digits accuracy in
<samp class="file">Rmath.h</samp>.  The following definitions use <code class="code">ln(x)</code> for the
natural logarithm (<code class="code">log(x)</code> in R).
</p>
<blockquote class="quotation">
<table summary="" class="multitable">
<thead><tr><th>Name</th><th>Definition (<code class="code">ln = log</code>)</th><th>round(<em class="emph">value</em>, 7)</th></tr></thead>
<tbody><tr><td><code class="code">M_E</code></td><td><em class="math">e</em></td><td>2.7182818</td></tr>
<tr><td><code class="code">M_LOG2E</code></td><td>log2(<em class="math">e</em>)</td><td>1.4426950</td></tr>
<tr><td><code class="code">M_LOG10E</code></td><td>log10(<em class="math">e</em>)</td><td>0.4342945</td></tr>
<tr><td><code class="code">M_LN2</code></td><td>ln(2)</td><td>0.6931472</td></tr>
<tr><td><code class="code">M_LN10</code></td><td>ln(10)</td><td>2.3025851</td></tr>
<tr><td><code class="code">M_PI</code></td><td>pi</td><td>3.1415927</td></tr>
<tr><td><code class="code">M_PI_2</code></td><td>pi/2</td><td>1.5707963</td></tr>
<tr><td><code class="code">M_PI_4</code></td><td>pi/4</td><td>0.7853982</td></tr>
<tr><td><code class="code">M_1_PI</code></td><td>1/pi</td><td>0.3183099</td></tr>
<tr><td><code class="code">M_2_PI</code></td><td>2/pi</td><td>0.6366198</td></tr>
<tr><td><code class="code">M_2_SQRTPI</code></td><td>2/sqrt(pi)</td><td>1.1283792</td></tr>
<tr><td><code class="code">M_SQRT2</code></td><td>sqrt(2)</td><td>1.4142136</td></tr>
<tr><td><code class="code">M_SQRT1_2</code></td><td>1/sqrt(2)</td><td>0.7071068</td></tr>
<tr><td><code class="code">M_SQRT_3</code></td><td>sqrt(3)</td><td>1.7320508</td></tr>
<tr><td><code class="code">M_SQRT_32</code></td><td>sqrt(32)</td><td>5.6568542</td></tr>
<tr><td><code class="code">M_LOG10_2</code></td><td>log10(2)</td><td>0.3010300</td></tr>
<tr><td><code class="code">M_2PI</code></td><td>2*pi</td><td>6.2831853</td></tr>
<tr><td><code class="code">M_SQRT_PI</code></td><td>sqrt(pi)</td><td>1.7724539</td></tr>
<tr><td><code class="code">M_1_SQRT_2PI</code></td><td>1/sqrt(2*pi)</td><td>0.3989423</td></tr>
<tr><td><code class="code">M_SQRT_2dPI</code></td><td>sqrt(2/pi)</td><td>0.7978846</td></tr>
<tr><td><code class="code">M_LN_SQRT_PI</code></td><td>ln(sqrt(pi))</td><td>0.5723649</td></tr>
<tr><td><code class="code">M_LN_SQRT_2PI</code></td><td>ln(sqrt(2*pi))</td><td>0.9189385</td></tr>
<tr><td><code class="code">M_LN_SQRT_PId2</code></td><td>ln(sqrt(pi/2))</td><td>0.2257914</td></tr>
</tbody>
</table>
</blockquote>

<p>There are a set of constants (<code class="code">PI</code>, <code class="code">DOUBLE_EPS</code>) (and so on)
defined (unless <code class="code">STRICT_R_HEADERS</code> is defined) in the included
header <samp class="file">R_ext/Constants.h</samp>, mainly for compatibility with S.
All but <code class="code">PI</code> are deprecated and should be replaced by the C99/C++11
versions used in that file.
</p>
<a class="index-entry-id" id="index-TRUE"></a>
<a class="index-entry-id" id="index-FALSE"></a>
<p>Further, the included header <samp class="file">R_ext/Boolean.h</samp> has enumeration
constants <code class="code">TRUE</code> and <code class="code">FALSE</code> of type <code class="code">Rboolean</code> in
order to provide a way of using &ldquo;logical&rdquo; variables in C consistently.
This can conflict with other software: for example it conflicts with the
headers in IJG&rsquo;s <code class="code">jpeg-9</code> (but not earlier versions).
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Optimization">
<div class="nav-panel">
<p>
Next: <a href="#Integration" accesskey="n" rel="next">Integration</a>, Previous: <a href="#Numerical-analysis-subroutines" accesskey="p" rel="prev">Numerical analysis subroutines</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Optimization-1"><span>6.8 Optimization<a class="copiable-link" href="#Optimization-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-optimization"></a>

<p>The C code underlying <code class="code">optim</code> can be accessed directly.  The user
needs to supply a function to compute the function to be minimized, of
the type
</p>
<a class="index-entry-id" id="index-optimfn"></a>
<div class="example">
<pre class="example-preformatted">typedef double optimfn(int n, double *par, void *ex);
</pre></div>

<p>where the first argument is the number of parameters in the second
argument.  The third argument is a pointer passed down from the calling
routine, normally used to carry auxiliary information.
</p>
<p>Some of the methods also require a gradient function
</p>
<a class="index-entry-id" id="index-optimgr"></a>
<div class="example">
<pre class="example-preformatted">typedef void optimgr(int n, double *par, double *gr, void *ex);
</pre></div>

<p>which passes back the gradient in the <code class="code">gr</code> argument.  No function
is provided for finite-differencing, nor for approximating the Hessian
at the result.
</p>
<p>The interfaces (defined in header <samp class="file">R_ext/Applic.h</samp>) are
</p>
<ul class="itemize mark-bullet">
<li>Nelder Mead:
<a class="index-entry-id" id="index-nmmin"></a>
<div class="example">
<pre class="example-preformatted">void nmmin(int n, double *xin, double *x, double *Fmin, optimfn fn,
           int *fail, double abstol, double intol, void *ex,
           double alpha, double beta, double gamma, int trace,
           int *fncount, int maxit);
</pre></div>

</li><li>BFGS:
<a class="index-entry-id" id="index-vmmin"></a>
<div class="example">
<pre class="example-preformatted">void vmmin(int n, double *x, double *Fmin,
           optimfn fn, optimgr gr, int maxit, int trace,
           int *mask, double abstol, double reltol, int nREPORT,
           void *ex, int *fncount, int *grcount, int *fail);
</pre></div>

</li><li>Conjugate gradients:
<a class="index-entry-id" id="index-cgmin"></a>
<div class="example">
<pre class="example-preformatted">void cgmin(int n, double *xin, double *x, double *Fmin,
           optimfn fn, optimgr gr, int *fail, double abstol,
           double intol, void *ex, int type, int trace,
           int *fncount, int *grcount, int maxit);
</pre></div>

</li><li>Limited-memory BFGS with bounds:
<a class="index-entry-id" id="index-lbfgsb"></a>
<div class="example">
<pre class="example-preformatted">void lbfgsb(int n, int lmm, double *x, double *lower,
            double *upper, int *nbd, double *Fmin, optimfn fn,
            optimgr gr, int *fail, void *ex, double factr,
            double pgtol, int *fncount, int *grcount,
            int maxit, char *msg, int trace, int nREPORT);
</pre></div>

</li><li>Simulated annealing:
<a class="index-entry-id" id="index-samin"></a>
<div class="example">
<pre class="example-preformatted">void samin(int n, double *x, double *Fmin, optimfn fn, int maxit,
           int tmax, double temp, int trace, void *ex);
</pre></div>

</li></ul>

<p>Many of the arguments are common to the various methods.  <code class="code">n</code> is
the number of parameters, <code class="code">x</code> or <code class="code">xin</code> is the starting
parameters on entry and <code class="code">x</code> the final parameters on exit, with
final value returned in <code class="code">Fmin</code>.  Most of the other parameters can
be found from the help page for <code class="code">optim</code>: see the source code
<samp class="file">src/appl/lbfgsb.c</samp> for the values of <code class="code">nbd</code>, which
specifies which bounds are to be used.
</p>

<hr>
</div>
<div class="section-level-extent" id="Integration">
<div class="nav-panel">
<p>
Next: <a href="#Utility-functions" accesskey="n" rel="next">Utility functions</a>, Previous: <a href="#Optimization" accesskey="p" rel="prev">Optimization</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Integration-1"><span>6.9 Integration<a class="copiable-link" href="#Integration-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-integration"></a>

<p>The C code underlying <code class="code">integrate</code> can be accessed directly.  The
user needs to supply a <em class="emph">vectorizing</em> C function to compute the
function to be integrated, of the type
</p>
<a class="index-entry-id" id="index-integr_005ffn"></a>
<div class="example">
<pre class="example-preformatted">typedef void integr_fn(double *x, int n, void *ex);
</pre></div>

<p>where <code class="code">x[]</code> is both input and output and has length <code class="code">n</code>, i.e.,
a C function, say <code class="code">fn</code>, of type <code class="code">integr_fn</code> must basically do
<code class="code">for(i in 1:n) x[i] := f(x[i], ex)</code>.  The vectorization requirement
can be used to speed up the integrand instead of calling it <code class="code">n</code>
times.  Note that in the current implementation built on QUADPACK,
<code class="code">n</code> will be either 15 or 21.  The <code class="code">ex</code> argument is a pointer
passed down from the calling routine, normally used to carry auxiliary
information.
</p>
<p>There are interfaces (defined in header <samp class="file">R_ext/Applic.h</samp>) for
integrals over finite and infinite intervals (or &ldquo;ranges&rdquo; or
&ldquo;integration boundaries&rdquo;).
</p>
<ul class="itemize mark-bullet">
<li>Finite:
<a class="index-entry-id" id="index-Rdqags"></a>
<div class="example">
<pre class="example-preformatted">void Rdqags(integr_fn f, void *ex, double *a, double *b,
            double *epsabs, double *epsrel,
            double *result, double *abserr, int *neval, int *ier,
            int *limit, int *lenw, int *last,
            int *iwork, double *work);
</pre></div>

</li><li>Infinite:
<a class="index-entry-id" id="index-Rdqagi"></a>
<div class="example">
<pre class="example-preformatted">void Rdqagi(integr_fn f, void *ex, double *bound, int *inf,
            double *epsabs, double *epsrel,
            double *result, double *abserr, int *neval, int *ier,
            int *limit, int *lenw, int *last,
            int *iwork, double *work);
</pre></div>

</li></ul>

<p>Only the 3rd and 4th argument differ for the two integrators; for the
finite range integral using <code class="code">Rdqags</code>, <code class="code">a</code> and <code class="code">b</code> are the
integration interval bounds, whereas for an infinite range integral using
<code class="code">Rdqagi</code>, <code class="code">bound</code> is the finite bound of the integration (if
the integral is not doubly-infinite) and <code class="code">inf</code> is a code indicating
the kind of integration range,
</p>
<dl class="table">
<dt><code class="code">inf = 1</code></dt>
<dd><p>corresponds to (bound, +Inf),
</p></dd>
<dt><code class="code">inf = -1</code></dt>
<dd><p>corresponds to (-Inf, bound),
</p></dd>
<dt><code class="code">inf = 2</code></dt>
<dd><p>corresponds to (-Inf, +Inf),
</p></dd>
</dl>

<p><code class="code">f</code> and <code class="code">ex</code> define the integrand function, see above;
<code class="code">epsabs</code> and <code class="code">epsrel</code> specify the absolute and relative
accuracy requested, <code class="code">result</code>, <code class="code">abserr</code> and <code class="code">last</code> are the
output components <code class="code">value</code>, <code class="code">abs.err</code> and <code class="code">subdivisions</code>
of the R function integrate, where <code class="code">neval</code> gives the number of
integrand function evaluations, and the error code <code class="code">ier</code> is
translated to R&rsquo;s <code class="code">integrate() $ message</code>, look at that function
definition.  <code class="code">limit</code> corresponds to <code class="code">integrate(...,
subdivisions = *)</code>.  It seems you should always define the two work
arrays and the length of the second one as
</p>
<div class="example">
<pre class="example-preformatted">    lenw = 4 * limit;
    iwork =   (int *) R_alloc(limit, sizeof(int));
    work = (double *) R_alloc(lenw,  sizeof(double));
</pre></div>

<p>The comments in the source code in <samp class="file">src/appl/integrate.c</samp> give
more details, particularly about reasons for failure (<code class="code">ier &gt;= 1</code>).
</p>

<hr>
</div>
<div class="section-level-extent" id="Utility-functions">
<div class="nav-panel">
<p>
Next: <a href="#Re_002dencoding" accesskey="n" rel="next">Re-encoding</a>, Previous: <a href="#Integration" accesskey="p" rel="prev">Integration</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Utility-functions-1"><span>6.10 Utility functions<a class="copiable-link" href="#Utility-functions-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Sort-functions-from-C"></a>

<p>R has a fairly comprehensive set of sort routines which are made
available to users&rsquo; C code.
The following is declared in header file <samp class="file">Rinternals.h</samp>.
</p>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005forderVector"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_orderVector</strong> <code class="def-code-arguments">(int* <var class="var">indx</var>, int <var class="var">n</var>, SEXP <var class="var">arglist</var>, Rboolean <var class="var">nalast</var>, Rboolean <var class="var">decreasing</var>)</code><a class="copiable-link" href="#index-R_005forderVector"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005forderVector1"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_orderVector1</strong> <code class="def-code-arguments">(int* <var class="var">indx</var>, int <var class="var">n</var>, SEXP <var class="var">x</var>, Rboolean <var class="var">nalast</var>, Rboolean <var class="var">decreasing</var>)</code><a class="copiable-link" href="#index-R_005forderVector1"> &para;</a></span></dt>
<dd>
<p><code class="code">R_orderVector()</code> corresponds to R&rsquo;s <code class="code">order(..., na.last, decreasing)</code>.
More specifically, <code class="code">indx &lt;- order(x, y, na.last, decreasing)</code> corresponds to
<code class="code">R_orderVector(indx, n, Rf_lang2(x, y), nalast, decreasing)</code> and for
three vectors, <code class="code">Rf_lang3(x,y,z)</code> is used as <var class="var">arglist</var>.
</p>
<p>Both <code class="code">R_orderVector</code> and <code class="code">R_orderVector1</code> assume the vector
<code class="code">indx</code> to be allocated to length &gt;= n.  On return,
<code class="code">indx[]</code> contains a permutation of <code class="code">0:(n-1)</code>, i.e., 0-based C
indices (and not 1-based R indices, as R&rsquo;s <code class="code">order()</code>).
</p>
<p>When ordering only one vector, <code class="code">R_orderVector1</code> is faster and
corresponds (but is 0-based) to R&rsquo;s <code class="code">indx &lt;- order(x, na.last,
decreasing)</code>.  It was added in R 3.3.0.
</p></dd></dl>

<p>All other sort routines are declared in header file
<samp class="file">R_ext/Utils.h</samp> (included by <samp class="file">R.h</samp>) and include the following.
</p>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fisort"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_isort</strong> <code class="def-code-arguments">(int* <var class="var">x</var>, int <var class="var">n</var>)</code><a class="copiable-link" href="#index-R_005fisort"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005frsort"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_rsort</strong> <code class="def-code-arguments">(double* <var class="var">x</var>, int <var class="var">n</var>)</code><a class="copiable-link" href="#index-R_005frsort"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fcsort"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_csort</strong> <code class="def-code-arguments">(Rcomplex* <var class="var">x</var>, int <var class="var">n</var>)</code><a class="copiable-link" href="#index-R_005fcsort"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-rsort_005fwith_005findex"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">rsort_with_index</strong> <code class="def-code-arguments">(double* <var class="var">x</var>, int* <var class="var">index</var>, int <var class="var">n</var>)</code><a class="copiable-link" href="#index-rsort_005fwith_005findex"> &para;</a></span></dt>
<dd><p>The first three sort integer, real (double) and complex data
respectively.  (Complex numbers are sorted by the real part first then
the imaginary part.)  <code class="code">NA</code>s are sorted last.
</p>
<p><code class="code">rsort_with_index</code> sorts on <var class="var">x</var>, and applies the same
permutation to <var class="var">index</var>.  <code class="code">NA</code>s are sorted last.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-revsort"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">revsort</strong> <code class="def-code-arguments">(double* <var class="var">x</var>, int* <var class="var">index</var>, int <var class="var">n</var>)</code><a class="copiable-link" href="#index-revsort"> &para;</a></span></dt>
<dd><p>Is similar to <code class="code">rsort_with_index</code> but sorts into decreasing order,
and <code class="code">NA</code>s are not handled.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-iPsort"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">iPsort</strong> <code class="def-code-arguments">(int* <var class="var">x</var>, int <var class="var">n</var>, int <var class="var">k</var>)</code><a class="copiable-link" href="#index-iPsort"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-rPsort"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">rPsort</strong> <code class="def-code-arguments">(double* <var class="var">x</var>, int <var class="var">n</var>, int <var class="var">k</var>)</code><a class="copiable-link" href="#index-rPsort"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-cPsort"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">cPsort</strong> <code class="def-code-arguments">(Rcomplex* <var class="var">x</var>, int <var class="var">n</var>, int <var class="var">k</var>)</code><a class="copiable-link" href="#index-cPsort"> &para;</a></span></dt>
<dd><p>These all provide (very) partial sorting: they permute <var class="var">x</var> so that
<code class="code"><var class="var">x</var>[<var class="var">k</var>]</code> is in the correct place with smaller values to
the left, larger ones to the right.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fqsort"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_qsort</strong> <code class="def-code-arguments">(double *<var class="var">v</var>, size_t <var class="var">i</var>, size_t <var class="var">j</var>)</code><a class="copiable-link" href="#index-R_005fqsort"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fqsort_005fI"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_qsort_I</strong> <code class="def-code-arguments">(double *<var class="var">v</var>, int *<var class="var">I</var>, int <var class="var">i</var>, int <var class="var">j</var>)</code><a class="copiable-link" href="#index-R_005fqsort_005fI"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fqsort_005fint"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_qsort_int</strong> <code class="def-code-arguments">(int *<var class="var">iv</var>, size_t <var class="var">i</var>, size_t <var class="var">j</var>)</code><a class="copiable-link" href="#index-R_005fqsort_005fint"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fqsort_005fint_005fI"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_qsort_int_I</strong> <code class="def-code-arguments">(int *<var class="var">iv</var>, int *<var class="var">I</var>, int <var class="var">i</var>, int <var class="var">j</var>)</code><a class="copiable-link" href="#index-R_005fqsort_005fint_005fI"> &para;</a></span></dt>
<dd>

<p>These routines sort <code class="code"><var class="var">v</var>[<var class="var">i</var>:<var class="var">j</var>]</code> or
<code class="code"><var class="var">iv</var>[<var class="var">i</var>:<var class="var">j</var>]</code> (using 1-indexing, i.e.,
<code class="code"><var class="var">v</var>[1]</code> is the first element) calling the quicksort algorithm
as used by R&rsquo;s <code class="code">sort(v, method = &quot;quick&quot;)</code> and documented on the
help page for the R function <code class="code">sort</code>.  The <code class="code">..._I()</code>
versions also return the <code class="code">sort.index()</code> vector in <code class="code">I</code>.  Note
that the ordering is <em class="emph">not</em> stable, so tied values may be permuted.
</p>
<p>Note that <code class="code">NA</code>s are not handled (explicitly) and you should
use different sorting functions if <code class="code">NA</code>s can be present.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-qsort4"><span class="category-def">Function: </span><span><code class="def-type">subroutine</code> <strong class="def-name">qsort4</strong> <code class="def-code-arguments">(double precision <var class="var">v</var>, integer <var class="var">indx</var>, integer <var class="var">ii</var>, integer <var class="var">jj</var>)</code><a class="copiable-link" href="#index-qsort4"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-qsort3"><span class="category-def">Function: </span><span><code class="def-type">subroutine</code> <strong class="def-name">qsort3</strong> <code class="def-code-arguments">(double precision <var class="var">v</var>, integer <var class="var">ii</var>, integer <var class="var">jj</var>)</code><a class="copiable-link" href="#index-qsort3"> &para;</a></span></dt>
<dd>
<p>The Fortran interface routines for sorting double precision vectors are
<code class="code">qsort3</code> and <code class="code">qsort4</code>, equivalent to <code class="code">R_qsort</code> and
<code class="code">R_qsort_I</code>, respectively.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fmax_005fcol"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_max_col</strong> <code class="def-code-arguments">(double* <var class="var">matrix</var>, int* <var class="var">nr</var>, int* <var class="var">nc</var>, int* <var class="var">maxes</var>, int* <var class="var">ties_meth</var>)</code><a class="copiable-link" href="#index-R_005fmax_005fcol"> &para;</a></span></dt>
<dd><p>Given the <var class="var">nr</var> by <var class="var">nc</var> matrix <code class="code">matrix</code> in column-major
(&ldquo;Fortran&rdquo;)
order, <code class="code">R_max_col()</code> returns in <code class="code"><var class="var">maxes</var>[<var class="var">i</var>-1]</code> the
column number of the maximal element in the <var class="var">i</var>-th row (the same as
R&rsquo;s <code class="code">max.col()</code> function).  In the case of ties (multiple maxima),
<code class="code">*ties_meth</code> is an integer code in <code class="code">1:3</code> determining the method:
1 = &ldquo;random&rdquo;, 2 = &ldquo;first&rdquo; and 3 = &ldquo;last&rdquo;.
See R&rsquo;s help page <code class="code">?max.col</code>.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-findInterval"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">findInterval</strong> <code class="def-code-arguments">(double* <var class="var">xt</var>, int <var class="var">n</var>, double <var class="var">x</var>, Rboolean <var class="var">rightmost_closed</var>, Rboolean <var class="var">all_inside</var>, int <var class="var">ilo</var>, int* <var class="var">mflag</var>)</code><a class="copiable-link" href="#index-findInterval"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-findInterval2_0028double_002a"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">findInterval2(double*</strong> <code class="def-code-arguments"><var class="var">xt</var>, int <var class="var">n</var>, double <var class="var">x</var>, Rboolean <var class="var">rightmost_closed</var>, Rboolean <var class="var">all_inside</var>, Rboolean <var class="var">left_open</var>, int <var class="var">ilo</var>, int* <var class="var">mflag</var>)</code><a class="copiable-link" href="#index-findInterval2_0028double_002a"> &para;</a></span></dt>
<dd><p>Given the ordered vector <var class="var">xt</var> of length <var class="var">n</var>, return the interval
or index of <var class="var">x</var> in <code class="code"><var class="var">xt</var>[]</code>, typically max(<em class="math">i</em>; 1 &lt;= i &lt;= <var class="var">n</var> &amp; <em class="math"><var class="var">xt</var>[i]</em> &lt;=
<var class="var">x</var>) where we use 1-indexing as in R and Fortran (but not C).  If
<var class="var">rightmost_closed</var> is true, also returns <em class="math"><var class="var">n</var>-1</em> if <var class="var">x</var>
equals <em class="math"><var class="var">xt</var>[<var class="var">n</var>]</em>.  If <var class="var">all_inside</var> is not 0, the
result is coerced to lie in <code class="code">1:(<var class="var">n</var>-1)</code> even when <var class="var">x</var> is
outside the <var class="var">xt</var>[] range.  On return, <code class="code">*<var class="var">mflag</var></code> equals
<em class="math">-1</em> if <var class="var">x</var> &lt; <var class="var">xt</var>[1], <em class="math">+1</em> if <var class="var">x</var> &gt;=
<var class="var">xt</var>[<var class="var">n</var>], and 0 otherwise.
</p>
<p>The algorithm is particularly fast when <var class="var">ilo</var> is set to the last
result of <code class="code">findInterval()</code> and <var class="var">x</var> is a value of a sequence which
is increasing or decreasing for subsequent calls.
</p>
<p><code class="code">findInterval2()</code> is a generalization of <code class="code">findInterval()</code>,
with an extra <code class="code">Rboolean</code> argument <var class="var">left_open</var>.  Setting
<code class="code">left_open = TRUE</code> basically replaces all left-closed right-open
intervals t) by left-open ones t], see the help page
of R function <code class="code">findInterval</code> for details.
</p>
<p>There is also an <code class="code">F77_CALL(interv)()</code> version of
<code class="code">findInterval()</code> with the same arguments, but all pointers.
</p></dd></dl>

<p>A system-independent interface to produce the name of a temporary
file is provided as
</p>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005ftmpnam"><span class="category-def">Function: </span><span><code class="def-type">char *</code> <strong class="def-name">R_tmpnam</strong> <code class="def-code-arguments">(const char *<var class="var">prefix</var>, const char *<var class="var">tmpdir</var>)</code><a class="copiable-link" href="#index-R_005ftmpnam"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005ftmpnam2"><span class="category-def">Function: </span><span><code class="def-type">char *</code> <strong class="def-name">R_tmpnam2</strong> <code class="def-code-arguments">(const char *<var class="var">prefix</var>, const char *<var class="var">tmpdir</var>, const char *<var class="var">fileext</var>)</code><a class="copiable-link" href="#index-R_005ftmpnam2"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005ffree_005ftmpnam"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_free_tmpnam</strong> <code class="def-code-arguments">(char *<var class="var">name</var>)</code><a class="copiable-link" href="#index-R_005ffree_005ftmpnam"> &para;</a></span></dt>
<dd><p>Return a pathname for a temporary file with name beginning with
<var class="var">prefix</var> and ending with <var class="var">fileext</var> in directory <var class="var">tmpdir</var>.
A <code class="code">NULL</code> prefix or extension is replaced by <code class="code">&quot;&quot;</code>.  Note that
the return value is dynamically allocated and should be freed using
<code class="code">R_free_tmpnam</code> when no longer needed (unlike the
system call <code class="code">tmpnam</code>). Freeing the result using <code class="code">free</code> is no
longer recommended. 
</p></dd></dl>


<p>There is also the internal function used to expand file names in several
R functions, and called directly by <code class="code">path.expand</code>.
</p>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fExpandFileName"><span class="category-def">Function: </span><span><code class="def-type">const char *</code> <strong class="def-name">R_ExpandFileName</strong> <code class="def-code-arguments">(const char *<var class="var">fn</var>)</code><a class="copiable-link" href="#index-R_005fExpandFileName"> &para;</a></span></dt>
<dd><p>Expand a path name <var class="var">fn</var> by replacing a leading tilde by the user&rsquo;s
home directory (if defined).  The precise meaning is platform-specific;
it will usually be taken from the environment variable <code class="env">HOME</code> if
this is defined.
</p></dd></dl>

<p>For historical reasons there are Fortran interfaces to functions
<code class="code">D1MACH</code> and <code class="code">I1MACH</code>.  These can be called from C code as
e.g. <code class="code">F77_CALL(d1mach)(4)</code>.  Note that these are emulations of
the original functions by Fox, Hall and Schryer on Netlib at
<a class="uref" href="https://netlib.org/slatec/src/">https://netlib.org/slatec/src/</a> for <abbr class="acronym">IEC</abbr>&nbsp;60559 arithmetic
(required by R).
</p>
<hr>
</div>
<div class="section-level-extent" id="Re_002dencoding">
<div class="nav-panel">
<p>
Next: <a href="#Condition-handling-and-cleanup-code" accesskey="n" rel="next">Condition handling and cleanup code</a>, Previous: <a href="#Utility-functions" accesskey="p" rel="prev">Utility functions</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Re_002dencoding-1"><span>6.11 Re-encoding<a class="copiable-link" href="#Re_002dencoding-1"> &para;</a></span></h3>

<p>R has its own C-level interface to the encoding conversion
capabilities provided by <code class="code">iconv</code> because there are
incompatibilities between the declarations in different implementations
of <code class="code">iconv</code>.
</p>
<p>These are declared in header file <samp class="file">R_ext/Riconv.h</samp>.
</p>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-Riconv_005fopen"><span class="category-def">Function: </span><span><code class="def-type">void *</code> <strong class="def-name">Riconv_open</strong> <code class="def-code-arguments">(const char *<var class="var">to</var>, const char *<var class="var">from</var>)</code><a class="copiable-link" href="#index-Riconv_005fopen"> &para;</a></span></dt>
<dd><p>Set up a pointer to an encoding object to be used to convert between two
encodings: <code class="code">&quot;&quot;</code> indicates the current locale.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-Riconv"><span class="category-def">Function: </span><span><code class="def-type">size_t</code> <strong class="def-name">Riconv</strong> <code class="def-code-arguments">(void *<var class="var">cd</var>, const char **<var class="var">inbuf</var>, size_t *<var class="var">inbytesleft</var>, char  **<var class="var">outbuf</var>, size_t *<var class="var">outbytesleft</var>)</code><a class="copiable-link" href="#index-Riconv"> &para;</a></span></dt>
<dd><p>Convert as much as possible of <code class="code">inbuf</code> to <code class="code">outbuf</code>.  Initially
the <code class="code">size_t</code> variables indicate the number of bytes available in the
buffers, and they are updated (and the <code class="code">char</code> pointers are updated
to point to the next free byte in the buffer).  The return value is the
number of characters converted, or <code class="code">(size_t)-1</code> (beware:
<code class="code">size_t</code> is usually an unsigned type).  It should be safe to assume
that an error condition sets <code class="code">errno</code> to one of <code class="code">E2BIG</code> (the
output buffer is full), <code class="code">EILSEQ</code> (the input cannot be converted,
and might be invalid in the encoding specified) or <code class="code">EINVAL</code> (the
input does not end with a complete multi-byte character).
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-Riconv_005fclose"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">Riconv_close</strong> <code class="def-code-arguments">(void * <var class="var">cd</var>)</code><a class="copiable-link" href="#index-Riconv_005fclose"> &para;</a></span></dt>
<dd><p>Free the resources of an encoding object.
</p></dd></dl>


<hr>
</div>
<div class="section-level-extent" id="Condition-handling-and-cleanup-code">
<div class="nav-panel">
<p>
Next: <a href="#Allowing-interrupts" accesskey="n" rel="next">Allowing interrupts</a>, Previous: <a href="#Re_002dencoding" accesskey="p" rel="prev">Re-encoding</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Condition-handling-and-cleanup-code-1"><span>6.12 Condition handling and cleanup code<a class="copiable-link" href="#Condition-handling-and-cleanup-code-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Condition-handling"></a>
<a class="index-entry-id" id="index-Cleanup-code"></a>
<a class="index-entry-id" id="index-Error-handling"></a>

<p>Three functions are available for establishing condition handlers from
within C code:
</p>
<div class="example">
<pre class="example-preformatted">#include &lt;Rinternals.h&gt;

SEXP R_tryCatchError(SEXP (*fun)(void *data), void *data,
		     SEXP (*hndlr)(SEXP cond, void *hdata), void *hdata);

SEXP R_tryCatch(SEXP (*fun)(void *data), void *data,
		SEXP,
		SEXP (*hndlr)(SEXP cond, void *hdata), void *hdata,
		void (*clean)(void *cdata), void *cdata);
SEXP R_withCallingErrorHandler(SEXP (*fun)(void *data), void *data,
			       SEXP (*hndlr)(SEXP cond, void *hdata), void *hdata)
</pre></div>
<a class="index-entry-id" id="index-R_005ftryCatchError"></a>
<a class="index-entry-id" id="index-R_005ftryCatch"></a>
<a class="index-entry-id" id="index-R_005fwithCallingErrorHandler"></a>

<p><code class="code">R_tryCatchError</code> establishes an exiting handler for conditions
inheriting form class <code class="code">error</code>.
</p>
<p><code class="code">R_tryCatch</code> can be used to establish a handler for other
conditions and to register a cleanup action. The conditions to be
handled are specified as a character vector (<code class="code">STRSXP</code>).
A <code class="code">NULL</code> pointer can be passed as <code class="code">fun</code> or <code class="code">clean</code>
if condition handling or cleanup are not needed.
</p>
<p>These are currently implemented using the R-level <code class="code">tryCatch</code>
mechanism so are subject to some overhead.
</p>
<p><code class="code">R_withCallingErrorHandler</code> establishes a calling handler for
conditions inheriting form class <code class="code">error</code>.  It establishes the
handler without calling back into R and will therefore be more
efficient.
</p>
<p>The function <code class="code">R_UnwindProtect</code> can be used to ensure that a cleanup
action takes place on ordinary return as well as on a non-local transfer
of control, which R implements as a <code class="code">longjmp</code>.
</p>
<div class="example">
<pre class="example-preformatted">SEXP R_UnwindProtect(SEXP (*fun)(void *data), void *data,
                     void (*clean)(void *data, Rboolean jump), void *cdata,
                     SEXP cont);
</pre></div>
<a class="index-entry-id" id="index-R_005fUnwindProtect"></a>

<p><code class="code">R_UnwindProtect</code> can be used in two ways.  The simper usage,
suitable for use in C code, passes <code class="code">NULL</code> for the <code class="code">cont</code>
argument.  <code class="code">R_UnwindProtect</code> will call <code class="code">fun(data)</code>.  If
<code class="code">fun</code> returns a value, then <code class="code">R_UnwindProtect</code> calls
<code class="code">clean(cleandata, FALSE)</code> before returning the value returned by
<code class="code">fun</code>. If <code class="code">fun</code> executes a non-local transfer of control, then
<code class="code">clean(cleandata, TRUE)</code> is called, and the non-local transfer of
control is resumed.
</p>
<p>The second use pattern, suitable to support C++ stack unwinding, uses
two additional functions:
</p>
<div class="example">
<pre class="example-preformatted">SEXP R_MakeUnwindCont();
NORET void R_ContinueUnwind(SEXP cont);
</pre></div>
<a class="index-entry-id" id="index-R_005fMakeUnwindCont"></a>
<a class="index-entry-id" id="index-R_005fContinueUnwind"></a>

<p><code class="code">R_MakeUnwindCont</code> allocates a <em class="emph">continuation token</em>
<code class="code">cont</code> to pass to <code class="code">R_UnwindProtect</code>. This token should be
protected with <code class="code">PROTECT</code> before calling
<code class="code">R_UnwindProtect</code>. When the <code class="code">clean</code> function is called with
<code class="code">jump == TRUE</code>, indicating that R is executing a non-local transfer
of control, it can throw a C++ exception to a C++ <code class="code">catch</code> outside
the C++ code to be unwound, and then use the continuation token in the a
call <code class="code">R_ContinueUnwind(cont)</code> to resume the non-local transfer of
control within R.
</p>
<hr>
</div>
<div class="section-level-extent" id="Allowing-interrupts">
<div class="nav-panel">
<p>
Next: <a href="#Platform-and-version-information" accesskey="n" rel="next">Platform and version information</a>, Previous: <a href="#Condition-handling-and-cleanup-code" accesskey="p" rel="prev">Condition handling and cleanup code</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Allowing-interrupts-1"><span>6.13 Allowing interrupts<a class="copiable-link" href="#Allowing-interrupts-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Interrupts"></a>

<p>No part of R can be interrupted whilst running long computations in
compiled code, so programmers should make provision for the code to be
interrupted at suitable points by calling from C
</p>
<div class="example">
<pre class="example-preformatted">#include &lt;R_ext/Utils.h&gt;

void R_CheckUserInterrupt(void);
</pre></div>
<a class="index-entry-id" id="index-R_005fCheckUserInterrupt"></a>

<p>and from Fortran
</p>
<div class="example">
<pre class="example-preformatted">subroutine rchkusr()
</pre></div>
<a class="index-entry-id" id="index-rchkusr"></a>

<p>These check if the user has requested an interrupt, and if so branch to
R&rsquo;s error signaling functions.
</p>
<p>Note that it is possible that the code behind one of the entry points
defined here if called from your C or Fortran code could be interruptible
or generate an error and so not return to your code.
</p>

<hr>
</div>
<div class="section-level-extent" id="Platform-and-version-information">
<div class="nav-panel">
<p>
Next: <a href="#Inlining-C-functions" accesskey="n" rel="next">Inlining C functions</a>, Previous: <a href="#Allowing-interrupts" accesskey="p" rel="prev">Allowing interrupts</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Platform-and-version-information-1"><span>6.14 Platform and version information<a class="copiable-link" href="#Platform-and-version-information-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Version-information-from-C"></a>
<a class="index-entry-id" id="index-OpenMP-1"></a>
<a class="index-entry-id" id="index-R_005fVersion"></a>

<p>The header files define <code class="code">USING_R</code>, which can be used to test if
the code is indeed being used with R.
</p>
<p>Header file <samp class="file">Rconfig.h</samp> (included by <samp class="file">R.h</samp>) is used to define
platform-specific macros that are mainly for use in other header files.
The macro <code class="code">WORDS_BIGENDIAN</code> is defined on
big-endian<a class="footnote" id="DOCF167" href="#FOOT167"><sup>167</sup></a>
systems (e.g. most OSes on Sparc and PowerPC hardware) and not on
little-endian systems (nowadays all the commoner R platforms).  It
can be useful when manipulating binary files.  NB: these macros apply
only to the C compiler used to build R, not necessarily to another C
or C++ compiler.
</p>
<p>Header file <samp class="file">Rversion.h</samp> (<strong class="strong">not</strong> included by <samp class="file">R.h</samp>)
defines a macro <code class="code">R_VERSION</code> giving the version number encoded as an
integer, plus a macro <code class="code">R_Version</code> to do the encoding.  This can be
used to test if the version of R is late enough, or to include
back-compatibility features.  For protection against very old versions
of R which did not have this macro, use a construction such as
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#if defined(R_VERSION) &amp;&amp; R_VERSION &gt;= R_Version(3, 1, 0)
  ...
#endif
</pre></div></div>

<p>More detailed information is available in the macros <code class="code">R_MAJOR</code>,
<code class="code">R_MINOR</code>, <code class="code">R_YEAR</code>, <code class="code">R_MONTH</code> and <code class="code">R_DAY</code>: see the
header file <samp class="file">Rversion.h</samp> for their format.  Note that the minor
version includes the patch level (as in &lsquo;<samp class="samp">2.2</samp>&rsquo;).
</p>
<p>Packages which use <code class="code">alloca</code> need to ensure it is defined: as it is
part of neither C nor POSIX there is no standard way to do so.  One can
use
</p>
<div class="example">
<pre class="example-preformatted">#include &lt;Rconfig.h&gt; // for HAVE_ALLOCA_H
#ifdef __GNUC__
// this covers gcc, clang, icc
# undef alloca
# define alloca(x) __builtin_alloca((x))
#elif defined(HAVE_ALLOCA_H)
// needed for native compilers on Solaris and AIX
# include &lt;alloca.h&gt;
#endif
</pre></div>

<p>(and this should be included before standard C headers such as
<samp class="file">stdlib.h</samp>, since on some platforms these include <samp class="file">malloc.h</samp>
which may have a conflicting definition), which suffices for known R
platforms.
</p>
<hr>
</div>
<div class="section-level-extent" id="Inlining-C-functions">
<div class="nav-panel">
<p>
Next: <a href="#Controlling-visibility" accesskey="n" rel="next">Controlling visibility</a>, Previous: <a href="#Platform-and-version-information" accesskey="p" rel="prev">Platform and version information</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Inlining-C-functions-1"><span>6.15 Inlining C functions<a class="copiable-link" href="#Inlining-C-functions-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-R_005fINLINE"></a>

<p>The C99 keyword <code class="code">inline</code> should be recognized by all compilers
nowadays used to build R.  Portable code which might be used with
earlier versions of R can be written using the macro <code class="code">R_INLINE</code>
(defined in file <samp class="file">Rconfig.h</samp> included by <samp class="file">R.h</samp>), as for
example from package <a class="url" href="https://CRAN.R-project.org/package=cluster"><strong class="strong">cluster</strong></a>
</p>
<div class="example">
<pre class="example-preformatted">#include &lt;R.h&gt;

static R_INLINE int ind_2(int l, int j)
{
...
}
</pre></div>

<p>Be aware that using inlining with functions in more than one compilation
unit is almost impossible to do portably, see
<a class="uref" href="https://www.greenend.org.uk/rjk/tech/inline.html">https://www.greenend.org.uk/rjk/tech/inline.html</a>, so this usage
is for <code class="code">static</code> functions as in the example.  All the R
configure code has checked is that <code class="code">R_INLINE</code> can be used in a
single C file with the compiler used to build R.  We recommend that
packages making extensive use of inlining include their own configure
code.
</p>
<hr>
</div>
<div class="section-level-extent" id="Controlling-visibility">
<div class="nav-panel">
<p>
Next: <a href="#Standalone-Mathlib" accesskey="n" rel="next">Using these functions in your own C code</a>, Previous: <a href="#Inlining-C-functions" accesskey="p" rel="prev">Inlining C functions</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Controlling-visibility-1"><span>6.16 Controlling visibility<a class="copiable-link" href="#Controlling-visibility-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-Visibility"></a>

<p>Header <samp class="file">R_ext/Visibility.h</samp> has some definitions for controlling the
visibility of entry points.  These are only effective when
&lsquo;<samp class="samp">HAVE_VISIBILITY_ATTRIBUTE</samp>&rsquo; is defined &ndash; this is checked when R
is configured and recorded in header <samp class="file">Rconfig.h</samp> (included by
<samp class="file">R_ext/Visibility.h</samp>).  It is often defined on modern Unix-alikes
with a recent compiler<a class="footnote" id="DOCF168" href="#FOOT168"><sup>168</sup></a>, but not
supported on macOS nor Windows.  Minimizing the visibility of symbols in
a shared library will both speed up its loading (unlikely to be
significant) and reduce the possibility of linking to other entry points
of the same name.
</p>
<p>C/C++ entry points prefixed by <code class="code">attribute_hidden</code> will not be
visible in the shared object.  There is no comparable mechanism for
Fortran entry points, but there is a more comprehensive scheme used by,
for example package <strong class="strong">stats</strong>.  Most compilers which allow control of
visibility will allow control of visibility for all symbols <em class="emph">via</em> a
flag, and where known the flag is encapsulated in the macros
&lsquo;<samp class="samp">C_VISIBILITY</samp>&rsquo;, &lsquo;<samp class="samp">CXX_VISIBILITY</samp>&rsquo;<a class="footnote" id="DOCF169" href="#FOOT169"><sup>169</sup></a> and &lsquo;<samp class="samp">F_VISIBILITY</samp>&rsquo; for C, C++ and
Fortran compilers.<a class="footnote" id="DOCF170" href="#FOOT170"><sup>170</sup></a>  These are defined in
<samp class="file">etc/Makeconf</samp> and so available for normal compilation of package
code.  For example, <samp class="file">src/Makevars</samp> could include some of
</p>
<div class="example">
<pre class="example-preformatted">PKG_CFLAGS=$(C_VISIBILITY)
PKG_CXXFLAGS=$(CXX_VISIBILITY)
PKG_FFLAGS=$(F_VISIBILITY)
</pre></div>

<p>This would end up with <strong class="strong">no</strong> visible entry points, which would be
pointless.  However, the effect of the flags can be overridden by using
the <code class="code">attribute_visible</code> prefix.  A shared object which registers
its entry points needs only for have one visible entry point, its
initializer, so for example package <strong class="strong">stats</strong> has
</p>
<div class="example">
<pre class="example-preformatted">void attribute_visible R_init_stats(DllInfo *dll)
{
    R_registerRoutines(dll, CEntries, CallEntries, FortEntries, NULL);
    R_useDynamicSymbols(dll, FALSE);
...
}
</pre></div>

<p>Because the &lsquo;<samp class="samp">C_VISIBILITY</samp>&rsquo; mechanism is only useful in conjunction
with <code class="code">attribute_visible</code>, it is not enabled unless
&lsquo;<samp class="samp">HAVE_VISIBILITY_ATTRIBUTE</samp>&rsquo; is defined.  The usual visibility flag
is <samp class="option">-fvisibility=hidden</samp>: some compilers also support
<samp class="option">-fvisibility-inlines-hidden</samp> which can be used by overriding
&lsquo;<samp class="samp">C_VISIBILITY</samp>&rsquo; and &lsquo;<samp class="samp">CXX_VISIBILITY</samp>&rsquo; in <samp class="file">config.site</samp> when
building R, or editing <samp class="file">etc/Makeconf</samp> in the R installation.
</p>
<p>Note that <code class="command">configure</code> only checks that visibility attributes and
flags are accepted, not that they actually hide symbols.
</p>
<p>The visibility mechanism is not available on Windows, but there is an
equally effective way to control which entry points are visible, by
supplying a definitions file
<samp class="file"><var class="var">pkgnme</var>/src/<var class="var">pkgname</var>-win.def</samp>: only entry points
listed in that file will be visible.  Again using <strong class="strong">stats</strong> as an
example, it has
</p>
<div class="example">
<pre class="example-preformatted">LIBRARY stats.dll
EXPORTS
 R_init_stats
</pre></div>

<hr>
</div>
<div class="section-level-extent" id="Standalone-Mathlib">
<div class="nav-panel">
<p>
Next: <a href="#Organization-of-header-files" accesskey="n" rel="next">Organization of header files</a>, Previous: <a href="#Controlling-visibility" accesskey="p" rel="prev">Controlling visibility</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Using-these-functions-in-your-own-C-code"><span>6.17 Using these functions in your own C code<a class="copiable-link" href="#Using-these-functions-in-your-own-C-code"> &para;</a></span></h3>

<p>It is possible to build <code class="code">Mathlib</code>, the R set of mathematical
functions documented in <samp class="file">Rmath.h</samp>, as a standalone library
<samp class="file">libRmath</samp> under both Unix-alikes and Windows.  (This includes the
functions documented in <a class="ref" href="#Numerical-analysis-subroutines">Numerical analysis subroutines</a> as from
that header file.)
</p>
<p>The library is not built automatically when R is installed, but can
be built in the directory <samp class="file">src/nmath/standalone</samp> in the R
sources: see the file <samp class="file">README</samp> there.  To use the code in your own
C program include
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">#define MATHLIB_STANDALONE
#include &lt;Rmath.h&gt;
</pre></div></div>

<p>and link against &lsquo;<samp class="samp">-lRmath</samp>&rsquo; (and perhaps &lsquo;<samp class="samp">-lm</samp>&rsquo;).  There is an
example file <samp class="file">test.c</samp>.
</p>
<p>A little care is needed to use the random-number routines. You will
need to supply the uniform random number generator
</p>
<div class="example">
<pre class="example-preformatted">double unif_rand(void)
</pre></div>

<p>or use the one supplied (and with a dynamic library or DLL you will have
to use the one supplied, which is the Marsaglia-multicarry with an entry
points
</p>
<div class="example">
<pre class="example-preformatted">set_seed(unsigned int, unsigned int)
</pre></div>

<p>to set its seeds and
</p>
<div class="example">
<pre class="example-preformatted">get_seed(unsigned int *, unsigned int *)
</pre></div>

<p>to read the seeds).
</p>
<hr>
</div>
<div class="section-level-extent" id="Organization-of-header-files">
<div class="nav-panel">
<p>
Previous: <a href="#Standalone-Mathlib" accesskey="p" rel="prev">Using these functions in your own C code</a>, Up: <a href="#The-R-API" accesskey="u" rel="up">The R <abbr class="acronym">API</abbr>: entry points for C code</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Organization-of-header-files-1"><span>6.18 Organization of header files<a class="copiable-link" href="#Organization-of-header-files-1"> &para;</a></span></h3>

<p>The header files which R installs are in directory
<samp class="file"><var class="var">R_INCLUDE_DIR</var></samp> (default <samp class="file"><var class="var">R_HOME</var>/include</samp>).  This
currently includes
</p>
<blockquote class="quotation">
<table summary="" class="multitable">
<tbody><tr><td width="30%"><samp class="file">R.h</samp></td><td width="55%">includes many other files</td></tr>
<tr><td width="30%"><samp class="file">Rinternals.h</samp></td><td width="55%">definitions for using R&rsquo;s internal
structures</td></tr>
<tr><td width="30%"><samp class="file">Rdefines.h</samp></td><td width="55%">macros for an S-like interface to the
above (no longer maintained)</td></tr>
<tr><td width="30%"><samp class="file">Rmath.h</samp></td><td width="55%">standalone math library</td></tr>
<tr><td width="30%"><samp class="file">Rversion.h</samp></td><td width="55%">R version information</td></tr>
<tr><td width="30%"><samp class="file">Rinterface.h</samp></td><td width="55%">for add-on front-ends (Unix-alikes only)</td></tr>
<tr><td width="30%"><samp class="file">Rembedded.h</samp></td><td width="55%">for add-on front-ends</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Applic.h</samp></td><td width="55%">optimization and integration</td></tr>
<tr><td width="30%"><samp class="file">R_ext/BLAS.h</samp></td><td width="55%">C definitions for BLAS routines</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Callbacks.h</samp></td><td width="55%">C (and R function) top-level task
handlers</td></tr>
<tr><td width="30%"><samp class="file">R_ext/GetX11Image.h</samp></td><td width="55%">X11Image interface used by package
<strong class="strong">trkplot</strong></td></tr>
<tr><td width="30%"><samp class="file">R_ext/Lapack.h</samp></td><td width="55%">C definitions for some LAPACK routines</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Linpack.h</samp></td><td width="55%">C definitions for some LINPACK
routines, not all of which are included in R</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Parse.h</samp></td><td width="55%">a small part of R&rsquo;s parse interface:
not part of the stable API.</td></tr>
<tr><td width="30%"><samp class="file">R_ext/RStartup.h</samp></td><td width="55%">for add-on front-ends</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Rdynload.h</samp></td><td width="55%">needed to register compiled code in
packages</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Riconv.h</samp></td><td width="55%">interface to <code class="code">iconv</code></td></tr>
<tr><td width="30%"><samp class="file">R_ext/Visibility.h</samp></td><td width="55%">definitions controlling visibility</td></tr>
<tr><td width="30%"><samp class="file">R_ext/eventloop.h</samp></td><td width="55%">for add-on front-ends and for
packages that need to share in the R event loops (not Windows)</td></tr>
</tbody>
</table>
</blockquote>

<p>The following headers are included by <samp class="file">R.h</samp>:
</p>
<blockquote class="quotation">
<table summary="" class="multitable">
<tbody><tr><td width="30%"><samp class="file">Rconfig.h</samp></td><td width="55%">configuration info that is made available</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Arith.h</samp></td><td width="55%">handling for <code class="code">NA</code>s, <code class="code">NaN</code>s,
<code class="code">Inf</code>/<code class="code">-Inf</code></td></tr>
<tr><td width="30%"><samp class="file">R_ext/Boolean.h</samp></td><td width="55%"><code class="code">TRUE</code>/<code class="code">FALSE</code> type</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Complex.h</samp></td><td width="55%">C typedefs for R&rsquo;s <code class="code">complex</code></td></tr>
<tr><td width="30%"><samp class="file">R_ext/Constants.h</samp></td><td width="55%">constants</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Error.h</samp></td><td width="55%">error signaling</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Memory.h</samp></td><td width="55%">memory allocation</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Print.h</samp></td><td width="55%"><code class="code">Rprintf</code> and variations.</td></tr>
<tr><td width="30%"><samp class="file">R_ext/RS.h</samp></td><td width="55%">definitions common to <samp class="file">R.h</samp> and the former
<samp class="file">S.h</samp>, including <code class="code">F77_CALL</code> etc.</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Random.h</samp></td><td width="55%">random number generation</td></tr>
<tr><td width="30%"><samp class="file">R_ext/Utils.h</samp></td><td width="55%">sorting and other utilities</td></tr>
<tr><td width="30%"><samp class="file">R_ext/libextern.h</samp></td><td width="55%">definitions for exports from
<samp class="file">R.dll</samp> on Windows.</td></tr>
</tbody>
</table>
</blockquote>

<p>The graphics systems are exposed in headers
<samp class="file">R_ext/GraphicsEngine.h</samp>, <samp class="file">R_ext/GraphicsDevice.h</samp> (which it
includes) and <samp class="file">R_ext/QuartzDevice.h</samp>. Facilities for defining
custom connection implementations are provided in
<samp class="file">R_ext/Connections.h</samp>, but make sure you consult the file before
use.
</p>
<p>Let us re-iterate the advice to include in C++ code system headers
before the R header files, especially <samp class="file">Rinternals.h</samp> (included
by <samp class="file">Rdefines.h</samp>) and <samp class="file">Rmath.h</samp>, which redefine names which may
be used in system headers, or (preferably) to define <code class="code">R_NO_REMAP</code>.
Setting the environment variable <code class="env">_R_CXX_USE_NO_REMAP_</code> to a true
value allows the need for this to be tested, as it causes <code class="command">R CMD
INSTALL</code> to compile C++ code defining <code class="code">R_NO_REMAP</code>.  This is
planned to become the default in future.
</p>
<hr>
</div>
</div>
<div class="chapter-level-extent" id="Generic-functions-and-methods">
<div class="nav-panel">
<p>
Next: <a href="#Linking-GUIs-and-other-front_002dends-to-R" accesskey="n" rel="next">Linking GUIs and other front-ends to R</a>, Previous: <a href="#The-R-API" accesskey="p" rel="prev">The R <abbr class="acronym">API</abbr>: entry points for C code</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="chapter" id="Generic-functions-and-methods-1"><span>7 Generic functions and methods<a class="copiable-link" href="#Generic-functions-and-methods-1"> &para;</a></span></h2>
<a class="index-entry-id" id="index-Generic-functions"></a>
<a class="index-entry-id" id="index-Method-functions"></a>

<p>R programmers will often want to add methods for existing generic
functions, and may want to add new generic functions or make existing
functions generic.  In this chapter we give guidelines for doing so,
with examples of the problems caused by not adhering to them.
</p>
<p>This chapter only covers the &lsquo;informal&rsquo; class system copied from S3,
and not with the S4 (formal) methods of package <strong class="strong">methods</strong>.
</p>
<p>First, a <em class="emph">caveat</em>: a function named <code class="code"><var class="var">gen</var>.<var class="var">cl</var></code> will
be invoked by the generic <code class="code"><var class="var">gen</var></code> for class <code class="code"><var class="var">cl</var></code>, so
do not name functions in this style unless they are intended to be
methods.
</p>
<p>The key function for methods is <code class="code">NextMethod</code>, which dispatches the
next method.  It is quite typical for a method function to make a few
changes to its arguments, dispatch to the next method, receive the
results and modify them a little.  An example is
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">t.data.frame &lt;- function(x)
{
    x &lt;- as.matrix(x)
    NextMethod(&quot;t&quot;)
}
</pre></div></div>

<p>Note that the example above works because there is a <em class="emph">next</em> method,
the default method, not that a new method is selected when the class is
changed.
</p>
<p><em class="emph">Any</em> method a programmer writes may be invoked from another method
by <code class="code">NextMethod</code>, <em class="emph">with the arguments appropriate to the
previous method</em>.  Further, the programmer cannot predict which method
<code class="code">NextMethod</code> will pick (it might be one not yet dreamt of), and the
end user calling the generic needs to be able to pass arguments to the
next method.  For this to work
</p>
<blockquote class="quotation">
<p><em class="emph">A method must have all the arguments of the generic, including
<code class="code">&hellip;</code> if the generic does.</em>
</p></blockquote>

<p>It is a grave misunderstanding to think that a method needs only to
accept the arguments it needs.  The original S version of
<code class="code">predict.lm</code> did not have a <code class="code">&hellip;</code> argument, although
<code class="code">predict</code> did.  It soon became clear that <code class="code">predict.glm</code> needed
an argument <code class="code">dispersion</code> to handle over-dispersion.  As
<code class="code">predict.lm</code> had neither a <code class="code">dispersion</code> nor a <code class="code">&hellip;</code>
argument, <code class="code">NextMethod</code> could no longer be used.  (The legacy, two
direct calls to <code class="code">predict.lm</code>, lives on in <code class="code">predict.glm</code> in
R, which is based on the workaround for S3 written by Venables &amp;
Ripley.)
</p>
<p>Further, the user is entitled to use positional matching when calling
the generic, and the arguments to a method called by <code class="code">UseMethod</code>
are those of the call to the generic.  Thus
</p>
<blockquote class="quotation">
<p><em class="emph">A method must have arguments in exactly the same order as the
generic.</em>
</p></blockquote>

<p>To see the scale of this problem, consider the generic function
<code class="code">scale</code>, defined as
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">scale &lt;- function (x, center = TRUE, scale = TRUE)
    UseMethod(&quot;scale&quot;)
</pre></div></div>

<p>Suppose an unthinking package writer created methods such as
</p>
<div class="example">
<pre class="example-preformatted">scale.foo &lt;- function(x, scale = FALSE, ...) { }
</pre></div>

<p>Then for <code class="code">x</code> of class <code class="code">&quot;foo&quot;</code> the calls
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">scale(x, , TRUE)
scale(x, scale = TRUE)
</pre></div></div>

<p>would most likely do different things, to the justifiable
consternation of the end user.
</p>
<p>To add a further twist, which default is used when a user calls
<code class="code">scale(x)</code> in our example?  What if
</p>
<div class="example">
<pre class="example-preformatted">scale.bar &lt;- function(x, center, scale = TRUE) NextMethod(&quot;scale&quot;)
</pre></div>

<p>and <code class="code">x</code> has class <code class="code">c(&quot;bar&quot;, &quot;foo&quot;)</code>?  It is the default
specified in the method that is used, but the default
specified in the generic may be the one the user sees.
This leads to the recommendation:
</p>
<blockquote class="quotation">
<p><em class="emph">If the generic specifies defaults, all methods should use the same defaults.</em>
</p></blockquote>

<p>An easy way to follow these recommendations is to always keep generics
simple, e.g.
</p>
<div class="example">
<pre class="example-preformatted">scale &lt;- function(x, ...) UseMethod(&quot;scale&quot;)
</pre></div>

<p>Only add parameters and defaults to the generic if they make sense in
all possible methods implementing it.
</p>

<ul class="mini-toc">
<li><a href="#Adding-new-generics" accesskey="1">Adding new generics</a></li>
</ul>
<hr>
<div class="section-level-extent" id="Adding-new-generics">
<div class="nav-panel">
<p>
Previous: <a href="#Generic-functions-and-methods" accesskey="p" rel="prev">Generic functions and methods</a>, Up: <a href="#Generic-functions-and-methods" accesskey="u" rel="up">Generic functions and methods</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Adding-new-generics-1"><span>7.1 Adding new generics<a class="copiable-link" href="#Adding-new-generics-1"> &para;</a></span></h3>

<p>When creating a new generic function, bear in mind that its argument
list will be the maximal set of arguments for methods, including those
written elsewhere years later.  So choosing a good set of arguments may
well be an important design issue, and there need to be good arguments
<em class="emph">not</em> to include a <code class="code">&hellip;</code> argument.
</p>
<p>If a <code class="code">&hellip;</code> argument is supplied, some thought should be given
to its position in the argument sequence.  Arguments which follow
<code class="code">&hellip;</code> must be named in calls to the function, and they must be
named in full (partial matching is suppressed after <code class="code">&hellip;</code>).
Formal arguments before <code class="code">&hellip;</code> can be partially matched, and so
may &lsquo;swallow&rsquo; actual arguments intended for <code class="code">&hellip;</code>.  Although it
is commonplace to make the <code class="code">&hellip;</code> argument the last one, that is
not always the right choice.
</p>
<p>Sometimes package writers want to make generic a function in the base
package, and request a change in R.  This may be justifiable, but
making a function generic with the old definition as the default method
does have a small performance cost.  It is never necessary, as a package
can take over a function in the base package and make it generic by
something like
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">foo &lt;- function(object, ...) UseMethod(&quot;foo&quot;)
foo.default &lt;- function(object, ...) base::foo(object)
</pre></div></div>

<p>Earlier versions of this manual suggested assigning <code class="code">foo.default &lt;-
base::foo</code>.  This is <strong class="strong">not</strong> a good idea, as it captures the base
function at the time of installation and it might be changed as R is
patched or updated.
</p>
<p>The same idea can be applied for functions in other packages.
</p>
<hr>
</div>
</div>
<div class="chapter-level-extent" id="Linking-GUIs-and-other-front_002dends-to-R">
<div class="nav-panel">
<p>
Next: <a href="#Function-and-variable-index" accesskey="n" rel="next">Function and variable index</a>, Previous: <a href="#Generic-functions-and-methods" accesskey="p" rel="prev">Generic functions and methods</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="chapter" id="Linking-GUIs-and-other-front_002dends-to-R-1"><span>8 Linking GUIs and other front-ends to R<a class="copiable-link" href="#Linking-GUIs-and-other-front_002dends-to-R-1"> &para;</a></span></h2>

<p>There are a number of ways to build front-ends to R: we take this to
mean a GUI or other application that has the ability to submit commands
to R and perhaps to receive results back (not necessarily in a text
format).  There are other routes besides those described here, for
example the package <a class="url" href="https://CRAN.R-project.org/package=Rserve"><strong class="strong">Rserve</strong></a> (from <abbr class="acronym">CRAN</abbr>, see also
<a class="uref" href="https://www.rforge.net/Rserve/">https://www.rforge.net/Rserve/</a>) and connections to Java in
&lsquo;<samp class="samp">JRI</samp>&rsquo; (part of the <a class="url" href="https://CRAN.R-project.org/package=rJava"><strong class="strong">rJava</strong></a> package on <abbr class="acronym">CRAN</abbr>).
</p>
<p>Note that the <abbr class="abbr">API</abbr>s described in this chapter are only intended to be
used in an alternative front-end: they are not part of the API made
available for R packages and can be dangerous to use in a
conventional package (although packages may contain alternative
front-ends).  Conversely some of the functions from the API (such as
<code class="code">R_alloc</code>) should not be used in front-ends.
</p>

<ul class="mini-toc">
<li><a href="#Embedding-R-under-Unix_002dalikes" accesskey="1">Embedding R under Unix-alikes</a></li>
<li><a href="#Embedding-R-under-Windows" accesskey="2">Embedding R under Windows</a></li>
</ul>
<hr>
<div class="section-level-extent" id="Embedding-R-under-Unix_002dalikes">
<div class="nav-panel">
<p>
Next: <a href="#Embedding-R-under-Windows" accesskey="n" rel="next">Embedding R under Windows</a>, Previous: <a href="#Linking-GUIs-and-other-front_002dends-to-R" accesskey="p" rel="prev">Linking GUIs and other front-ends to R</a>, Up: <a href="#Linking-GUIs-and-other-front_002dends-to-R" accesskey="u" rel="up">Linking GUIs and other front-ends to R</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Embedding-R-under-Unix_002dalikes-1"><span>8.1 Embedding R under Unix-alikes<a class="copiable-link" href="#Embedding-R-under-Unix_002dalikes-1"> &para;</a></span></h3>

<p>R can be built as a shared library<a class="footnote" id="DOCF171" href="#FOOT171"><sup>171</sup></a> if configured with <samp class="option">--enable-R-shlib</samp>.  This
shared library can be used to run R from alternative front-end
programs.  We will assume this has been done for the rest of this
section.  Also, it can be built as a static library if configured with
<samp class="option">--enable-R-static-lib</samp>, and that can be used in a very similar
way (at least on Linux: on other platforms one needs to ensure that all
the symbols exported by <samp class="file">libR.a</samp> are linked into the front-end).
</p>
<p>The command-line R front-end, <samp class="file"><var class="var">R_HOME</var>/bin/exec/R</samp>, is one
such example, and the former <abbr class="acronym">GNOME</abbr> (see package <strong class="strong">gnomeGUI</strong>
on <abbr class="acronym">CRAN</abbr>&rsquo;s &lsquo;<samp class="samp">Archive</samp>&rsquo; area) and macOS consoles are others.
The source for <samp class="file"><var class="var">R_HOME</var>/bin/exec/R</samp> is in file
<samp class="file">src/main/Rmain.c</samp> and is very simple
</p>
<a class="index-entry-id" id="index-Rf_005finitialize_005fR"></a>
<a class="index-entry-id" id="index-Rf_005fmainloop"></a>
<div class="example">
<pre class="example-preformatted">int Rf_initialize_R(int ac, char **av); /* in ../unix/system.c */
void Rf_mainloop();                     /* in main.c */

extern int R_running_as_main_program;   /* in ../unix/system.c */

int main(int ac, char **av)
{
    R_running_as_main_program = 1;
    Rf_initialize_R(ac, av);
    Rf_mainloop(); /* does not return */
    return 0;
}
</pre></div>

<p>indeed, misleadingly simple.  Remember that
<samp class="file"><var class="var">R_HOME</var>/bin/exec/R</samp> is run from a shell script
<samp class="file"><var class="var">R_HOME</var>/bin/R</samp> which sets up the environment for the
executable, and this is used for
</p>
<ul class="itemize mark-bullet">
<li>Setting <code class="env">R_HOME</code> and checking it is valid, as well as the path
<code class="env">R_SHARE_DIR</code> and <code class="env">R_DOC_DIR</code> to the installed <samp class="file">share</samp> and
<samp class="file">doc</samp> directory trees.  Also setting <code class="env">R_ARCH</code> if needed.

</li><li>Setting <code class="env">LD_LIBRARY_PATH</code> to include the directories used in linking
R.  This is recorded as the default setting of
<code class="env">R_LD_LIBRARY_PATH</code> in the shell script
<samp class="file"><var class="var">R_HOME</var>/etc<var class="var">R_ARCH</var>/ldpaths</samp>.

</li><li>Processing some of the arguments, for example to run R under a
debugger and to launch alternative front-ends to provide GUIs.
</li></ul>

<p>The first two of these can be achieved for your front-end by running it
<em class="emph">via</em> <code class="command">R CMD</code>. So, for example
</p>
<div class="example">
<pre class="example-preformatted">R CMD /usr/local/lib/R/bin/exec/R
R CMD exec/R
</pre></div>

<p>will both work in a standard R installation. (<code class="command">R CMD</code> looks
first for executables in <samp class="file"><var class="var">R_HOME</var>/bin</samp>.  These command-lines
need modification if a sub-architecture is in use.) If you do not want
to run your front-end in this way, you need to ensure that <code class="env">R_HOME</code>
is set and <code class="env">LD_LIBRARY_PATH</code> is suitable.  (The latter might well
be, but modern Unix/Linux systems do not normally include
<samp class="file">/usr/local/lib</samp> (<samp class="file">/usr/local/lib64</samp> on some architectures),
and R does look there for system components.)
</p>
<p>The other senses in which this example is too simple are that all the
internal defaults are used and that control is handed over to the
R main loop.  There are a number of small examples<a class="footnote" id="DOCF172" href="#FOOT172"><sup>172</sup></a> in the
<samp class="file">tests/Embedding</samp> directory.  These make use of
<code class="code">Rf_initEmbeddedR</code> in <samp class="file">src/main/Rembedded.c</samp>, and essentially
use
<a class="index-entry-id" id="index-Rf_005finitEmbeddedR"></a>
<a class="index-entry-id" id="index-R_005fReplDLLinit"></a>
<a class="index-entry-id" id="index-R_005fReplDLLdo1"></a>
<a class="index-entry-id" id="index-Rf_005fendEmbeddedR"></a>
<a class="index-entry-id" id="index-run_005fRmainloop"></a>
</p><div class="example">
<pre class="example-preformatted">#include &lt;Rembedded.h&gt;

int main(int ac, char **av)
{
    /* do some setup */
    Rf_initEmbeddedR(argc, argv);
    /* do some more setup */

    /* submit some code to R, which is done interactively via
        run_Rmainloop();

        A possible substitute for a pseudo-console is

        R_ReplDLLinit();
        while(R_ReplDLLdo1() &gt; 0) {
        /* add user actions here if desired */
       }

     */
    Rf_endEmbeddedR(0);
    /* final tidying up after R is shutdown */
    return 0;
}
</pre></div>

<p>If you do not want to pass R arguments, you can fake an <code class="code">argv</code>
array, for example by
</p>
<div class="example">
<pre class="example-preformatted">    char *argv[]= {&quot;REmbeddedPostgres&quot;, &quot;--silent&quot;};
    Rf_initEmbeddedR(sizeof(argv)/sizeof(argv[0]), argv);
</pre></div>

<p>However, to make a GUI we usually do want to run <code class="code">run_Rmainloop</code>
after setting up various parts of R to talk to our GUI, and arranging
for our GUI callbacks to be called during the R mainloop.
</p>
<p>One issue to watch is that on some platforms <code class="code">Rf_initEmbeddedR</code> and
<code class="code">Rf_endEmbeddedR</code> change the settings of the <abbr class="abbr">FPU</abbr> (e.g. to allow
errors to be trapped and to make use of extended precision registers).
</p>
<p>The standard code sets up a session temporary directory in the usual
way, <em class="emph">unless</em> <code class="code">R_TempDir</code> is set to a non-NULL value before
<code class="code">Rf_initEmbeddedR</code> is called.  In that case the value is assumed to
contain an existing writable directory, and it is not
cleaned up when R is shut down.
</p>
<p><code class="code">Rf_initEmbeddedR</code> sets R to be in interactive mode: you can set
<code class="code">R_Interactive</code> (defined in <samp class="file">Rinterface.h</samp>) subsequently to
change this.
</p>
<p>Note that R expects to be run with the locale category
&lsquo;<samp class="samp">LC_NUMERIC</samp>&rsquo; set to its default value of <code class="code">C</code>, and so should
not be embedded into an application which changes that.
</p>
<p>It is the user&rsquo;s responsibility to attempt to initialize only once.  To
protect the R interpreter, <code class="code">Rf_initialize_R</code> will exit the
process if re-initialization is attempted.
</p>

<ul class="mini-toc">
<li><a href="#Compiling-against-the-R-library" accesskey="1">Compiling against the R library</a></li>
<li><a href="#Setting-R-callbacks" accesskey="2">Setting R callbacks</a></li>
<li><a href="#Registering-symbols" accesskey="3">Registering symbols</a></li>
<li><a href="#Meshing-event-loops" accesskey="4">Meshing event loops</a></li>
<li><a href="#Threading-issues" accesskey="5">Threading issues</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Compiling-against-the-R-library">
<div class="nav-panel">
<p>
Next: <a href="#Setting-R-callbacks" accesskey="n" rel="next">Setting R callbacks</a>, Previous: <a href="#Embedding-R-under-Unix_002dalikes" accesskey="p" rel="prev">Embedding R under Unix-alikes</a>, Up: <a href="#Embedding-R-under-Unix_002dalikes" accesskey="u" rel="up">Embedding R under Unix-alikes</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Compiling-against-the-R-library-1"><span>8.1.1 Compiling against the R library<a class="copiable-link" href="#Compiling-against-the-R-library-1"> &para;</a></span></h4>

<p>Suitable flags to compile and link against the R (shared or static)
library can be found by
</p>
<div class="example">
<pre class="example-preformatted">R CMD config --cppflags
R CMD config --ldflags
</pre></div>

<p>(These apply only to an uninstalled copy or a standard install.)
</p>
<p>If R is installed, <code class="code">pkg-config</code> is available and neither
sub-architectures nor a macOS framework have been used, alternatives for
a shared R library are
</p>
<div class="example">
<pre class="example-preformatted">pkg-config --cflags libR
pkg-config --libs libR
</pre></div>

<p>and for a static R library
</p>
<div class="example">
<pre class="example-preformatted">pkg-config --cflags libR
pkg-config --static --libs libR
</pre></div>

<p>(This may work for an installed OS framework if <code class="code">pkg-config</code> is
taught where to look for <samp class="file">libR.pc</samp>: it is installed inside the
framework.)
</p>
<p>However, a more comprehensive way is to set up a <samp class="file">Makefile</samp> to
compile the front-end.  Suppose file <samp class="file">myfe.c</samp> is to be compiled to
<samp class="file">myfe</samp>. A suitable <samp class="file">Makefile</samp> might be
</p>
<div class="example">
<pre class="example-preformatted">## WARNING: does not work when ${R_HOME} contains spaces
include ${R_HOME}/etc${R_ARCH}/Makeconf
all: myfe

## The following is not needed, but avoids PIC flags.
myfe.o: myfe.c
        $(CC) $(ALL_CPPFLAGS) $(CFLAGS) -c myfe.c -o $@

## replace $(LIBR) $(LIBS) by $(STATIC_LIBR) if R was build with a static libR
myfe: myfe.o
        $(MAIN_LINK) -o $@ myfe.o $(LIBR) $(LIBS)
</pre></div>

<p>invoked as
</p>
<div class="example">
<pre class="example-preformatted">R CMD make
R CMD myfe
</pre></div>

<p>Even though not recommended, <code class="code">${R_HOME}</code> may contain spaces.  In
that case, it cannot be passed as an argument to <code class="code">include</code> in the
makefile.  Instead, one can instruct <code class="command">make</code> using the <code class="code">-f</code>
option to include <samp class="file">Makeconf</samp>, for example <em class="emph">via</em> recursive
invocation of <code class="command">make</code>, see <a class="ref" href="#Writing-portable-packages">Writing portable packages</a>.
</p>
<div class="example">
<pre class="example-preformatted">all:
      $(MAKE) -f &quot;${R_HOME}/etc${R_ARCH}/Makeconf&quot; -f Makefile.inner
</pre></div>
  
<p>Additional flags which <code class="code">$(MAIN_LINK)</code> includes are, amongst others,
those to select <abbr class="abbr">OpenMP</abbr> and <samp class="option">--export-dynamic</samp> for the GNU linker
on some platforms.  In principle <code class="code">$(LIBS)</code> is not needed
when using a shared R library as <samp class="file">libR</samp> is linked against
those libraries, but some platforms need the executable also linked
against them.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Setting-R-callbacks">
<div class="nav-panel">
<p>
Next: <a href="#Registering-symbols" accesskey="n" rel="next">Registering symbols</a>, Previous: <a href="#Compiling-against-the-R-library" accesskey="p" rel="prev">Compiling against the R library</a>, Up: <a href="#Embedding-R-under-Unix_002dalikes" accesskey="u" rel="up">Embedding R under Unix-alikes</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Setting-R-callbacks-1"><span>8.1.2 Setting R callbacks<a class="copiable-link" href="#Setting-R-callbacks-1"> &para;</a></span></h4>

<p>For Unix-alikes there is a public header file <samp class="file">Rinterface.h</samp> that
makes it possible to change the standard callbacks used by R in a
documented way.  This defines pointers (if <code class="code">R_INTERFACE_PTRS</code> is
defined)
</p>
<div class="example">
<pre class="example-preformatted">extern void (*ptr_R_Suicide)(const char *);
extern void (*ptr_R_ShowMessage)(const char *);
extern int  (*ptr_R_ReadConsole)(const char *, unsigned char *, int, int);
extern void (*ptr_R_WriteConsole)(const char *, int);
extern void (*ptr_R_WriteConsoleEx)(const char *, int, int);
extern void (*ptr_R_ResetConsole)();
extern void (*ptr_R_FlushConsole)();
extern void (*ptr_R_ClearerrConsole)();
extern void (*ptr_R_Busy)(int);
extern void (*ptr_R_CleanUp)(SA_TYPE, int, int);
extern int  (*ptr_R_ShowFiles)(int, const char **, const char **,
                               const char *, Rboolean, const char *);
extern int  (*ptr_R_ChooseFile)(int, char *, int);
extern int  (*ptr_R_EditFile)(const char *);
extern void (*ptr_R_loadhistory)(SEXP, SEXP, SEXP, SEXP);
extern void (*ptr_R_savehistory)(SEXP, SEXP, SEXP, SEXP);
extern void (*ptr_R_addhistory)(SEXP, SEXP, SEXP, SEXP);
extern int  (*ptr_R_EditFiles)(int, const char **, const char **, const char *);
extern SEXP (*ptr_do_selectlist)(SEXP, SEXP, SEXP, SEXP);
extern SEXP (*ptr_do_dataentry)(SEXP, SEXP, SEXP, SEXP);
extern SEXP (*ptr_do_dataviewer)(SEXP, SEXP, SEXP, SEXP);
extern void (*ptr_R_ProcessEvents)();
</pre></div>

<p>which allow standard R callbacks to be redirected to your GUI.  What
these do is generally documented in the file <samp class="file">src/unix/system.txt</samp>.
</p>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fShowMessage"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_ShowMessage</strong> <code class="def-code-arguments">(char *<var class="var">message</var>)</code><a class="copiable-link" href="#index-R_005fShowMessage"> &para;</a></span></dt>
<dd><p>This should display the message, which may have multiple lines:  it
should be brought to the user&rsquo;s attention immediately.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fBusy"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_Busy</strong> <code class="def-code-arguments">(int <var class="var">which</var>)</code><a class="copiable-link" href="#index-R_005fBusy"> &para;</a></span></dt>
<dd><p>This function invokes actions (such as change of cursor) when R
embarks on an extended computation (<code class="code"><var class="var">which</var>=1</code>) and when such
a state terminates (<code class="code"><var class="var">which</var>=0</code>).
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fReadConsole"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">R_ReadConsole</strong> <code class="def-code-arguments">(const char *<var class="var">prompt</var>, unsigned char *<var class="var">buf</var>,   int <var class="var">buflen</var>, int <var class="var">hist</var>)</code><a class="copiable-link" href="#index-R_005fReadConsole"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fWriteConsole"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_WriteConsole</strong> <code class="def-code-arguments">(const char *<var class="var">buf</var>, int <var class="var">buflen</var>)</code><a class="copiable-link" href="#index-R_005fWriteConsole"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fWriteConsoleEx"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_WriteConsoleEx</strong> <code class="def-code-arguments">(const char *<var class="var">buf</var>, int <var class="var">buflen</var>, int <var class="var">otype</var>)</code><a class="copiable-link" href="#index-R_005fWriteConsoleEx"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fResetConsole"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_ResetConsole</strong> <code class="def-code-arguments">()</code><a class="copiable-link" href="#index-R_005fResetConsole"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fFlushConsole"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_FlushConsole</strong> <code class="def-code-arguments">()</code><a class="copiable-link" href="#index-R_005fFlushConsole"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fClearerrConsole"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_ClearerrConsole</strong> <code class="def-code-arguments">()</code><a class="copiable-link" href="#index-R_005fClearerrConsole"> &para;</a></span></dt>
<dd>
<p>These functions interact with a console.
</p>
<p><code class="code">R_ReadConsole</code> prints the given prompt at the console and then
does a <code class="code">fgets(3)</code>&ndash;like operation, transferring up to <var class="var">buflen</var>
characters into the buffer <var class="var">buf</var>. The last two bytes should be
set to &lsquo;<samp class="samp">&quot;\n\0&quot;</samp>&rsquo; to preserve sanity.  If <var class="var">hist</var> is non-zero,
then the line should be added to any command history which is being
maintained.  The return value is 0 is no input is available and &gt;0
otherwise.
</p>
<p><code class="code">R_WriteConsoleEx</code> writes the given buffer to the console,
<var class="var">otype</var> specifies the output type (regular output or
warning/error). Call to <code class="code">R_WriteConsole(buf, buflen)</code> is equivalent
to <code class="code">R_WriteConsoleEx(buf, buflen, 0)</code>. To ensure backward
compatibility of the callbacks, <code class="code">ptr_R_WriteConsoleEx</code> is used only
if <code class="code">ptr_R_WriteConsole</code> is set to <code class="code">NULL</code>.  To ensure that
<code class="code">stdout()</code> and <code class="code">stderr()</code> connections point to the console,
set the corresponding files to <code class="code">NULL</code> <em class="emph">via</em>
</p><div class="example">
<pre class="example-preformatted">      R_Outputfile = NULL;
      R_Consolefile = NULL;
</pre></div>

<p><code class="code">R_ResetConsole</code> is called when the system is reset after an error.
<code class="code">R_FlushConsole</code> is called to flush any pending output to the
system console.  <code class="code">R_ClearerrConsole</code> clears any errors associated
with reading from the console.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fShowFiles"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">R_ShowFiles</strong> <code class="def-code-arguments">(int <var class="var">nfile</var>, const char **<var class="var">file</var>,   const char **<var class="var">headers</var>, const char *<var class="var">wtitle</var>, Rboolean <var class="var">del</var>,   const char *<var class="var">pager</var>)</code><a class="copiable-link" href="#index-R_005fShowFiles"> &para;</a></span></dt>
<dd>
<p>This function is used to display the contents of files.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fChooseFile"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">R_ChooseFile</strong> <code class="def-code-arguments">(int <var class="var">new</var>, char *<var class="var">buf</var>,   int <var class="var">len</var>)</code><a class="copiable-link" href="#index-R_005fChooseFile"> &para;</a></span></dt>
<dd>
<p>Choose a file and return its name in <var class="var">buf</var> of length <var class="var">len</var>.
Return value is 0 for success, &gt; 0 otherwise.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fEditFile"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">R_EditFile</strong> <code class="def-code-arguments">(const char *<var class="var">buf</var>)</code><a class="copiable-link" href="#index-R_005fEditFile"> &para;</a></span></dt>
<dd><p>Send a file to an editor window.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fEditFiles"><span class="category-def">Function: </span><span><code class="def-type">int</code> <strong class="def-name">R_EditFiles</strong> <code class="def-code-arguments">(int <var class="var">nfile</var>, const char **<var class="var">file</var>, const char **<var class="var">title</var>, const char *<var class="var">editor</var>)</code><a class="copiable-link" href="#index-R_005fEditFiles"> &para;</a></span></dt>
<dd><p>Send <var class="var">nfile</var> files to an editor, with titles possibly to be used for
the editor window(s).
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005floadhistory"><span class="category-def">Function: </span><span><code class="def-type">SEXP</code> <strong class="def-name">R_loadhistory</strong> <code class="def-code-arguments">(SEXP, SEXP, SEXP, SEXP);</code><a class="copiable-link" href="#index-R_005floadhistory"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fsavehistory"><span class="category-def">Function: </span><span><code class="def-type">SEXP</code> <strong class="def-name">R_savehistory</strong> <code class="def-code-arguments">(SEXP, SEXP, SEXP, SEXP);</code><a class="copiable-link" href="#index-R_005fsavehistory"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005faddhistory"><span class="category-def">Function: </span><span><code class="def-type">SEXP</code> <strong class="def-name">R_addhistory</strong> <code class="def-code-arguments">(SEXP, SEXP, SEXP, SEXP);</code><a class="copiable-link" href="#index-R_005faddhistory"> &para;</a></span></dt>
<dd>
<p><code class="code">.Internal</code> functions for <code class="code">loadhistory</code>, <code class="code">savehistory</code>
and <code class="code">timestamp</code>.
</p>
<p>If the console has no history mechanism these can be as
simple as
</p>
<div class="example">
<pre class="example-preformatted">SEXP R_loadhistory (SEXP call, SEXP op, SEXP args, SEXP env)
{
    errorcall(call, &quot;loadhistory is not implemented&quot;);
    return R_NilValue;
}
SEXP R_savehistory (SEXP call, SEXP op , SEXP args, SEXP env)
{
    errorcall(call, &quot;savehistory is not implemented&quot;);
    return R_NilValue;
}
SEXP R_addhistory (SEXP call, SEXP op , SEXP args, SEXP env)
{
    return R_NilValue;
}
</pre></div>

<p>The <code class="code">R_addhistory</code> function should return silently if no history
mechanism is present, as a user may be calling <code class="code">timestamp</code> purely
to write the time stamp to the console.
</p></dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fSuicide"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_Suicide</strong> <code class="def-code-arguments">(const char *<var class="var">message</var>)</code><a class="copiable-link" href="#index-R_005fSuicide"> &para;</a></span></dt>
<dd><p>This should abort R as rapidly as possible, displaying the message.
A possible implementation is
</p>
<div class="example">
<pre class="example-preformatted">void R_Suicide (const char *message)
{
    char  pp[1024];
    snprintf(pp, 1024, &quot;Fatal error: %s\n&quot;, message);
    R_ShowMessage(pp);
    R_CleanUp(SA_SUICIDE, 2, 0);
}
</pre></div>
</dd></dl>

<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fCleanUp"><span class="category-def">Function: </span><span><code class="def-type">void</code> <strong class="def-name">R_CleanUp</strong> <code class="def-code-arguments">(SA_TYPE <var class="var">saveact</var>, int <var class="var">status</var>,   int <var class="var">RunLast</var>)</code><a class="copiable-link" href="#index-R_005fCleanUp"> &para;</a></span></dt>
<dd>
<p>This function invokes any actions which occur at system termination.
It needs to be quite complex:
</p>
<div class="example">
<pre class="example-preformatted">#include &lt;Rinterface.h&gt;
#include &lt;Rembedded.h&gt;    /* for Rf_KillAllDevices */

void R_CleanUp (SA_TYPE saveact, int status, int RunLast)
{
    if(saveact == SA_DEFAULT) saveact = SaveAction;
    if(saveact == SA_SAVEASK) {
       /* ask what to do and set saveact */
    }
    switch (saveact) {
    case SA_SAVE:
        if(runLast) R_dot_Last();
        if(R_DirtyImage) R_SaveGlobalEnv();
        /* save the console history in R_HistoryFile */
        break;
    case SA_NOSAVE:
        if(runLast) R_dot_Last();
        break;
    case SA_SUICIDE:
    default:
        break;
    }

    R_RunExitFinalizers();
    /* clean up after the editor e.g. CleanEd() */

    R_CleanTempDir();

    /* close all the graphics devices */
    if(saveact != SA_SUICIDE) Rf_KillAllDevices();
    fpu_setup(FALSE);

    exit(status);
}
</pre></div>
</dd></dl>
<a class="index-entry-id" id="index-R_005fdot_005fLast"></a>
<a class="index-entry-id" id="index-R_005fRunExitFinalizers"></a>
<a class="index-entry-id" id="index-R_005fCleanTempDir"></a>
<a class="index-entry-id" id="index-R_005fSaveGlobalEnv"></a>
<a class="index-entry-id" id="index-Rf_005fKillAllDevices"></a>
<a class="index-entry-id" id="index-CleanEd"></a>
<a class="index-entry-id" id="index-fpu_005fsetup"></a>

<p>These callbacks should never be changed in a running R session (and
hence cannot be called from an extension package).
</p>
<dl class="first-deftypefn first-deftypefun-alias-first-deftypefn">
<dt class="deftypefn deftypefun-alias-deftypefn" id="index-R_005fdataentry"><span class="category-def">Function: </span><span><code class="def-type">SEXP</code> <strong class="def-name">R_dataentry</strong> <code class="def-code-arguments">(SEXP, SEXP, SEXP, SEXP);</code><a class="copiable-link" href="#index-R_005fdataentry"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fdataviewer"><span class="category-def">Function: </span><span><code class="def-type">SEXP</code> <strong class="def-name">R_dataviewer</strong> <code class="def-code-arguments">(SEXP, SEXP, SEXP, SEXP);</code><a class="copiable-link" href="#index-R_005fdataviewer"> &para;</a></span></dt>
<dt class="deftypefnx deftypefunx-alias-deftypefnx def-cmd-deftypefn" id="index-R_005fselectlist"><span class="category-def">Function: </span><span><code class="def-type">SEXP</code> <strong class="def-name">R_selectlist</strong> <code class="def-code-arguments">(SEXP, SEXP, SEXP, SEXP);</code><a class="copiable-link" href="#index-R_005fselectlist"> &para;</a></span></dt>
<dd>
<p><code class="code">.External</code> functions for <code class="code">dataentry</code> (and <code class="code">edit</code> on
matrices and data frames), <code class="code">View</code> and <code class="code">select.list</code>.  These
can be changed if they are not currently in use.
</p></dd></dl>


<hr>
</div>
<div class="subsection-level-extent" id="Registering-symbols">
<div class="nav-panel">
<p>
Next: <a href="#Meshing-event-loops" accesskey="n" rel="next">Meshing event loops</a>, Previous: <a href="#Setting-R-callbacks" accesskey="p" rel="prev">Setting R callbacks</a>, Up: <a href="#Embedding-R-under-Unix_002dalikes" accesskey="u" rel="up">Embedding R under Unix-alikes</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Registering-symbols-1"><span>8.1.3 Registering symbols<a class="copiable-link" href="#Registering-symbols-1"> &para;</a></span></h4>

<p>An application embedding R needs a different way of registering
symbols because it is not a dynamic library loaded by R as would be
the case with a package.  Therefore R reserves a special
<code class="code">DllInfo</code> entry for the embedding application such that it can
register symbols to be used with <code class="code">.C</code>, <code class="code">.Call</code> etc.  This
entry can be obtained by calling <code class="code">getEmbeddingDllInfo</code>, so a
typical use is
</p>
<a class="index-entry-id" id="index-R_005fgetEmbeddingDllInfo"></a>
<div class="example">
<pre class="example-preformatted">DllInfo *info = R_getEmbeddingDllInfo();
R_registerRoutines(info, cMethods, callMethods, NULL, NULL);
</pre></div>

<p>The native routines defined by <code class="code">cMethods</code> and <code class="code">callMethods</code>
should be present in the embedding application.  See <a class="ref" href="#Registering-native-routines">Registering native routines</a> for details on registering symbols in general.
</p>

<hr>
</div>
<div class="subsection-level-extent" id="Meshing-event-loops">
<div class="nav-panel">
<p>
Next: <a href="#Threading-issues" accesskey="n" rel="next">Threading issues</a>, Previous: <a href="#Registering-symbols" accesskey="p" rel="prev">Registering symbols</a>, Up: <a href="#Embedding-R-under-Unix_002dalikes" accesskey="u" rel="up">Embedding R under Unix-alikes</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Meshing-event-loops-1"><span>8.1.4 Meshing event loops<a class="copiable-link" href="#Meshing-event-loops-1"> &para;</a></span></h4>

<p>One of the most difficult issues in interfacing R to a front-end is
the handling of event loops, at least if a single thread is used.  R
uses events and timers for
</p>
<ul class="itemize mark-bullet">
<li>Running X11 windows such as the graphics device and data editor, and
interacting with them (e.g., using <code class="code">locator()</code>).

</li><li>Supporting Tcl/Tk events for the <strong class="strong">tcltk</strong> package (for at least the
X11 version of Tk).

</li><li>Preparing input.

</li><li>Timing operations, for example for profiling R code and
<code class="code">Sys.sleep()</code>.

</li><li>Interrupts, where permitted.
</li></ul>

<p>Specifically, the Unix-alike command-line version of R runs separate
event loops for
</p>
<ul class="itemize mark-bullet">
<li>Preparing input at the console command-line, in file
<samp class="file">src/unix/sys-unix.c</samp>.

</li><li>Waiting for a response from a socket in the internal functions for
direct socket access in file
<samp class="file">src/modules/internet/Rsock.c</samp>
and for the interface to <code class="code">libcurl</code>.

</li><li>Mouse and window events when displaying the X11-based dataentry window,
in file <samp class="file">src/modules/X11/dataentry.c</samp>.  This is regarded as
<em class="emph">modal</em>, and no other events are serviced whilst it is active.
</li></ul>

<p>There is a protocol for adding event handlers to the first two types of
event loops, using types and functions declared in the header
<samp class="file">R_ext/eventloop.h</samp> and described in comments in file
<samp class="file">src/unix/sys-std.c</samp>.  It is possible to add (or remove) an input
handler for events on a particular file descriptor, or to set a polling
interval (<em class="emph">via</em> <code class="code">R_wait_usec</code>) and a function to be called
periodically <em class="emph">via</em> <code class="code">R_PolledEvents</code>: the polling mechanism is used by
the <strong class="strong">tcltk</strong> package.
<a class="index-entry-id" id="index-R_005fPolledEvents"></a>
<a class="index-entry-id" id="index-R_005fwait_005fusec"></a>
</p>
<p>It is not intended that these facilities are used by packages, but if
they are needed exceptionally, the package should ensure that it cleans
up and removes its handlers when its namespace is unloaded.  Note that
the header <samp class="file">sys/select.h</samp> is needed<a class="footnote" id="DOCF173" href="#FOOT173"><sup>173</sup></a>: users should check this is available and define
<code class="code">HAVE_SYS_SELECT_H</code> before including <samp class="file">R_ext/eventloop.h</samp>. (It
is often the case that another header will include <samp class="file">sys/select.h</samp>
before <samp class="file">eventloop.h</samp> is processed, but this should not be relied
on.)
</p>
<p>An alternative front-end needs both to make provision for other R
events whilst waiting for input, and to ensure that it is not frozen out
during events of the second type.  The ability to add a polled handler
as <code class="code">R_timeout_handler</code> is used by the <strong class="strong">tcltk</strong> package.
</p>

<hr>
</div>
<div class="subsection-level-extent" id="Threading-issues">
<div class="nav-panel">
<p>
Previous: <a href="#Meshing-event-loops" accesskey="p" rel="prev">Meshing event loops</a>, Up: <a href="#Embedding-R-under-Unix_002dalikes" accesskey="u" rel="up">Embedding R under Unix-alikes</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Threading-issues-1"><span>8.1.5 Threading issues<a class="copiable-link" href="#Threading-issues-1"> &para;</a></span></h4>

<p>Embedded R is designed to be run in the main thread, and all the
testing is done in that context.  There is a potential issue with the
stack-checking mechanism where threads are involved.  This uses two
variables declared in <samp class="file">Rinterface.h</samp> (if <code class="code">CSTACK_DEFNS</code> is
defined) as
</p>
<div class="example">
<pre class="example-preformatted">extern uintptr_t R_CStackLimit; /* C stack limit */
extern uintptr_t R_CStackStart; /* Initial stack address */
</pre></div>

<p>Note that <code class="code">uintptr_t</code> is an optional C99 type for which a
substitute is defined in R, so your code needs to define
<code class="code">HAVE_UINTPTR_T</code> appropriately.  To do so, test if the type is
defined in C header <samp class="file">stdint.h</samp> or C++ header <samp class="file">cstdint</samp> and if
so include the header and define <code class="code">HAVE_UINTPTR_T</code> before including
<samp class="file">Rinterface.h</samp>.  (For C code one can simply include
<samp class="file">Rconfig.h</samp>, possibly <em class="emph">via</em> <samp class="file">R.h</samp>, and for C++11 code
<samp class="file">Rinterface.h</samp> will include the header <samp class="file">cstdint</samp>.)
</p>
<p>These will be set<a class="footnote" id="DOCF174" href="#FOOT174"><sup>174</sup></a> when <code class="code">Rf_initialize_R</code> is called, to values appropriate to
the main thread.  Stack-checking can be disabled by setting
<code class="code">R_CStackLimit = (uintptr_t)-1</code> immediately after
<code class="code">Rf_initialize_R</code> is called, but it is better to if possible set
appropriate values.  (What these are and how to determine them are
OS-specific, and the stack size limit may differ for secondary threads.
If you have a choice of stack size, at least 10Mb is recommended.)
</p>
<p>You may also want to consider how signals are handled: R sets signal
handlers for several signals, including <code class="code">SIGINT</code>, <code class="code">SIGSEGV</code>,
<code class="code">SIGPIPE</code>, <code class="code">SIGUSR1</code> and <code class="code">SIGUSR2</code>, but these can all be
suppressed by setting the variable <code class="code">R_SignalHandlers</code> (declared in
<samp class="file">Rinterface.h</samp>) to <code class="code">0</code>.
</p>
<p>Note that these variables must not be changed by an R
<strong class="strong">package</strong>: a package should not call R internals which
makes use of the stack-checking mechanism on a secondary thread.
</p>
<hr>
</div>
</div>
<div class="section-level-extent" id="Embedding-R-under-Windows">
<div class="nav-panel">
<p>
Previous: <a href="#Embedding-R-under-Unix_002dalikes" accesskey="p" rel="prev">Embedding R under Unix-alikes</a>, Up: <a href="#Linking-GUIs-and-other-front_002dends-to-R" accesskey="u" rel="up">Linking GUIs and other front-ends to R</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h3 class="section" id="Embedding-R-under-Windows-1"><span>8.2 Embedding R under Windows<a class="copiable-link" href="#Embedding-R-under-Windows-1"> &para;</a></span></h3>

<p>This section is only about &lsquo;<samp class="samp">x86_64</samp>&rsquo; Windows.
</p>
<p>All Windows interfaces to R call entry points in the DLL
<samp class="file">R.dll</samp>, directly or indirectly.  Simpler applications may find it
easier to use the indirect route <em class="emph">via</em> <abbr class="acronym">(D)COM</abbr>.
</p>

<ul class="mini-toc">
<li><a href="#Using-_0028D_0029COM" accesskey="1">Using (D)COM</a></li>
<li><a href="#Calling-R_002edll-directly" accesskey="2">Calling <samp class="file">R.dll</samp> directly</a></li>
<li><a href="#Finding-R_005fHOME" accesskey="3">Finding R_HOME</a></li>
</ul>
<hr>
<div class="subsection-level-extent" id="Using-_0028D_0029COM">
<div class="nav-panel">
<p>
Next: <a href="#Calling-R_002edll-directly" accesskey="n" rel="next">Calling <samp class="file">R.dll</samp> directly</a>, Previous: <a href="#Embedding-R-under-Windows" accesskey="p" rel="prev">Embedding R under Windows</a>, Up: <a href="#Embedding-R-under-Windows" accesskey="u" rel="up">Embedding R under Windows</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Using-_0028D_0029COM-1"><span>8.2.1 Using (D)COM<a class="copiable-link" href="#Using-_0028D_0029COM-1"> &para;</a></span></h4>

<p><abbr class="acronym">(D)COM</abbr> is a standard Windows mechanism used for communication
between Windows applications.  One application (here R) is run as COM
server which offers services to clients, here the front-end calling
application.  The services are described in a &lsquo;Type Library&rsquo; and are
(more or less) language-independent, so the calling application can be
written in C or C++ or Visual Basic or Perl or Python and so on.
The &lsquo;D&rsquo; in (D)COM refers to &lsquo;distributed&rsquo;, as the client and server can
be running on different machines.
</p>
<p>The basic R distribution is not a (D)COM server, but two addons are
currently available that interface directly with R and provide a
(D)COM server:
</p><ul class="itemize mark-bullet">
<li>There is a (D)COM server called <code class="code">StatConnector</code> written by
Thomas Baier available <em class="emph">via</em> <a class="uref" href="https://www.autstat.com/">https://www.autstat.com/</a>,
which works with R packages to support transfer of data to and from
R and remote execution of R commands, as well as embedding of an
R graphics window.

<p>Recent versions have usage restrictions.
</p>
</li></ul>
<hr>
</div>
<div class="subsection-level-extent" id="Calling-R_002edll-directly">
<div class="nav-panel">
<p>
Next: <a href="#Finding-R_005fHOME" accesskey="n" rel="next">Finding R_HOME</a>, Previous: <a href="#Using-_0028D_0029COM" accesskey="p" rel="prev">Using (D)COM</a>, Up: <a href="#Embedding-R-under-Windows" accesskey="u" rel="up">Embedding R under Windows</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Calling-R_002edll-directly-1"><span>8.2.2 Calling <samp class="file">R.dll</samp> directly<a class="copiable-link" href="#Calling-R_002edll-directly-1"> &para;</a></span></h4>

<p>The <code class="code">R</code> DLL is mainly written in C and has <code class="code">_cdecl</code> entry
points.  Calling it directly will be tricky except from C code (or C++
with a little care).
</p>
<p>There is a version of the Unix-alike interface calling
</p>
<div class="example">
<pre class="example-preformatted">int Rf_initEmbeddedR(int ac, char **av);
void Rf_endEmbeddedR(int fatal);
</pre></div>

<p>which is an entry point in <samp class="file">R.dll</samp>.  Examples of its use (and a
suitable <samp class="file">Makefile.win</samp>) can be found in the <samp class="file">tests/Embedding</samp>
directory of the sources.  You may need to ensure that
<samp class="file"><var class="var">R_HOME</var>/bin</samp> is in your <code class="env">PATH</code> so the R DLLs are found.
</p>
<p>Examples of calling <samp class="file">R.dll</samp> directly are provided in the directory
<samp class="file">src/gnuwin32/front-ends</samp>, including a simple command-line
front end <samp class="file">rtest.c</samp> whose code is
</p>
<a class="index-entry-id" id="index-setup_005fRmainloop"></a>
<a class="index-entry-id" id="index-R_005fsetStartTime"></a>
<a class="index-entry-id" id="index-R_005fset_005fcommand_005fline_005farguments"></a>
<div class="example smallexample">
<pre class="example-preformatted">#define Win32
#include &lt;windows.h&gt;
#include &lt;stdio.h&gt;
#include &lt;Rversion.h&gt;
#define LibExtern __declspec(dllimport) extern
#include &lt;Rembedded.h&gt;
#include &lt;R_ext/RStartup.h&gt;
/* for askok and askyesnocancel */
#include &lt;graphapp.h&gt;

/* for signal-handling code */
#include &lt;psignal.h&gt;

/* simple input, simple output */

/* This version blocks all events: a real one needs to call ProcessEvents
   frequently. See rterm.c and ../system.c for one approach using
   a separate thread for input.
*/
int myReadConsole(const char *prompt, unsigned char *buf, int len, int addtohistory)
{
    fputs(prompt, stdout);
    fflush(stdout);
    if(fgets((char *)buf, len, stdin)) return 1; else return 0;
}

void myWriteConsole(const char *buf, int len)
{
    printf(&quot;%s&quot;, buf);
}

void myCallBack(void)
{
    /* called during i/o, eval, graphics in ProcessEvents */
}

void myBusy(int which)
{
    /* set a busy cursor ... if which = 1, unset if which = 0 */
}

static void my_onintr(int sig) { UserBreak = 1; }

int main (int argc, char **argv)
{
    structRstart rp;
    Rstart Rp = &amp;rp;
    char Rversion[25], *RHome, *RUser;

    sprintf(Rversion, &quot;%s.%s&quot;, R_MAJOR, R_MINOR);
    if(strcmp(getDLLVersion(), Rversion) != 0) {
        fprintf(stderr, &quot;Error: R.DLL version does not match\n&quot;);
        exit(1);
    }

    R_setStartTime();
    R_DefParamsEx(Rp, RSTART_VERSION);
    if((RHome = get_R_HOME()) == NULL) {
        fprintf(stderr, &quot;R_HOME must be set in the environment or Registry\n&quot;);
        exit(1);
    }
    Rp-&gt;rhome = RHome;
    RUser = getRUser();
    Rp-&gt;home = RUser;
    Rp-&gt;CharacterMode = LinkDLL;
    Rp-&gt;EmitEmbeddedUTF8 = FALSE;
    Rp-&gt;ReadConsole = myReadConsole;
    Rp-&gt;WriteConsole = myWriteConsole;
    Rp-&gt;CallBack = myCallBack;
    Rp-&gt;ShowMessage = askok;
    Rp-&gt;YesNoCancel = askyesnocancel;
    Rp-&gt;Busy = myBusy;
    
    Rp-&gt;R_Quiet = TRUE;        /* Default is FALSE */
    Rp-&gt;R_Interactive = FALSE; /* Default is TRUE */
    Rp-&gt;RestoreAction = SA_RESTORE;
    Rp-&gt;SaveAction = SA_NOSAVE;
    R_SetParams(Rp);
    freeRUser(RUser);
    free_R_HOME(RHome);
    R_set_command_line_arguments(argc, argv);

    FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));

    signal(SIGBREAK, my_onintr);
    GA_initapp(0, 0);
    readconsolecfg();
    setup_Rmainloop();
#ifdef SIMPLE_CASE
    run_Rmainloop();
#else
    R_ReplDLLinit();
    while(R_ReplDLLdo1() &gt; 0) {
/* add user actions here if desired */
    }
/* only get here on EOF (not q()) */
#endif
    Rf_endEmbeddedR(0);
    return 0;
}
</pre></div>

<p>The ideas are
</p>
<ul class="itemize mark-bullet">
<li>Check that the front-end and the linked <samp class="file">R.dll</samp> match &ndash; other
front-ends may allow a looser match.

</li><li>Find and set the R home directory and the user&rsquo;s home directory.  The
former may be available from the Windows Registry: it will be in
<code class="code">HKEY_LOCAL_MACHINE\Software\R-core\R\InstallPath</code> from an
administrative install and
<code class="code">HKEY_CURRENT_USER\Software\R-core\R\InstallPath</code> otherwise, if
selected during installation (as it is by default).

</li><li><a class="index-entry-id" id="index-R_005fDefParams"></a>
<a class="index-entry-id" id="index-R_005fDefParamsEx"></a>
<a class="index-entry-id" id="index-R_005fSetParams"></a>
Define startup conditions and callbacks <em class="emph">via</em> the <code class="code">Rstart</code> structure.
<code class="code">R_DefParams</code> sets the defaults, and <code class="code">R_SetParams</code> sets
updated values. <code class="code">R_DefParamsEx</code> takes an extra argument, the version
number of the <code class="code">Rstart</code> structure provided (<code class="code">RSTART_VERSION</code> refers
to the current version) and returns a non-zero status when that version is
not supported by R.

</li><li>Record the command-line arguments used by
<code class="code">R_set_command_line_arguments</code> for use by the R function
<code class="code">commandArgs()</code>.

</li><li>Set up the signal handler and the basic user interface.

</li><li>Run the main R loop, possibly with our actions intermeshed.

</li><li>Arrange to clean up.
</li></ul>

<p>An underlying theme is the need to keep the GUI &lsquo;alive&rsquo;, and this has
not been done in this example.  The R callback <code class="code">R_ProcessEvents</code>
needs to be called frequently to ensure that Windows events in R
windows are handled expeditiously.  Conversely, R needs to allow the
GUI code (which is running in the same process) to update itself as
needed &ndash; two ways are provided to allow this:
</p>
<ul class="itemize mark-bullet">
<li><code class="code">R_ProcessEvents</code> calls the callback registered by
<code class="code">Rp-&gt;callback</code>.  A version of this is used to run package Tcl/Tk
for <strong class="strong">tcltk</strong> under Windows, for the code is

<a class="index-entry-id" id="index-R_005fProcessEvents"></a>
<a class="index-entry-id" id="index-onintr"></a>
<div class="example">
<pre class="example-preformatted">void R_ProcessEvents(void)
{
    while (peekevent()) doevent(); /* Windows events for GraphApp */
    if (UserBreak) { UserBreak = FALSE; onintr(); }
    R_CallBackHook();
    if(R_tcldo) R_tcldo();
}
</pre></div>

</li><li>The mainloop can be split up to allow the calling application to take
some action after each line of input has been dealt with: see the
alternative code below <code class="code">#ifdef SIMPLE_CASE</code>.
</li></ul>

<p>It may be that no R GraphApp windows need to be considered, although
these include pagers, the <code class="code">windows()</code> graphics device, the R
data and script editors and various popups such as <code class="code">choose.file()</code>
and <code class="code">select.list()</code>.  It would be possible to replace all of these,
but it seems easier to allow GraphApp to handle most of them.
</p>
<p>It is possible to run R in a GUI in a single thread (as
<samp class="file">RGui.exe</samp> shows) but it will normally be easier<a class="footnote" id="DOCF175" href="#FOOT175"><sup>175</sup></a> to
use multiple threads.
</p>
<p>Note that R&rsquo;s own front ends use a stack size of 10Mb, whereas MinGW
executables default to 2Mb, and Visual C++ ones to 1Mb.  The latter
stack sizes are too small for a number of R applications, so
general-purpose front-ends should use a larger stack size.
</p>
<p>Applications embedding R 4.2.0 and newer should use <abbr class="abbr">UCRT</abbr> as the C runtime
and opt in for UTF-8 as the active code page in their manifest, as all
frontends shipped with R do.  This will allow the embedded R to use
UTF-8 as its native encoding on recent Windows systems.
</p>
<hr>
</div>
<div class="subsection-level-extent" id="Finding-R_005fHOME">
<div class="nav-panel">
<p>
Previous: <a href="#Calling-R_002edll-directly" accesskey="p" rel="prev">Calling <samp class="file">R.dll</samp> directly</a>, Up: <a href="#Embedding-R-under-Windows" accesskey="u" rel="up">Embedding R under Windows</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h4 class="subsection" id="Finding-R_005fHOME-1"><span>8.2.3 Finding R_HOME<a class="copiable-link" href="#Finding-R_005fHOME-1"> &para;</a></span></h4>

<p>Both applications which embed R and those which use a <code class="code">system</code>
call to invoke R (as <code class="command">Rscript.exe</code>, <code class="command">Rterm.exe</code> or
<code class="command">R.exe</code>) need to be able to find the R <samp class="file">bin</samp> directory.
The simplest way to do so is the ask the user to set an environment
variable <code class="env">R_HOME</code> and use that, but naive users may be flummoxed as
to how to do so or what value to use.
</p>
<p>The R for Windows installers have for a long time allowed the value
of <code class="code">R_HOME</code> to be recorded in the Windows Registry: this is
optional but selected by default.  <em class="emph">Where</em> it is recorded has
changed over the years to allow for multiple versions of R to be
installed at once, and to allow 32- and 64-bit versions of R to be
installed on the same machine. Only 64-bit versions are supported since R
4.2.
</p>
<p>The basic Registry location is <code class="code">Software\R-core\R</code>.  For an
administrative install this is under <code class="code">HKEY_LOCAL_MACHINE</code> and on a
64-bit OS <code class="code">HKEY_LOCAL_MACHINE\Software\R-core\R</code> is by default
redirected for a 32-bit application, so a 32-bit application will see
the information for the last 32-bit install, and a 64-bit application
that for the last 64-bit install.  For a personal install, the
information is under <code class="code">HKEY_CURRENT_USER\Software\R-core\R</code> which is
seen by both 32-bit and 64-bit applications and so records the last
install of either architecture.  To circumvent this, with Intel builds there
are locations <code class="code">Software\R-core\R32</code> and <code class="code">Software\R-core\R64</code>
which always refer to one architecture.
</p>
<p>When R is installed and recording is not disabled then two string
values are written at that location for keys <code class="code">InstallPath</code> and
<code class="code">Current Version</code>, and these keys are removed when R is
uninstalled.  To allow information about other installed versions to be
retained, there is also a key named something like <code class="code">3.0.0</code> or
<code class="code">3.0.0 patched</code> or <code class="code">3.1.0 Pre-release</code> with a value for
<code class="code">InstallPath</code>.
</p>
<p>So a comprehensive algorithm to search for <code class="code">R_HOME</code> is something
like
</p>
<ul class="itemize mark-bullet">
<li>Decide which of personal or administrative installs should have
precedence.  There are arguments both ways: we find that with roaming
profiles that <code class="code">HKEY_CURRENT_USER\Software</code> often gets reverted to
an earlier version.  Do the following for one or both of
<code class="code">HKEY_CURRENT_USER</code> and <code class="code">HKEY_LOCAL_MACHINE</code>.

</li><li>If the desired architecture is known, look in <code class="code">Software\R-core\R32</code>
or <code class="code">Software\R-core\R64</code>, and if that does not exist or the
architecture is immaterial, in <code class="code">Software\R-core\R</code>.

</li><li>If key <code class="code">InstallPath</code> exists then this is <code class="code">R_HOME</code> (recorded
using backslashes).  If it does not, look for version-specific keys like
<code class="code">2.11.0 alpha</code>, pick the latest (which is of itself a complicated
algorithm as <code class="code">2.11.0 patched &gt; 2.11.0 &gt; 2.11.0 alpha &gt; 2.8.1</code>) and
use its value for <code class="code">InstallPath</code>.
</li></ul>

<hr>
</div>
</div>
</div>
<div class="unnumbered-level-extent" id="Function-and-variable-index">
<div class="nav-panel">
<p>
Next: <a href="#Concept-index" accesskey="n" rel="next">Concept index</a>, Previous: <a href="#Linking-GUIs-and-other-front_002dends-to-R" accesskey="p" rel="prev">Linking GUIs and other front-ends to R</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="unnumbered" id="Function-and-variable-index-1"><span>Function and variable index<a class="copiable-link" href="#Function-and-variable-index-1"> &para;</a></span></h2>

<div class="printindex vr-printindex">
<table summary="" class="vr-letters-header-printindex"><tr><th>Jump to: &nbsp; </th><td><a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-1"><b>.</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-2"><b>\</b></a>
 &nbsp; 
<br>
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-A"><b>A</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-B"><b>B</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-C"><b>C</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-D"><b>D</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-E"><b>E</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-F"><b>F</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-G"><b>G</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-I"><b>I</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-L"><b>L</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-M"><b>M</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-N"><b>N</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-O"><b>O</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-P"><b>P</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-Q"><b>Q</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-R"><b>R</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-S"><b>S</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-T"><b>T</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-U"><b>U</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-V"><b>V</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-W"><b>W</b></a>
 &nbsp; 
</td></tr></table>
<table summary="" class="vr-entries-printindex" border="0">
<tr><td></td><th class="entries-header-printindex">Index Entry</th><th class="sections-header-printindex">Section</th></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_symbol-1">.</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eC"><code>.C</code></a></td><td class="printindex-index-section"><a href="#Interface-functions-_002eC-and-_002eFortran">Interface functions .C and .Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eCall"><code>.Call</code></a></td><td class="printindex-index-section"><a href="#Handling-R-objects-in-C">Handling R objects in C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eCall-1"><code>.Call</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eCall">Calling .Call</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eExternal"><code>.External</code></a></td><td class="printindex-index-section"><a href="#Handling-R-objects-in-C">Handling R objects in C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eExternal-1"><code>.External</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eFortran"><code>.Fortran</code></a></td><td class="printindex-index-section"><a href="#Interface-functions-_002eC-and-_002eFortran">Interface functions .C and .Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eLast_002elib"><code>.Last.lib</code></a></td><td class="printindex-index-section"><a href="#Load-hooks">Load hooks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eonAttach"><code>.onAttach</code></a></td><td class="printindex-index-section"><a href="#Load-hooks">Load hooks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eonDetach"><code>.onDetach</code></a></td><td class="printindex-index-section"><a href="#Load-hooks">Load hooks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eonLoad"><code>.onLoad</code></a></td><td class="printindex-index-section"><a href="#Load-hooks">Load hooks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eonUnload"><code>.onUnload</code></a></td><td class="printindex-index-section"><a href="#Load-hooks">Load hooks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eRandom_002eseed"><code>.Random.seed</code></a></td><td class="printindex-index-section"><a href="#Random-numbers">Random numbers</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_symbol-2">\</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cabbr"><code>\abbr</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cacronym"><code>\acronym</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005calias"><code>\alias</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005carguments"><code>\arguments</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cauthor"><code>\author</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cbold"><code>\bold</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005ccite"><code>\cite</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005ccode"><code>\code</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005ccommand"><code>\command</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cconcept"><code>\concept</code></a></td><td class="printindex-index-section"><a href="#Indices">Indices</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005ccr"><code>\cr</code></a></td><td class="printindex-index-section"><a href="#Sectioning">Sectioning</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cCRANpkg_007bpkg_007d"><code>\CRANpkg{<var class="var">pkg</var>}</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdeqn"><code>\deqn</code></a></td><td class="printindex-index-section"><a href="#Mathematics">Mathematics</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdescribe"><code>\describe</code></a></td><td class="printindex-index-section"><a href="#Lists-and-tables">Lists and tables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdescription"><code>\description</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdetails"><code>\details</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdfn"><code>\dfn</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdoi_007bnumbers_007d"><code>\doi{<var class="var">numbers</var>}</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdontdiff"><code>\dontdiff</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdontrun"><code>\dontrun</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdontshow"><code>\dontshow</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdonttest"><code>\donttest</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdots"><code>\dots</code></a></td><td class="printindex-index-section"><a href="#Insertions">Insertions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cdQuote"><code>\dQuote</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cemail"><code>\email</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cemph"><code>\emph</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cenc"><code>\enc</code></a></td><td class="printindex-index-section"><a href="#Insertions">Insertions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cenumerate"><code>\enumerate</code></a></td><td class="printindex-index-section"><a href="#Lists-and-tables">Lists and tables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cenv"><code>\env</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005ceqn"><code>\eqn</code></a></td><td class="printindex-index-section"><a href="#Mathematics">Mathematics</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cexamples"><code>\examples</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cfigure"><code>\figure</code></a></td><td class="printindex-index-section"><a href="#Figures">Figures</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cfile"><code>\file</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cformat"><code>\format</code></a></td><td class="printindex-index-section"><a href="#Documenting-data-sets">Documenting data sets</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005chref"><code>\href</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cif"><code>\if</code></a></td><td class="printindex-index-section"><a href="#Conditional-text">Conditional text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cifelse"><code>\ifelse</code></a></td><td class="printindex-index-section"><a href="#Conditional-text">Conditional text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005citemize"><code>\itemize</code></a></td><td class="printindex-index-section"><a href="#Lists-and-tables">Lists and tables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005ckbd"><code>\kbd</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005ckeyword"><code>\keyword</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cldots"><code>\ldots</code></a></td><td class="printindex-index-section"><a href="#Insertions">Insertions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005clink"><code>\link</code></a></td><td class="printindex-index-section"><a href="#Cross_002dreferences">Cross-references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005clinkS4class"><code>\linkS4class</code></a></td><td class="printindex-index-section"><a href="#Cross_002dreferences">Cross-references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cmethod"><code>\method</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cname"><code>\name</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cnewcommand"><code>\newcommand</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cnote"><code>\note</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005coption"><code>\option</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cout"><code>\out</code></a></td><td class="printindex-index-section"><a href="#Conditional-text">Conditional text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cpackageAuthor"><code>\packageAuthor</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cpackageDescription"><code>\packageDescription</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cpackageDESCRIPTION"><code>\packageDESCRIPTION</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cpackageIndices"><code>\packageIndices</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cpackageMaintainer"><code>\packageMaintainer</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cpackageTitle"><code>\packageTitle</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cpkg"><code>\pkg</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cpreformatted"><code>\preformatted</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cR"><code>\R</code></a></td><td class="printindex-index-section"><a href="#Insertions">Insertions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cRdOpts"><code>\RdOpts</code></a></td><td class="printindex-index-section"><a href="#Dynamic-pages">Dynamic pages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005creferences"><code>\references</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005crenewcommand"><code>\renewcommand</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cS3method"><code>\S3method</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005csamp"><code>\samp</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005csection"><code>\section</code></a></td><td class="printindex-index-section"><a href="#Sectioning">Sectioning</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cseealso"><code>\seealso</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cSexpr"><code>\Sexpr</code></a></td><td class="printindex-index-section"><a href="#Dynamic-pages">Dynamic pages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005csource"><code>\source</code></a></td><td class="printindex-index-section"><a href="#Documenting-data-sets">Documenting data sets</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005csQuote"><code>\sQuote</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005csspace"><code>\sspace</code></a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cstrong"><code>\strong</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005ctabular"><code>\tabular</code></a></td><td class="printindex-index-section"><a href="#Lists-and-tables">Lists and tables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005ctitle"><code>\title</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005curl"><code>\url</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cusage"><code>\usage</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cvalue"><code>\value</code></a></td><td class="printindex-index-section"><a href="#Documenting-functions">Documenting functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cvar"><code>\var</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_005cverb"><code>\verb</code></a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-A">A</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-allocList"><code>allocList</code></a></td><td class="printindex-index-section"><a href="#Evaluating-R-expressions-from-C">Evaluating R expressions from C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-allocMatrix"><code>allocMatrix</code></a></td><td class="printindex-index-section"><a href="#Calculating-numerical-derivatives">Calculating numerical derivatives</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-allocVector"><code>allocVector</code></a></td><td class="printindex-index-section"><a href="#Allocating-storage">Allocating storage</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-any_005fduplicated"><code>any_duplicated</code></a></td><td class="printindex-index-section"><a href="#Semi_002dinternal-convenience-functions">Semi-internal convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-any_005fduplicated3"><code>any_duplicated3</code></a></td><td class="printindex-index-section"><a href="#Semi_002dinternal-convenience-functions">Semi-internal convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-asChar"><code>asChar</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-asComplex"><code>asComplex</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-asInteger"><code>asInteger</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-asLogical"><code>asLogical</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-asReal"><code>asReal</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-AUTHORS"><code>AUTHORS</code></a></td><td class="printindex-index-section"><a href="#Package-subdirectories">Package subdirectories</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-B">B</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-bessel_005fi"><code>bessel_i</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-bessel_005fj"><code>bessel_j</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-bessel_005fk"><code>bessel_k</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-bessel_005fy"><code>bessel_y</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-beta"><code>beta</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-BLAS_005fLIBS"><code>BLAS_LIBS</code></a></td><td class="printindex-index-section"><a href="#Using-Makevars">Using Makevars</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-browser"><code>browser</code></a></td><td class="printindex-index-section"><a href="#Browsing">Browsing</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-C">C</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CAAR"><code>CAAR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CAD4R"><code>CAD4R</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CAD5R"><code>CAD5R</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CADDDR"><code>CADDDR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CADDR"><code>CADDR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CADR"><code>CADR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Calloc"><code>Calloc</code></a></td><td class="printindex-index-section"><a href="#User_002dcontrolled-memory">User-controlled memory</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CallocCharBuf"><code>CallocCharBuf</code></a></td><td class="printindex-index-section"><a href="#User_002dcontrolled-memory">User-controlled memory</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CAR"><code>CAR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CDAR"><code>CDAR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CDDDR"><code>CDDDR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CDDR"><code>CDDR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CDR"><code>CDR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-cgmin"><code>cgmin</code></a></td><td class="printindex-index-section"><a href="#Optimization">Optimization</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-choose"><code>choose</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CITATION"><code>CITATION</code></a></td><td class="printindex-index-section"><a href="#Package-subdirectories">Package subdirectories</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CITATION-1"><code>CITATION</code></a></td><td class="printindex-index-section"><a href="#Preparing-translations">Preparing translations</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-classgets"><code>classgets</code></a></td><td class="printindex-index-section"><a href="#Classes">Classes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CleanEd"><code>CleanEd</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-coerceVector"><code>coerceVector</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-COMPLEX"><code>COMPLEX</code></a></td><td class="printindex-index-section"><a href="#Vector-accessor-functions">Vector accessor functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CONS"><code>CONS</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-cons"><code>cons</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-COPYRIGHTS"><code>COPYRIGHTS</code></a></td><td class="printindex-index-section"><a href="#The-DESCRIPTION-file">The DESCRIPTION file</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-COPYRIGHTS-1"><code>COPYRIGHTS</code></a></td><td class="printindex-index-section"><a href="#Package-subdirectories">Package subdirectories</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-cospi"><code>cospi</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-cPsort"><code>cPsort</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-D">D</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-dblepr"><code>dblepr</code></a></td><td class="printindex-index-section"><a href="#Printing-from-Fortran">Printing from Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-dblepr1"><code>dblepr1</code></a></td><td class="printindex-index-section"><a href="#Printing-from-Fortran">Printing from Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-debug"><code>debug</code></a></td><td class="printindex-index-section"><a href="#Debugging-R-code">Debugging R code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-debugger"><code>debugger</code></a></td><td class="printindex-index-section"><a href="#Debugging-R-code">Debugging R code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-defineVar"><code>defineVar</code></a></td><td class="printindex-index-section"><a href="#Finding-and-setting-variables">Finding and setting variables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-digamma"><code>digamma</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-dimgets"><code>dimgets</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-dimnamesgets"><code>dimnamesgets</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-dpsifn"><code>dpsifn</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-dump_002eframes"><code>dump.frames</code></a></td><td class="printindex-index-section"><a href="#Debugging-R-code">Debugging R code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-duplicate"><code>duplicate</code></a></td><td class="printindex-index-section"><a href="#Named-objects-and-copying">Named objects and copying</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-dyn_002eload"><code>dyn.load</code></a></td><td class="printindex-index-section"><a href="#dyn_002eload-and-dyn_002eunload">dyn.load and dyn.unload</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-dyn_002eunload"><code>dyn.unload</code></a></td><td class="printindex-index-section"><a href="#dyn_002eload-and-dyn_002eunload">dyn.load and dyn.unload</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-E">E</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-elt"><code>elt</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-error"><code>error</code></a></td><td class="printindex-index-section"><a href="#Error-signaling">Error signaling</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-errorcall"><code>errorcall</code></a></td><td class="printindex-index-section"><a href="#Error-signaling">Error signaling</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-eval"><code>eval</code></a></td><td class="printindex-index-section"><a href="#Evaluating-R-expressions-from-C">Evaluating R expressions from C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-exp_005frand"><code>exp_rand</code></a></td><td class="printindex-index-section"><a href="#Random-numbers">Random numbers</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-expm1"><code>expm1</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-export"><code>export</code></a></td><td class="printindex-index-section"><a href="#Specifying-imports-and-exports">Specifying imports and exports</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-exportClasses"><code>exportClasses</code></a></td><td class="printindex-index-section"><a href="#Namespaces-with-S4-classes-and-methods">Namespaces with S4 classes and methods</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-exportClassPattern"><code>exportClassPattern</code></a></td><td class="printindex-index-section"><a href="#Namespaces-with-S4-classes-and-methods">Namespaces with S4 classes and methods</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-exportMethods"><code>exportMethods</code></a></td><td class="printindex-index-section"><a href="#Namespaces-with-S4-classes-and-methods">Namespaces with S4 classes and methods</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-exportPattern"><code>exportPattern</code></a></td><td class="printindex-index-section"><a href="#Specifying-imports-and-exports">Specifying imports and exports</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-exportPattern-1"><code>exportPattern</code></a></td><td class="printindex-index-section"><a href="#Namespaces-with-S4-classes-and-methods">Namespaces with S4 classes and methods</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-F">F</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-FALSE"><code>FALSE</code></a></td><td class="printindex-index-section"><a href="#Mathematical-constants">Mathematical constants</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-findFun"><code>findFun</code></a></td><td class="printindex-index-section"><a href="#Evaluating-R-expressions-from-C">Evaluating R expressions from C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-findInterval"><code>findInterval</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-findInterval2_0028double_002a"><code>findInterval2(double*</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-findVar"><code>findVar</code></a></td><td class="printindex-index-section"><a href="#Finding-and-setting-variables">Finding and setting variables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-FLIBS"><code>FLIBS</code></a></td><td class="printindex-index-section"><a href="#Using-Makevars">Using Makevars</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-fmax2"><code>fmax2</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-fmin2"><code>fmin2</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-fprec"><code>fprec</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-fpu_005fsetup"><code>fpu_setup</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Free"><code>Free</code></a></td><td class="printindex-index-section"><a href="#User_002dcontrolled-memory">User-controlled memory</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-fround"><code>fround</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-fsign"><code>fsign</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ftrunc"><code>ftrunc</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-G">G</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-gammafn"><code>gammafn</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-gctorture"><code>gctorture</code></a></td><td class="printindex-index-section"><a href="#Using-gctorture">Using gctorture</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-GetArrayDimnames"><code>GetArrayDimnames</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-getAttrib"><code>getAttrib</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-getCharCE"><code>getCharCE</code></a></td><td class="printindex-index-section"><a href="#Character-encoding-issues">Character encoding issues</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-GetColNames"><code>GetColNames</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-GetMatrixDimnames"><code>GetMatrixDimnames</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-GetRNGstate"><code>GetRNGstate</code></a></td><td class="printindex-index-section"><a href="#Random-numbers">Random numbers</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-GetRowNames"><code>GetRowNames</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-I">I</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-imax2"><code>imax2</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-imin2"><code>imin2</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-import"><code>import</code></a></td><td class="printindex-index-section"><a href="#Specifying-imports-and-exports">Specifying imports and exports</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-importClassesFrom"><code>importClassesFrom</code></a></td><td class="printindex-index-section"><a href="#Namespaces-with-S4-classes-and-methods">Namespaces with S4 classes and methods</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-importFrom"><code>importFrom</code></a></td><td class="printindex-index-section"><a href="#Specifying-imports-and-exports">Specifying imports and exports</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-importMethodsFrom"><code>importMethodsFrom</code></a></td><td class="printindex-index-section"><a href="#Namespaces-with-S4-classes-and-methods">Namespaces with S4 classes and methods</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-install"><code>install</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-installChar"><code>installChar</code></a></td><td class="printindex-index-section"><a href="#Finding-and-setting-variables">Finding and setting variables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-INTEGER"><code>INTEGER</code></a></td><td class="printindex-index-section"><a href="#Vector-accessor-functions">Vector accessor functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-integr_005ffn"><code>integr_fn</code></a></td><td class="printindex-index-section"><a href="#Integration">Integration</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-intpr"><code>intpr</code></a></td><td class="printindex-index-section"><a href="#Printing-from-Fortran">Printing from Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-intpr1"><code>intpr1</code></a></td><td class="printindex-index-section"><a href="#Printing-from-Fortran">Printing from Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-iPsort"><code>iPsort</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isArray"><code>isArray</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isComplex"><code>isComplex</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isEnvironment"><code>isEnvironment</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isExpression"><code>isExpression</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isFactor"><code>isFactor</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isFunction"><code>isFunction</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isInteger"><code>isInteger</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isLanguage"><code>isLanguage</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isList"><code>isList</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isLogical"><code>isLogical</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isMatrix"><code>isMatrix</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ISNA"><code>ISNA</code></a></td><td class="printindex-index-section"><a href="#Missing-and-special-values">Missing and special values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ISNA-1"><code>ISNA</code></a></td><td class="printindex-index-section"><a href="#Missing-and-IEEE-values">Missing and IEEE values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ISNAN"><code>ISNAN</code></a></td><td class="printindex-index-section"><a href="#Missing-and-special-values">Missing and special values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ISNAN-1"><code>ISNAN</code></a></td><td class="printindex-index-section"><a href="#Missing-and-IEEE-values">Missing and IEEE values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isNewList"><code>isNewList</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isNull"><code>isNull</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isNumeric"><code>isNumeric</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isObject"><code>isObject</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isOrdered"><code>isOrdered</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isPairList"><code>isPairList</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isPrimitive"><code>isPrimitive</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isReal"><code>isReal</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isString"><code>isString</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isSymbol"><code>isSymbol</code></a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isTs"><code>isTs</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isUnordered"><code>isUnordered</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isVector"><code>isVector</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isVectorAtomic"><code>isVectorAtomic</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-isVectorList"><code>isVectorList</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-L">L</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-labelpr"><code>labelpr</code></a></td><td class="printindex-index-section"><a href="#Printing-from-Fortran">Printing from Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lang1"><code>lang1</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lang2"><code>lang2</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lang3"><code>lang3</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lang4"><code>lang4</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lang5"><code>lang5</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lang6"><code>lang6</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-LAPACK_005fLIBS"><code>LAPACK_LIBS</code></a></td><td class="printindex-index-section"><a href="#Using-Makevars">Using Makevars</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lastElt"><code>lastElt</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lbeta"><code>lbeta</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lbfgsb"><code>lbfgsb</code></a></td><td class="printindex-index-section"><a href="#Optimization">Optimization</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lchoose"><code>lchoose</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-LCONS"><code>LCONS</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lcons"><code>lcons</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lgamma1p"><code>lgamma1p</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-lgammafn"><code>lgammafn</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-library_002edynam"><code>library.dynam</code></a></td><td class="printindex-index-section"><a href="#Package-subdirectories">Package subdirectories</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-library_002edynam-1"><code>library.dynam</code></a></td><td class="printindex-index-section"><a href="#dyn_002eload-and-dyn_002eunload">dyn.load and dyn.unload</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-list1"><code>list1</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-list2"><code>list2</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-list3"><code>list3</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-list4"><code>list4</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-list5"><code>list5</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-list6"><code>list6</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-log1mexp"><code>log1mexp</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-log1p"><code>log1p</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-log1pexp"><code>log1pexp</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-log1pmx"><code>log1pmx</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-LOGICAL"><code>LOGICAL</code></a></td><td class="printindex-index-section"><a href="#Vector-accessor-functions">Vector accessor functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-logspace_005fadd"><code>logspace_add</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-logspace_005fsub"><code>logspace_sub</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-logspace_005fsum"><code>logspace_sum</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-M">M</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-M_005fE"><code>M_E</code></a></td><td class="printindex-index-section"><a href="#Mathematical-constants">Mathematical constants</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-M_005fPI"><code>M_PI</code></a></td><td class="printindex-index-section"><a href="#Mathematical-constants">Mathematical constants</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-MARK_005fNOT_005fMUTABLE"><code>MARK_NOT_MUTABLE</code></a></td><td class="printindex-index-section"><a href="#Named-objects-and-copying">Named objects and copying</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-MAYBE_005fREFERENCED"><code>MAYBE_REFERENCED</code></a></td><td class="printindex-index-section"><a href="#Named-objects-and-copying">Named objects and copying</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-MAYBE_005fSHARED"><code>MAYBE_SHARED</code></a></td><td class="printindex-index-section"><a href="#Named-objects-and-copying">Named objects and copying</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Memcpy"><code>Memcpy</code></a></td><td class="printindex-index-section"><a href="#User_002dcontrolled-memory">User-controlled memory</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Memzero"><code>Memzero</code></a></td><td class="printindex-index-section"><a href="#User_002dcontrolled-memory">User-controlled memory</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-mkChar"><code>mkChar</code></a></td><td class="printindex-index-section"><a href="#Handling-character-data">Handling character data</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-mkCharCE"><code>mkCharCE</code></a></td><td class="printindex-index-section"><a href="#Character-encoding-issues">Character encoding issues</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-mkCharLen"><code>mkCharLen</code></a></td><td class="printindex-index-section"><a href="#Handling-character-data">Handling character data</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-mkCharLenCE"><code>mkCharLenCE</code></a></td><td class="printindex-index-section"><a href="#Character-encoding-issues">Character encoding issues</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-mkString"><code>mkString</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-N">N</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-NA_005fREAL"><code>NA_REAL</code></a></td><td class="printindex-index-section"><a href="#Missing-and-IEEE-values">Missing and IEEE values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-namesgets"><code>namesgets</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-NEWS_002eRd"><code>NEWS.Rd</code></a></td><td class="printindex-index-section"><a href="#Package-subdirectories">Package subdirectories</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-nmmin"><code>nmmin</code></a></td><td class="printindex-index-section"><a href="#Optimization">Optimization</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-norm_005frand"><code>norm_rand</code></a></td><td class="printindex-index-section"><a href="#Random-numbers">Random numbers</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-nrows"><code>nrows</code></a></td><td class="printindex-index-section"><a href="#Transient-storage-allocation">Transient storage allocation</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-nthcdr"><code>nthcdr</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-O">O</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-OBJECTS"><code>OBJECTS</code></a></td><td class="printindex-index-section"><a href="#Using-Makevars">Using Makevars</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-OBJECTS-1"><code>OBJECTS</code></a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-onintr"><code>onintr</code></a></td><td class="printindex-index-section"><a href="#Calling-R_002edll-directly">Calling R.dll directly</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-optimfn"><code>optimfn</code></a></td><td class="printindex-index-section"><a href="#Optimization">Optimization</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-optimgr"><code>optimgr</code></a></td><td class="printindex-index-section"><a href="#Optimization">Optimization</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-P">P</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-pentagamma"><code>pentagamma</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PKG_005fCFLAGS"><code>PKG_CFLAGS</code></a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PKG_005fCPPFLAGS"><code>PKG_CPPFLAGS</code></a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PKG_005fCXXFLAGS"><code>PKG_CXXFLAGS</code></a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PKG_005fFCFLAGS"><code>PKG_FCFLAGS</code></a></td><td class="printindex-index-section"><a href="#Using-modern-Fortran-code">Using modern Fortran code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PKG_005fFFLAGS"><code>PKG_FFLAGS</code></a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PKG_005fLIBS"><code>PKG_LIBS</code></a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PKG_005fOBJCFLAGS"><code>PKG_OBJCFLAGS</code></a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PKG_005fOBJCXXFLAGS"><code>PKG_OBJCXXFLAGS</code></a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-pow1p"><code>pow1p</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PRINTNAME"><code>PRINTNAME</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PrintValue"><code>PrintValue</code></a></td><td class="printindex-index-section"><a href="#Inspecting-R-objects">Inspecting R objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-prompt"><code>prompt</code></a></td><td class="printindex-index-section"><a href="#Rd-format">Rd format</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PROTECT"><code>PROTECT</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-protect"><code>protect</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PROTECT_005fWITH_005fINDEX"><code>PROTECT_WITH_INDEX</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-psigamma"><code>psigamma</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-PutRNGstate"><code>PutRNGstate</code></a></td><td class="printindex-index-section"><a href="#Random-numbers">Random numbers</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-Q">Q</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-qsort3"><code>qsort3</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-qsort4"><code>qsort4</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-R">R</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R-CMD-build"><code>R CMD build</code></a></td><td class="printindex-index-section"><a href="#Building-package-tarballs">Building package tarballs</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R-CMD-check"><code>R CMD check</code></a></td><td class="printindex-index-section"><a href="#Checking-packages">Checking packages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R-CMD-config"><code>R CMD config</code></a></td><td class="printindex-index-section"><a href="#Configure-and-cleanup">Configure and cleanup</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R-CMD-Rd2pdf"><code>R CMD Rd2pdf</code></a></td><td class="printindex-index-section"><a href="#Processing-documentation-files">Processing documentation files</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R-CMD-Rdconv"><code>R CMD Rdconv</code></a></td><td class="printindex-index-section"><a href="#Processing-documentation-files">Processing documentation files</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R-CMD-SHLIB"><code>R CMD SHLIB</code></a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R-CMD-Stangle"><code>R CMD Stangle</code></a></td><td class="printindex-index-section"><a href="#Processing-documentation-files">Processing documentation files</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R-CMD-Sweave"><code>R CMD Sweave</code></a></td><td class="printindex-index-section"><a href="#Processing-documentation-files">Processing documentation files</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005faddhistory"><code>R_addhistory</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005falloc"><code>R_alloc</code></a></td><td class="printindex-index-section"><a href="#Transient-storage-allocation">Transient storage allocation</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fallocLD"><code>R_allocLD</code></a></td><td class="printindex-index-section"><a href="#Transient-storage-allocation">Transient storage allocation</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fBusy"><code>R_Busy</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fCalloc"><code>R_Calloc</code></a></td><td class="printindex-index-section"><a href="#User_002dcontrolled-memory">User-controlled memory</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fCheckUserInterrupt"><code>R_CheckUserInterrupt</code></a></td><td class="printindex-index-section"><a href="#Allowing-interrupts">Allowing interrupts</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fChooseFile"><code>R_ChooseFile</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fCleanTempDir"><code>R_CleanTempDir</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fCleanUp"><code>R_CleanUp</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fClearerrConsole"><code>R_ClearerrConsole</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fClearExternalPtr"><code>R_ClearExternalPtr</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fcompute_005fidentical"><code>R_compute_identical</code></a></td><td class="printindex-index-section"><a href="#Semi_002dinternal-convenience-functions">Semi-internal convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fContinueUnwind"><code>R_ContinueUnwind</code></a></td><td class="printindex-index-section"><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fcsort"><code>R_csort</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fdataentry"><code>R_dataentry</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fdataviewer"><code>R_dataviewer</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fDefParams"><code>R_DefParams</code></a></td><td class="printindex-index-section"><a href="#Calling-R_002edll-directly">Calling R.dll directly</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fDefParamsEx"><code>R_DefParamsEx</code></a></td><td class="printindex-index-section"><a href="#Calling-R_002edll-directly">Calling R.dll directly</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fdot_005fLast"><code>R_dot_Last</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fEditFile"><code>R_EditFile</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fEditFiles"><code>R_EditFiles</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fExpandFileName"><code>R_ExpandFileName</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fExternalPtrAddr"><code>R_ExternalPtrAddr</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fExternalPtrAddrFn"><code>R_ExternalPtrAddrFn</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fExternalPtrProtected"><code>R_ExternalPtrProtected</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fExternalPtrTag"><code>R_ExternalPtrTag</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fFINITE"><code>R_FINITE</code></a></td><td class="printindex-index-section"><a href="#Missing-and-IEEE-values">Missing and IEEE values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fFlushConsole"><code>R_FlushConsole</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fforceSymbols"><code>R_forceSymbols</code></a></td><td class="printindex-index-section"><a href="#Registering-native-routines">Registering native routines</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fFree"><code>R_Free</code></a></td><td class="printindex-index-section"><a href="#User_002dcontrolled-memory">User-controlled memory</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005ffree_005ftmpnam"><code>R_free_tmpnam</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fGetCCallable"><code>R_GetCCallable</code></a></td><td class="printindex-index-section"><a href="#Linking-to-native-routines-in-other-packages">Linking to native routines in other packages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fGetCurrentEnv"><code>R_GetCurrentEnv</code></a></td><td class="printindex-index-section"><a href="#Evaluating-R-expressions-from-C">Evaluating R expressions from C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fGetCurrentSrcref"><code>R_GetCurrentSrcref</code></a></td><td class="printindex-index-section"><a href="#Accessing-source-references">Accessing source references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fgetEmbeddingDllInfo"><code>R_getEmbeddingDllInfo</code></a></td><td class="printindex-index-section"><a href="#Registering-symbols">Registering symbols</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fGetSrcFilename"><code>R_GetSrcFilename</code></a></td><td class="printindex-index-section"><a href="#Accessing-source-references">Accessing source references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fINLINE"><code>R_INLINE</code></a></td><td class="printindex-index-section"><a href="#Inlining-C-functions">Inlining C functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fIsNaN"><code>R_IsNaN</code></a></td><td class="printindex-index-section"><a href="#Missing-and-IEEE-values">Missing and IEEE values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fisort"><code>R_isort</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fLIBRARY_005fDIR"><code>R_LIBRARY_DIR</code></a></td><td class="printindex-index-section"><a href="#Configure-and-cleanup">Configure and cleanup</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005floadhistory"><code>R_loadhistory</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fMakeExternalPtr"><code>R_MakeExternalPtr</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fMakeExternalPtrFn"><code>R_MakeExternalPtrFn</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fMakeUnwindCont"><code>R_MakeUnwindCont</code></a></td><td class="printindex-index-section"><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fMakeWeakRef"><code>R_MakeWeakRef</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fMakeWeakRefC"><code>R_MakeWeakRefC</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fmax_005fcol"><code>R_max_col</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fNegInf"><code>R_NegInf</code></a></td><td class="printindex-index-section"><a href="#Missing-and-IEEE-values">Missing and IEEE values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fNewEnv"><code>R_NewEnv</code></a></td><td class="printindex-index-section"><a href="#Finding-and-setting-variables">Finding and setting variables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fNewPreciousMSet"><code>R_NewPreciousMSet</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005forderVector"><code>R_orderVector</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005forderVector1"><code>R_orderVector1</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fPACKAGE_005fDIR"><code>R_PACKAGE_DIR</code></a></td><td class="printindex-index-section"><a href="#Configure-and-cleanup">Configure and cleanup</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fPACKAGE_005fDIR-1"><code>R_PACKAGE_DIR</code></a></td><td class="printindex-index-section"><a href="#Configure-and-cleanup">Configure and cleanup</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fPACKAGE_005fNAME"><code>R_PACKAGE_NAME</code></a></td><td class="printindex-index-section"><a href="#Configure-and-cleanup">Configure and cleanup</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fPACKAGE_005fNAME-1"><code>R_PACKAGE_NAME</code></a></td><td class="printindex-index-section"><a href="#Configure-and-cleanup">Configure and cleanup</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fParseVector"><code>R_ParseVector</code></a></td><td class="printindex-index-section"><a href="#Parsing-R-code-from-C">Parsing R code from C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fPolledEvents"><code>R_PolledEvents</code></a></td><td class="printindex-index-section"><a href="#Meshing-event-loops">Meshing event loops</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fPosInf"><code>R_PosInf</code></a></td><td class="printindex-index-section"><a href="#Missing-and-IEEE-values">Missing and IEEE values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fpow"><code>R_pow</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fpow_005fdi"><code>R_pow_di</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fPreserveInMSet"><code>R_PreserveInMSet</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fPreserveObject"><code>R_PreserveObject</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fProcessEvents"><code>R_ProcessEvents</code></a></td><td class="printindex-index-section"><a href="#Calling-R_002edll-directly">Calling R.dll directly</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fProtectWithIndex"><code>R_ProtectWithIndex</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fPV"><code>R_PV</code></a></td><td class="printindex-index-section"><a href="#Inspecting-R-objects">Inspecting R objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fqsort"><code>R_qsort</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fqsort_005fI"><code>R_qsort_I</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fqsort_005fint"><code>R_qsort_int</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fqsort_005fint_005fI"><code>R_qsort_int_I</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fReadConsole"><code>R_ReadConsole</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fRealloc"><code>R_Realloc</code></a></td><td class="printindex-index-section"><a href="#User_002dcontrolled-memory">User-controlled memory</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fRegisterCCallable"><code>R_RegisterCCallable</code></a></td><td class="printindex-index-section"><a href="#Linking-to-native-routines-in-other-packages">Linking to native routines in other packages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fRegisterCFinalizer"><code>R_RegisterCFinalizer</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fRegisterCFinalizerEx"><code>R_RegisterCFinalizerEx</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fRegisterFinalizer"><code>R_RegisterFinalizer</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fRegisterFinalizerEx"><code>R_RegisterFinalizerEx</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fregisterRoutines"><code>R_registerRoutines</code></a></td><td class="printindex-index-section"><a href="#Registering-native-routines">Registering native routines</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fReleaseFromMSet"><code>R_ReleaseFromMSet</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fReleaseObject"><code>R_ReleaseObject</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fReplDLLdo1"><code>R_ReplDLLdo1</code></a></td><td class="printindex-index-section"><a href="#Embedding-R-under-Unix_002dalikes">Embedding R under Unix-alikes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fReplDLLinit"><code>R_ReplDLLinit</code></a></td><td class="printindex-index-section"><a href="#Embedding-R-under-Unix_002dalikes">Embedding R under Unix-alikes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fReprotect"><code>R_Reprotect</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fResetConsole"><code>R_ResetConsole</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005frsort"><code>R_rsort</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fRunExitFinalizers"><code>R_RunExitFinalizers</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fRunWeakRefFinalizer"><code>R_RunWeakRefFinalizer</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fSaveGlobalEnv"><code>R_SaveGlobalEnv</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fsavehistory"><code>R_savehistory</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fselectlist"><code>R_selectlist</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fset_005fcommand_005fline_005farguments"><code>R_set_command_line_arguments</code></a></td><td class="printindex-index-section"><a href="#Calling-R_002edll-directly">Calling R.dll directly</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fSetExternalPtrAddr"><code>R_SetExternalPtrAddr</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fSetExternalPtrProtected"><code>R_SetExternalPtrProtected</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fSetExternalPtrTag"><code>R_SetExternalPtrTag</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fSetParams"><code>R_SetParams</code></a></td><td class="printindex-index-section"><a href="#Calling-R_002edll-directly">Calling R.dll directly</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fsetStartTime"><code>R_setStartTime</code></a></td><td class="printindex-index-section"><a href="#Calling-R_002edll-directly">Calling R.dll directly</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fShowFiles"><code>R_ShowFiles</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fShowMessage"><code>R_ShowMessage</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fSrcref"><code>R_Srcref</code></a></td><td class="printindex-index-section"><a href="#Accessing-source-references">Accessing source references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fSuicide"><code>R_Suicide</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005ftmpnam"><code>R_tmpnam</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005ftmpnam2"><code>R_tmpnam2</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005ftryCatch"><code>R_tryCatch</code></a></td><td class="printindex-index-section"><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005ftryCatchError"><code>R_tryCatchError</code></a></td><td class="printindex-index-section"><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005funif_005findex"><code>R_unif_index</code></a></td><td class="printindex-index-section"><a href="#Random-numbers">Random numbers</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fUnwindProtect"><code>R_UnwindProtect</code></a></td><td class="printindex-index-section"><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fuseDynamicSymbols"><code>R_useDynamicSymbols</code></a></td><td class="printindex-index-section"><a href="#Registering-native-routines">Registering native routines</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fVersion"><code>R_Version</code></a></td><td class="printindex-index-section"><a href="#Platform-and-version-information">Platform and version information</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fwait_005fusec"><code>R_wait_usec</code></a></td><td class="printindex-index-section"><a href="#Meshing-event-loops">Meshing event loops</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fWeakRefKey"><code>R_WeakRefKey</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fWeakRefValue"><code>R_WeakRefValue</code></a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fwithCallingErrorHandler"><code>R_withCallingErrorHandler</code></a></td><td class="printindex-index-section"><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fWriteConsole"><code>R_WriteConsole</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-R_005fWriteConsoleEx"><code>R_WriteConsoleEx</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-RAW"><code>RAW</code></a></td><td class="printindex-index-section"><a href="#Vector-accessor-functions">Vector accessor functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-rchkusr"><code>rchkusr</code></a></td><td class="printindex-index-section"><a href="#Allowing-interrupts">Allowing interrupts</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rdqagi"><code>Rdqagi</code></a></td><td class="printindex-index-section"><a href="#Integration">Integration</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rdqags"><code>Rdqags</code></a></td><td class="printindex-index-section"><a href="#Integration">Integration</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-REAL"><code>REAL</code></a></td><td class="printindex-index-section"><a href="#Vector-accessor-functions">Vector accessor functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Realloc"><code>Realloc</code></a></td><td class="printindex-index-section"><a href="#User_002dcontrolled-memory">User-controlled memory</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-realpr"><code>realpr</code></a></td><td class="printindex-index-section"><a href="#Printing-from-Fortran">Printing from Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-realpr1"><code>realpr1</code></a></td><td class="printindex-index-section"><a href="#Printing-from-Fortran">Printing from Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-recover"><code>recover</code></a></td><td class="printindex-index-section"><a href="#Debugging-R-code">Debugging R code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-reEnc"><code>reEnc</code></a></td><td class="printindex-index-section"><a href="#Character-encoding-issues">Character encoding issues</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-REprintf"><code>REprintf</code></a></td><td class="printindex-index-section"><a href="#Printing">Printing</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-REPROTECT"><code>REPROTECT</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-REvprintf"><code>REvprintf</code></a></td><td class="printindex-index-section"><a href="#Printing">Printing</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-revsort"><code>revsort</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rf_005fendEmbeddedR"><code>Rf_endEmbeddedR</code></a></td><td class="printindex-index-section"><a href="#Embedding-R-under-Unix_002dalikes">Embedding R under Unix-alikes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rf_005finitEmbeddedR"><code>Rf_initEmbeddedR</code></a></td><td class="printindex-index-section"><a href="#Embedding-R-under-Unix_002dalikes">Embedding R under Unix-alikes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rf_005finitialize_005fR"><code>Rf_initialize_R</code></a></td><td class="printindex-index-section"><a href="#Embedding-R-under-Unix_002dalikes">Embedding R under Unix-alikes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rf_005fKillAllDevices"><code>Rf_KillAllDevices</code></a></td><td class="printindex-index-section"><a href="#Setting-R-callbacks">Setting R callbacks</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rf_005fmainloop"><code>Rf_mainloop</code></a></td><td class="printindex-index-section"><a href="#Embedding-R-under-Unix_002dalikes">Embedding R under Unix-alikes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Riconv"><code>Riconv</code></a></td><td class="printindex-index-section"><a href="#Re_002dencoding">Re-encoding</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Riconv_005fclose"><code>Riconv_close</code></a></td><td class="printindex-index-section"><a href="#Re_002dencoding">Re-encoding</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Riconv_005fopen"><code>Riconv_open</code></a></td><td class="printindex-index-section"><a href="#Re_002dencoding">Re-encoding</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rprintf"><code>Rprintf</code></a></td><td class="printindex-index-section"><a href="#Printing">Printing</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rprof"><code>Rprof</code></a></td><td class="printindex-index-section"><a href="#Profiling-R-code-for-speed">Profiling R code for speed</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rprof-1"><code>Rprof</code></a></td><td class="printindex-index-section"><a href="#Memory-statistics-from-Rprof">Memory statistics from Rprof</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rprofmem"><code>Rprofmem</code></a></td><td class="printindex-index-section"><a href="#Tracking-memory-allocations">Tracking memory allocations</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-rPsort"><code>rPsort</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-rsort_005fwith_005findex"><code>rsort_with_index</code></a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rtanpi"><code>Rtanpi</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-run_005fRmainloop"><code>run_Rmainloop</code></a></td><td class="printindex-index-section"><a href="#Embedding-R-under-Unix_002dalikes">Embedding R under Unix-alikes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Rvprintf"><code>Rvprintf</code></a></td><td class="printindex-index-section"><a href="#Printing">Printing</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-S">S</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-S_005falloc"><code>S_alloc</code></a></td><td class="printindex-index-section"><a href="#Transient-storage-allocation">Transient storage allocation</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-S_005frealloc"><code>S_realloc</code></a></td><td class="printindex-index-section"><a href="#Transient-storage-allocation">Transient storage allocation</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-S3method"><code>S3method</code></a></td><td class="printindex-index-section"><a href="#Registering-S3-methods">Registering S3 methods</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SAFE_005fFFLAGS"><code>SAFE_FFLAGS</code></a></td><td class="printindex-index-section"><a href="#Using-Makevars">Using Makevars</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-samin"><code>samin</code></a></td><td class="printindex-index-section"><a href="#Optimization">Optimization</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ScalarComplex"><code>ScalarComplex</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ScalarInteger"><code>ScalarInteger</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ScalarLogical"><code>ScalarLogical</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ScalarRaw"><code>ScalarRaw</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ScalarReal"><code>ScalarReal</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-ScalarString"><code>ScalarString</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SET_005fSTRING_005fELT"><code>SET_STRING_ELT</code></a></td><td class="printindex-index-section"><a href="#Handling-character-data">Handling character data</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SET_005fTAG"><code>SET_TAG</code></a></td><td class="printindex-index-section"><a href="#Evaluating-R-expressions-from-C">Evaluating R expressions from C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SET_005fVECTOR_005fELT"><code>SET_VECTOR_ELT</code></a></td><td class="printindex-index-section"><a href="#Vector-accessor-functions">Vector accessor functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-setAttrib"><code>setAttrib</code></a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SETCAD4R"><code>SETCAD4R</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SETCADDDR"><code>SETCADDDR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SETCADDR"><code>SETCADDR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SETCADR"><code>SETCADR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SETCAR"><code>SETCAR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-SETCDR"><code>SETCDR</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-setup_005fRmainloop"><code>setup_Rmainloop</code></a></td><td class="printindex-index-section"><a href="#Calling-R_002edll-directly">Calling R.dll directly</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-setVar"><code>setVar</code></a></td><td class="printindex-index-section"><a href="#Finding-and-setting-variables">Finding and setting variables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-sign"><code>sign</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-signrank_005ffree"><code>signrank_free</code></a></td><td class="printindex-index-section"><a href="#Distribution-functions">Distribution functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-sinpi"><code>sinpi</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-str2type"><code>str2type</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-STRING_005fELT"><code>STRING_ELT</code></a></td><td class="printindex-index-section"><a href="#Handling-character-data">Handling character data</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-summaryRprof"><code>summaryRprof</code></a></td><td class="printindex-index-section"><a href="#Memory-statistics-from-Rprof">Memory statistics from Rprof</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-system"><code>system</code></a></td><td class="printindex-index-section"><a href="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-system_002etime"><code>system.time</code></a></td><td class="printindex-index-section"><a href="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-system2"><code>system2</code></a></td><td class="printindex-index-section"><a href="#Operating-system-access">Operating system access</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-T">T</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-TAG"><code>TAG</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-tanpi"><code>tanpi</code></a></td><td class="printindex-index-section"><a href="#Numerical-Utilities">Numerical Utilities</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-tetragamma"><code>tetragamma</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-trace"><code>trace</code></a></td><td class="printindex-index-section"><a href="#Debugging-R-code">Debugging R code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-traceback"><code>traceback</code></a></td><td class="printindex-index-section"><a href="#Debugging-R-code">Debugging R code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-tracemem"><code>tracemem</code></a></td><td class="printindex-index-section"><a href="#Tracing-copies-of-an-object">Tracing copies of an object</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-translateChar"><code>translateChar</code></a></td><td class="printindex-index-section"><a href="#Character-encoding-issues">Character encoding issues</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-translateCharUTF8"><code>translateCharUTF8</code></a></td><td class="printindex-index-section"><a href="#Character-encoding-issues">Character encoding issues</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-trigamma"><code>trigamma</code></a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-TRUE"><code>TRUE</code></a></td><td class="printindex-index-section"><a href="#Mathematical-constants">Mathematical constants</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-type2char"><code>type2char</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-type2str"><code>type2str</code></a></td><td class="printindex-index-section"><a href="#Some-convenience-functions">Some convenience functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-TYPEOF"><code>TYPEOF</code></a></td><td class="printindex-index-section"><a href="#Calling-_002eExternal">Calling .External</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-U">U</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-undebug"><code>undebug</code></a></td><td class="printindex-index-section"><a href="#Debugging-R-code">Debugging R code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-unif_005frand"><code>unif_rand</code></a></td><td class="printindex-index-section"><a href="#Random-numbers">Random numbers</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-UNPROTECT"><code>UNPROTECT</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-unprotect"><code>unprotect</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-UNPROTECT_005fPTR"><code>UNPROTECT_PTR</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-unprotect_005fptr"><code>unprotect_ptr</code></a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-untracemem"><code>untracemem</code></a></td><td class="printindex-index-section"><a href="#Tracing-copies-of-an-object">Tracing copies of an object</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-useDynLib"><code>useDynLib</code></a></td><td class="printindex-index-section"><a href="#useDynLib">useDynLib</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-V">V</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-VECTOR_005fELT"><code>VECTOR_ELT</code></a></td><td class="printindex-index-section"><a href="#Vector-accessor-functions">Vector accessor functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-vmaxget"><code>vmaxget</code></a></td><td class="printindex-index-section"><a href="#Transient-storage-allocation">Transient storage allocation</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-vmaxset"><code>vmaxset</code></a></td><td class="printindex-index-section"><a href="#Transient-storage-allocation">Transient storage allocation</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-vmmin"><code>vmmin</code></a></td><td class="printindex-index-section"><a href="#Optimization">Optimization</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Function-and-variable-index_vr_letter-W">W</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-warning"><code>warning</code></a></td><td class="printindex-index-section"><a href="#Error-signaling">Error signaling</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-warningcall"><code>warningcall</code></a></td><td class="printindex-index-section"><a href="#Error-signaling">Error signaling</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-warningcall_005fimmediate"><code>warningcall_immediate</code></a></td><td class="printindex-index-section"><a href="#Error-signaling">Error signaling</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-wilcox_005ffree"><code>wilcox_free</code></a></td><td class="printindex-index-section"><a href="#Distribution-functions">Distribution functions</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
</table>
<table summary="" class="vr-letters-footer-printindex"><tr><th>Jump to: &nbsp; </th><td><a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-1"><b>.</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_symbol-2"><b>\</b></a>
 &nbsp; 
<br>
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-A"><b>A</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-B"><b>B</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-C"><b>C</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-D"><b>D</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-E"><b>E</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-F"><b>F</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-G"><b>G</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-I"><b>I</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-L"><b>L</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-M"><b>M</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-N"><b>N</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-O"><b>O</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-P"><b>P</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-Q"><b>Q</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-R"><b>R</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-S"><b>S</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-T"><b>T</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-U"><b>U</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-V"><b>V</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Function-and-variable-index_vr_letter-W"><b>W</b></a>
 &nbsp; 
</td></tr></table>
</div>

<hr>
</div>
<div class="unnumbered-level-extent" id="Concept-index">
<div class="nav-panel">
<p>
Previous: <a href="#Function-and-variable-index" accesskey="p" rel="prev">Function and variable index</a>, Up: <a href="#Top" accesskey="u" rel="up">Writing R Extensions</a> &nbsp; [<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="#Function-and-variable-index" title="Index" rel="index">Index</a>]</p>
</div>
<h2 class="unnumbered" id="Concept-index-1"><span>Concept index<a class="copiable-link" href="#Concept-index-1"> &para;</a></span></h2>

<div class="printindex cp-printindex">
<table summary="" class="cp-letters-header-printindex"><tr><th>Jump to: &nbsp; </th><td><a class="summary-letter-printindex" href="#Concept-index_cp_symbol-1"><b>.</b></a>
 &nbsp; 
<br>
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-A"><b>A</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-B"><b>B</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-C"><b>C</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-D"><b>D</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-E"><b>E</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-F"><b>F</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-G"><b>G</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-H"><b>H</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-I"><b>I</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-L"><b>L</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-M"><b>M</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-N"><b>N</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-O"><b>O</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-P"><b>P</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-R"><b>R</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-S"><b>S</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-T"><b>T</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-U"><b>U</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-V"><b>V</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-W"><b>W</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-Z"><b>Z</b></a>
 &nbsp; 
</td></tr></table>
<table summary="" class="cp-entries-printindex" border="0">
<tr><td></td><th class="entries-header-printindex">Index Entry</th><th class="sections-header-printindex">Section</th></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_symbol-1">.</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002einstall_005fextras-file">.install_extras file</a></td><td class="printindex-index-section"><a href="#Writing-package-vignettes">Writing package vignettes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eRbuildignore-file">.Rbuildignore file</a></td><td class="printindex-index-section"><a href="#Building-package-tarballs">Building package tarballs</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-_002eRinstignore-file">.Rinstignore file</a></td><td class="printindex-index-section"><a href="#Package-subdirectories">Package subdirectories</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-A">A</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Allocating-storage">Allocating storage</a></td><td class="printindex-index-section"><a href="#Allocating-storage">Allocating storage</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Attributes">Attributes</a></td><td class="printindex-index-section"><a href="#Attributes">Attributes</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-B">B</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Bessel-functions">Bessel functions</a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Beta-function">Beta function</a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Building-binary-packages">Building binary packages</a></td><td class="printindex-index-section"><a href="#Building-binary-packages">Building binary packages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Building-source-packages">Building source packages</a></td><td class="printindex-index-section"><a href="#Building-package-tarballs">Building package tarballs</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-C">C</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-C_002b_002b-code_002c-interfacing">C++ code, interfacing</a></td><td class="printindex-index-section"><a href="#Interfacing-C_002b_002b-code">Interfacing C++ code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Calling-C-from-Fortran-and-vice-versa">Calling C from Fortran and vice versa</a></td><td class="printindex-index-section"><a href="#Calling-C-from-Fortran-and-vice-versa">Calling C from Fortran and vice versa</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Checking-packages">Checking packages</a></td><td class="printindex-index-section"><a href="#Checking-packages">Checking packages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-citation">citation</a></td><td class="printindex-index-section"><a href="#Package-subdirectories">Package subdirectories</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-citation-1">citation</a></td><td class="printindex-index-section"><a href="#Preparing-translations">Preparing translations</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Classes">Classes</a></td><td class="printindex-index-section"><a href="#Classes">Classes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Cleanup-code">Cleanup code</a></td><td class="printindex-index-section"><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-cleanup-file">cleanup file</a></td><td class="printindex-index-section"><a href="#Package-structure">Package structure</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Condition-handling">Condition handling</a></td><td class="printindex-index-section"><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-conditionals">conditionals</a></td><td class="printindex-index-section"><a href="#Conditional-text">Conditional text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-configure-file">configure file</a></td><td class="printindex-index-section"><a href="#Package-structure">Package structure</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Copying-objects">Copying objects</a></td><td class="printindex-index-section"><a href="#Named-objects-and-copying">Named objects and copying</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-CRAN">CRAN</a></td><td class="printindex-index-section"><a href="#Creating-R-packages">Creating R packages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Creating-packages">Creating packages</a></td><td class="printindex-index-section"><a href="#Creating-R-packages">Creating R packages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Creating-shared-objects">Creating shared objects</a></td><td class="printindex-index-section"><a href="#Creating-shared-objects">Creating shared objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Cross_002dreferences-in-documentation">Cross-references in documentation</a></td><td class="printindex-index-section"><a href="#Cross_002dreferences">Cross-references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-cumulative-hazard">cumulative hazard</a></td><td class="printindex-index-section"><a href="#Distribution-functions">Distribution functions</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-D">D</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Debugging">Debugging</a></td><td class="printindex-index-section"><a href="#Debugging-compiled-code">Debugging compiled code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-DESCRIPTION-file">DESCRIPTION file</a></td><td class="printindex-index-section"><a href="#The-DESCRIPTION-file">The DESCRIPTION file</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Details-of-R-types">Details of R types</a></td><td class="printindex-index-section"><a href="#Details-of-R-types">Details of R types</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Distribution-functions-from-C">Distribution functions from C</a></td><td class="printindex-index-section"><a href="#Distribution-functions">Distribution functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Documentation_002c-writing">Documentation, writing</a></td><td class="printindex-index-section"><a href="#Writing-R-documentation-files">Writing R documentation files</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Dynamic-loading">Dynamic loading</a></td><td class="printindex-index-section"><a href="#dyn_002eload-and-dyn_002eunload">dyn.load and dyn.unload</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-dynamic-pages">dynamic pages</a></td><td class="printindex-index-section"><a href="#Dynamic-pages">Dynamic pages</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-E">E</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Editing-Rd-files">Editing Rd files</a></td><td class="printindex-index-section"><a href="#Editing-Rd-files">Editing Rd files</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-encoding">encoding</a></td><td class="printindex-index-section"><a href="#Encoding">Encoding</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Error-handling">Error handling</a></td><td class="printindex-index-section"><a href="#Condition-handling-and-cleanup-code">Condition handling and cleanup code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Error-signaling-from-C">Error signaling from C</a></td><td class="printindex-index-section"><a href="#Error-signaling">Error signaling</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Error-signaling-from-Fortran">Error signaling from Fortran</a></td><td class="printindex-index-section"><a href="#Error-signaling-from-Fortran">Error signaling from Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Evaluating-R-expressions-from-C">Evaluating R expressions from C</a></td><td class="printindex-index-section"><a href="#Evaluating-R-expressions-from-C">Evaluating R expressions from C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-external-pointer">external pointer</a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-F">F</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Figures-in-documentation">Figures in documentation</a></td><td class="printindex-index-section"><a href="#Figures">Figures</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-finalizer">finalizer</a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Finding-variables">Finding variables</a></td><td class="printindex-index-section"><a href="#Finding-and-setting-variables">Finding and setting variables</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-G">G</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Gamma-function">Gamma function</a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Garbage-collection">Garbage collection</a></td><td class="printindex-index-section"><a href="#Garbage-Collection">Garbage Collection</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Generic-functions">Generic functions</a></td><td class="printindex-index-section"><a href="#Generic-functions-and-methods">Generic functions and methods</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-H">H</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-handling-character-data">handling character data</a></td><td class="printindex-index-section"><a href="#Handling-character-data">Handling character data</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Handling-lists">Handling lists</a></td><td class="printindex-index-section"><a href="#Handling-lists">Handling lists</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Handling-R-objects-in-C">Handling R objects in C</a></td><td class="printindex-index-section"><a href="#Handling-R-objects-in-C">Handling R objects in C</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-I">I</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-IEEE-special-values">IEEE special values</a></td><td class="printindex-index-section"><a href="#Missing-and-special-values">Missing and special values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-IEEE-special-values-1">IEEE special values</a></td><td class="printindex-index-section"><a href="#Missing-and-IEEE-values">Missing and IEEE values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-INDEX-file">INDEX file</a></td><td class="printindex-index-section"><a href="#The-INDEX-file">The INDEX file</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Indices">Indices</a></td><td class="printindex-index-section"><a href="#Indices">Indices</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Inspecting-R-objects-when-debugging">Inspecting R objects when debugging</a></td><td class="printindex-index-section"><a href="#Inspecting-R-objects">Inspecting R objects</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-integration">integration</a></td><td class="printindex-index-section"><a href="#Integration">Integration</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Interfaces-to-compiled-code">Interfaces to compiled code</a></td><td class="printindex-index-section"><a href="#Interface-functions-_002eC-and-_002eFortran">Interface functions .C and .Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Interfaces-to-compiled-code-1">Interfaces to compiled code</a></td><td class="printindex-index-section"><a href="#Interface-functions-_002eCall-and-_002eExternal">Interface functions .Call and .External</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Interfacing-C_002b_002b-code">Interfacing C++ code</a></td><td class="printindex-index-section"><a href="#Interfacing-C_002b_002b-code">Interfacing C++ code</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Interrupts">Interrupts</a></td><td class="printindex-index-section"><a href="#Allowing-interrupts">Allowing interrupts</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-L">L</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-LICENCE-file">LICENCE file</a></td><td class="printindex-index-section"><a href="#Licensing">Licensing</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-LICENSE-file">LICENSE file</a></td><td class="printindex-index-section"><a href="#Licensing">Licensing</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Lists-and-tables-in-documentation">Lists and tables in documentation</a></td><td class="printindex-index-section"><a href="#Lists-and-tables">Lists and tables</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-M">M</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Marking-text-in-documentation">Marking text in documentation</a></td><td class="printindex-index-section"><a href="#Marking-text">Marking text</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Mathematics-in-documentation">Mathematics in documentation</a></td><td class="printindex-index-section"><a href="#Mathematics">Mathematics</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Memory-allocation-from-C">Memory allocation from C</a></td><td class="printindex-index-section"><a href="#Memory-allocation">Memory allocation</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Memory-use">Memory use</a></td><td class="printindex-index-section"><a href="#Profiling-R-code-for-memory-use">Profiling R code for memory use</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Method-functions">Method functions</a></td><td class="printindex-index-section"><a href="#Generic-functions-and-methods">Generic functions and methods</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Missing-values">Missing values</a></td><td class="printindex-index-section"><a href="#Missing-and-special-values">Missing and special values</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Missing-values-1">Missing values</a></td><td class="printindex-index-section"><a href="#Missing-and-IEEE-values">Missing and IEEE values</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-N">N</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-namespaces">namespaces</a></td><td class="printindex-index-section"><a href="#Package-namespaces">Package namespaces</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-news">news</a></td><td class="printindex-index-section"><a href="#Package-subdirectories">Package subdirectories</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Numerical-analysis-subroutines-from-C">Numerical analysis subroutines from C</a></td><td class="printindex-index-section"><a href="#Numerical-analysis-subroutines">Numerical analysis subroutines</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Numerical-derivatives">Numerical derivatives</a></td><td class="printindex-index-section"><a href="#Calculating-numerical-derivatives">Calculating numerical derivatives</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-O">O</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-OpenMP">OpenMP</a></td><td class="printindex-index-section"><a href="#OpenMP-support">OpenMP support</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-OpenMP-1">OpenMP</a></td><td class="printindex-index-section"><a href="#Platform-and-version-information">Platform and version information</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Operating-system-access">Operating system access</a></td><td class="printindex-index-section"><a href="#Operating-system-access">Operating system access</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-optimization">optimization</a></td><td class="printindex-index-section"><a href="#Optimization">Optimization</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-P">P</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Package-builder">Package builder</a></td><td class="printindex-index-section"><a href="#Building-package-tarballs">Building package tarballs</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Package-structure">Package structure</a></td><td class="printindex-index-section"><a href="#Package-structure">Package structure</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Package-subdirectories">Package subdirectories</a></td><td class="printindex-index-section"><a href="#Package-subdirectories">Package subdirectories</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Packages">Packages</a></td><td class="printindex-index-section"><a href="#Creating-R-packages">Creating R packages</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Parsing-R-code-from-C">Parsing R code from C</a></td><td class="printindex-index-section"><a href="#Parsing-R-code-from-C">Parsing R code from C</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Platform_002dspecific-documentation">Platform-specific documentation</a></td><td class="printindex-index-section"><a href="#Platform_002dspecific-sections">Platform-specific sections</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Polygamma-functions">Polygamma functions</a></td><td class="printindex-index-section"><a href="#Mathematical-functions">Mathematical functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Printing-from-C">Printing from C</a></td><td class="printindex-index-section"><a href="#Printing">Printing</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Printing-from-Fortran">Printing from Fortran</a></td><td class="printindex-index-section"><a href="#Printing-from-Fortran">Printing from Fortran</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Processing-Rd-format">Processing Rd format</a></td><td class="printindex-index-section"><a href="#Processing-documentation-files">Processing documentation files</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Profiling">Profiling</a></td><td class="printindex-index-section"><a href="#Profiling-R-code-for-speed">Profiling R code for speed</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Profiling-1">Profiling</a></td><td class="printindex-index-section"><a href="#Profiling-R-code-for-memory-use">Profiling R code for memory use</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Profiling-2">Profiling</a></td><td class="printindex-index-section"><a href="#Profiling-compiled-code">Profiling compiled code</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-R">R</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Random-numbers-in-C">Random numbers in C</a></td><td class="printindex-index-section"><a href="#Random-numbers">Random numbers</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Random-numbers-in-C-1">Random numbers in C</a></td><td class="printindex-index-section"><a href="#Distribution-functions">Distribution functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Random-numbers-in-Fortran">Random numbers in Fortran</a></td><td class="printindex-index-section"><a href="#Calling-C-from-Fortran-and-vice-versa">Calling C from Fortran and vice versa</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Registering-native-routines">Registering native routines</a></td><td class="printindex-index-section"><a href="#Registering-native-routines">Registering native routines</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-S">S</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Setting-variables">Setting variables</a></td><td class="printindex-index-section"><a href="#Finding-and-setting-variables">Finding and setting variables</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Sort-functions-from-C">Sort functions from C</a></td><td class="printindex-index-section"><a href="#Utility-functions">Utility functions</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Sweave">Sweave</a></td><td class="printindex-index-section"><a href="#Writing-package-vignettes">Writing package vignettes</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-T">T</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-tarballs">tarballs</a></td><td class="printindex-index-section"><a href="#Building-package-tarballs">Building package tarballs</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Tidying-R-code">Tidying R code</a></td><td class="printindex-index-section"><a href="#Tidying-R-code">Tidying R code</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-U">U</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-user_002ddefined-macros">user-defined macros</a></td><td class="printindex-index-section"><a href="#User_002ddefined-macros">User-defined macros</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-V">V</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Version-information-from-C">Version information from C</a></td><td class="printindex-index-section"><a href="#Platform-and-version-information">Platform and version information</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-vignettes">vignettes</a></td><td class="printindex-index-section"><a href="#Writing-package-vignettes">Writing package vignettes</a></td></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Visibility">Visibility</a></td><td class="printindex-index-section"><a href="#Controlling-visibility">Controlling visibility</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-W">W</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-weak-reference">weak reference</a></td><td class="printindex-index-section"><a href="#External-pointers-and-weak-references">External pointers and weak references</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><th id="Concept-index_cp_letter-Z">Z</th></tr>
<tr><td></td><td class="printindex-index-entry"><a href="#index-Zero_002dfinding">Zero-finding</a></td><td class="printindex-index-section"><a href="#Zero_002dfinding">Zero-finding</a></td></tr>
<tr><td colspan="3"><hr></td></tr>
</table>
<table summary="" class="cp-letters-footer-printindex"><tr><th>Jump to: &nbsp; </th><td><a class="summary-letter-printindex" href="#Concept-index_cp_symbol-1"><b>.</b></a>
 &nbsp; 
<br>
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-A"><b>A</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-B"><b>B</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-C"><b>C</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-D"><b>D</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-E"><b>E</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-F"><b>F</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-G"><b>G</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-H"><b>H</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-I"><b>I</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-L"><b>L</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-M"><b>M</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-N"><b>N</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-O"><b>O</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-P"><b>P</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-R"><b>R</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-S"><b>S</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-T"><b>T</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-U"><b>U</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-V"><b>V</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-W"><b>W</b></a>
 &nbsp; 
<a class="summary-letter-printindex" href="#Concept-index_cp_letter-Z"><b>Z</b></a>
 &nbsp; 
</td></tr></table>
</div>

</div>
</div>
<div class="footnotes-segment">
<hr>
<h4 class="footnotes-heading">Footnotes</h4>

<h5 class="footnote-body-heading"><a id="FOOT1" href="#DOCF1">(1)</a></h5>
<p>although this is a persistent
mis-usage.  It seems to stem from S, whose analogues of R&rsquo;s packages
were officially known as <em class="emph">library sections</em> and later as
<em class="emph">chapters</em>, but almost always referred to as <em class="emph">libraries</em>.</p>
<h5 class="footnote-body-heading"><a id="FOOT2" href="#DOCF2">(2)</a></h5>
<p>This
seems to be commonly used for a file in &lsquo;markdown&rsquo; format.  Be aware
that most users of R will not know that, nor know how to view such a
file: platforms such as macOS and Windows do not have a default viewer
set in their file associations.  The <abbr class="acronym">CRAN</abbr> package web pages
render such files in <abbr class="acronym">HTML</abbr>: the converter used expects the file to be
encoded in UTF-8.</p>
<h5 class="footnote-body-heading"><a id="FOOT3" href="#DOCF3">(3)</a></h5>
<p>currently, top-level files
<samp class="file">.Rbuildignore</samp> and <samp class="file">.Rinstignore</samp>, and
<samp class="file">vignettes/.install_extras</samp>.</p>
<h5 class="footnote-body-heading"><a id="FOOT4" href="#DOCF4">(4)</a></h5>
<p>false positives are possible, but only a handful have been
seen so far.</p>
<h5 class="footnote-body-heading"><a id="FOOT5" href="#DOCF5">(5)</a></h5>
<p>at least if this
is done in a locale which matches the package encoding.</p>
<h5 class="footnote-body-heading"><a id="FOOT6" href="#DOCF6">(6)</a></h5>
<p>and
required by <abbr class="acronym">CRAN</abbr>, so checked by <code class="command">R CMD check
--as-cran</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT7" href="#DOCF7">(7)</a></h5>
<p>without a <samp class="file">src/Makefile*</samp> file.</p>
<h5 class="footnote-body-heading"><a id="FOOT8" href="#DOCF8">(8)</a></h5>
<p><abbr class="abbr">LTO</abbr> is not currently supported by the toolchain
used on &lsquo;<samp class="samp">aarch64</samp>&rsquo;.</p>
<h5 class="footnote-body-heading"><a id="FOOT9" href="#DOCF9">(9)</a></h5>
<p>But it is checked for Open Source packages
by <code class="command">R CMD check --as-cran</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT10" href="#DOCF10">(10)</a></h5>
<p>Duplicate definitions may
trigger a warning: see <a class="ref" href="#User_002ddefined-macros">User-defined macros</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT11" href="#DOCF11">(11)</a></h5>
<p><code class="code">bug.report</code> will try to extract an
email address from a <code class="code">Contact</code> field if there is no
<code class="code">BugReports</code> field.</p>
<h5 class="footnote-body-heading"><a id="FOOT12" href="#DOCF12">(12)</a></h5>
<p><abbr class="acronym">CRAN</abbr> expands them to e.g. <code class="code">GPL-2
| GPL-3</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT13" href="#DOCF13">(13)</a></h5>
<p>even one wrapped in <code class="code">\donttest</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT14" href="#DOCF14">(14)</a></h5>
<p>This includes all packages
directly called by <code class="code">library</code> and <code class="code">require</code> calls, as well as
data obtained <em class="emph">via</em> <code class="code">data(theirdata, package = &quot;somepkg&quot;)</code>
calls: <code class="command">R CMD check</code> will warn about all of these.  But there
are subtler uses which it may not detect: e.g. if package A uses
package B and makes use of functionality in package B which uses package
C which package B suggests or enhances, then package C needs to be in
the &lsquo;<samp class="samp">Suggests</samp>&rsquo; list for package A.  Nor will undeclared uses in
included files be reported, nor unconditional uses of packages listed
under &lsquo;<samp class="samp">Enhances</samp>&rsquo;.  <code class="command">R CMD check --as-cran</code> will detect more
of the subtler uses.</p>
<h5 class="footnote-body-heading"><a id="FOOT15" href="#DOCF15">(15)</a></h5>
<p>Extensions
<samp class="file">.S</samp> and <samp class="file">.s</samp> arise from code originally written for S(-PLUS),
but are commonly used for assembler code.  Extension <samp class="file">.q</samp> was used
for S, which at one time was tentatively called QPE.</p>
<h5 class="footnote-body-heading"><a id="FOOT16" href="#DOCF16">(16)</a></h5>
<p>but they should be in the encoding
declared in the <samp class="file">DESCRIPTION</samp> file.</p>
<h5 class="footnote-body-heading"><a id="FOOT17" href="#DOCF17">(17)</a></h5>
<p>This is true for OSes which
implement the &lsquo;<samp class="samp">C</samp>&rsquo; locale: Windows&rsquo; idea of the &lsquo;<samp class="samp">C</samp>&rsquo; locale uses
the WinAnsi charset.</p>
<h5 class="footnote-body-heading"><a id="FOOT18" href="#DOCF18">(18)</a></h5>
<p>More precisely, they can
contain the English alphanumeric characters and the symbols
&lsquo;<samp class="samp">$ - _ . + ! ' ( ) , ; &nbsp;= &amp;</samp>&rsquo;.</p>
<h5 class="footnote-body-heading"><a id="FOOT19" href="#DOCF19">(19)</a></h5>
<p>either or both of which may not be supported on particular
platforms.  Their main use is on macOS, but unfortunately recent
versions of the macOS <abbr class="abbr">SDK</abbr> have removed much of the support for Objective
C v1.0 and Objective C++.</p>
<h5 class="footnote-body-heading"><a id="FOOT20" href="#DOCF20">(20)</a></h5>
<p>This is not accepted by the Intel Fortran compiler.</p>
<h5 class="footnote-body-heading"><a id="FOOT21" href="#DOCF21">(21)</a></h5>
<p>Using <samp class="file">.hpp</samp> is not guaranteed
to be portable.</p>
<h5 class="footnote-body-heading"><a id="FOOT22" href="#DOCF22">(22)</a></h5>
<p>There is also &lsquo;<samp class="samp">__APPLE_CC__</samp>&rsquo;, but that indicates a
compiler with Apple-specific features not the OS, although for
historical reasons is is defined by LLVM <code class="command">clang</code>.  It is
used in <samp class="file">Rinlinedfuns.h</samp>.</p>
<h5 class="footnote-body-heading"><a id="FOOT23" href="#DOCF23">(23)</a></h5>
<p>the POSIX
terminology, called &lsquo;make variables&rsquo; by GNU make.</p>
<h5 class="footnote-body-heading"><a id="FOOT24" href="#DOCF24">(24)</a></h5>
<p>The best way to generate such a file is to copy
the <samp class="file">.Rout</samp> from a successful run of <code class="command">R CMD check</code>.  If you
want to generate it separately, do run R with options
<samp class="option">--vanilla --no-echo</samp> and with environment variable
<code class="env">LANGUAGE=en</code> set to get messages in English.  Be careful not to use
output with the option <samp class="option">--timings</samp> (and note that
<samp class="option">--as-cran</samp> sets it).</p>
<h5 class="footnote-body-heading"><a id="FOOT25" href="#DOCF25">(25)</a></h5>
<p>e.g.
<a class="uref" href="https://www.rfc-editor.org/rfc/rfc4180">https://www.rfc-editor.org/rfc/rfc4180</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT26" href="#DOCF26">(26)</a></h5>
<p>People who have trouble with
case are advised to use <samp class="file">.rda</samp> as a common error is to refer to
<samp class="file">abc.RData</samp> as <samp class="file">abc.Rdata</samp>!</p>
<h5 class="footnote-body-heading"><a id="FOOT27" href="#DOCF27">(27)</a></h5>
<p>For all the <abbr class="acronym">CRAN</abbr> packages tested,
either <code class="code">gz</code> or <code class="code">bzip2</code> provided a very substantial reduction
in installed size.</p>
<h5 class="footnote-body-heading"><a id="FOOT28" href="#DOCF28">(28)</a></h5>
<p>&lsquo;<samp class="samp">BWidget</samp>&rsquo; still is on Windows but
&lsquo;<samp class="samp">Tktable</samp>&rsquo; was not in R 4.0.0.</p>
<h5 class="footnote-body-heading"><a id="FOOT29" href="#DOCF29">(29)</a></h5>
<p>The script
should only assume a POSIX-compliant <code class="command">/bin/sh</code> &ndash; see
<a class="uref" href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html">https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html</a>.
In particular <code class="command">bash</code> extensions must not be used, and not all
R platforms have a <code class="command">bash</code> command, let alone one at
<samp class="file">/bin/bash</samp>.  All known shells used with R support the use of
backticks, but not all support &lsquo;<samp class="samp">$(<var class="var">cmd</var>)</samp>&rsquo;.  However, real-world
shells are not fully POSIX-compliant and omissions and idiosyncrasies
need to be worked around&mdash;which Autoconf will do for you.  Arithmetic
expansion is a known issue: see
<a class="uref" href="https://www.gnu.org/software/autoconf/manual/autoconf.html#Portable-Shell">https://www.gnu.org/software/autoconf/manual/autoconf.html#Portable-Shell</a>
for this and others.  Some checks can be done by the
<code class="code">checkbashisms</code> Perl script at
<a class="uref" href="https://sourceforge.net/projects/checkbaskisms/files">https://sourceforge.net/projects/checkbaskisms/files</a>, also
available in most Linux distributions in a package named either
&lsquo;<samp class="samp">devscripts</samp>&rsquo; or &lsquo;<samp class="samp">devscripts-checkbashisms</samp>&rsquo;: a later version
can be extracted from Debian sources such as the most recent
<samp class="file">tar.xz</samp> in
<a class="uref" href="https://deb.debian.org/debian/pool/main/d/devscripts/">https://deb.debian.org/debian/pool/main/d/devscripts/</a> and has
been needed for recent versions of Perl.</p>
<h5 class="footnote-body-heading"><a id="FOOT30" href="#DOCF30">(30)</a></h5>
<p><a class="uref" href="https://www.gnu.org/software/autoconf-archive/ax_blas.html">https://www.gnu.org/software/autoconf-archive/ax_blas.html</a>. If
you include macros from that archive you need to arrange for them to be
included in the package sources for use by <code class="command">autoreconf</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT31" href="#DOCF31">(31)</a></h5>
<p>but it is available on the
machines used to produce the <abbr class="acronym">CRAN</abbr> binary packages: however as
Apple does not ship <samp class="file">.pc</samp> files for its system libraries such as
<code class="code">expat</code>, <code class="code">libcurl</code>, <code class="code">libxml2</code>, <code class="code">sqlite3</code> and
&lsquo;<samp class="samp">zlib</samp>&rsquo;, it may well not find information on these.  Some
substitutes are available from
<a class="url" href="https://github.com/R-macos/recipes/tree/master/stubs/pkgconfig-darwin">https://github.com/R-macos/recipes/tree/master/stubs/pkgconfig-darwin</a>
and are installed on the <abbr class="acronym">CRAN</abbr> package builders.</p>
<h5 class="footnote-body-heading"><a id="FOOT32" href="#DOCF32">(32)</a></h5>
<p>It is not wise
to check the version of <code class="command">pkg-config</code> as it is sometimes a link
to
<code class="command">pkgconf</code>, a separate project with a different version series.</p>
<h5 class="footnote-body-heading"><a id="FOOT33" href="#DOCF33">(33)</a></h5>
<p>but not all projects get this
right when only a static library is installed, so it is often necessary
to try in turn <code class="command">pkg-config --libs</code> and <code class="command">pkg-config
--static --libs</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT34" href="#DOCF34">(34)</a></h5>
<p>a decade ago Autoconf used
<samp class="file">configure.in</samp>: this is still accepted but should be renamed and
<code class="command">autoreconf</code> as used by <code class="command">R CMD check --as-cran</code> will
report as such.</p>
<h5 class="footnote-body-heading"><a id="FOOT35" href="#DOCF35">(35)</a></h5>
<p>For those using
<code class="command">autoconf</code> 2.70 or later there is also
<code class="code">AC_CONFIG_MACRO_DIRS</code> which allows multiple directories to be
specified.</p>
<h5 class="footnote-body-heading"><a id="FOOT36" href="#DOCF36">(36)</a></h5>
<p>in POSIX parlance: GNU <code class="command">make</code>
calls these &lsquo;make variables&rsquo;.</p>
<h5 class="footnote-body-heading"><a id="FOOT37" href="#DOCF37">(37)</a></h5>
<p>at least on Unix-alikes: the Windows build currently
resolves such dependencies to a static Fortran library when
<samp class="file">Rblas.dll</samp> is built.</p>
<h5 class="footnote-body-heading"><a id="FOOT38" href="#DOCF38">(38)</a></h5>
<p><a class="uref" href="https://www.openmp.org/">https://www.openmp.org/</a>,
<a class="uref" href="https://en.wikipedia.org/wiki/OpenMP">https://en.wikipedia.org/wiki/OpenMP</a>,
<a class="uref" href="https://hpc-tutorials.llnl.gov/openmp/">https://hpc-tutorials.llnl.gov/openmp/</a></p>
<h5 class="footnote-body-heading"><a id="FOOT39" href="#DOCF39">(39)</a></h5>
<p>There are somewhat fragile workarounds: see
<a class="uref" href="https://mac.r-project.org/openmp/">https://mac.r-project.org/openmp/</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT40" href="#DOCF40">(40)</a></h5>
<p>Default builds of LLVM <code class="command">clang</code> 3.8.0
and later have support for <abbr class="abbr">OpenMP</abbr>, but the <code class="code">libomp</code> run-time
library may not be installed.</p>
<h5 class="footnote-body-heading"><a id="FOOT41" href="#DOCF41">(41)</a></h5>
<p>In most implementations the <code class="code">_OPENMP</code>
macro has value a date which can be mapped to an <abbr class="abbr">OpenMP</abbr> version: for
example, value <code class="code">201307</code> is the date of version 4.0 (July
2013). However this may be used to denote the latest version which is
partially supported, not that which is fully implemented.</p>
<h5 class="footnote-body-heading"><a id="FOOT42" href="#DOCF42">(42)</a></h5>
<p>Windows default, not
MinGW-w64 default.</p>
<h5 class="footnote-body-heading"><a id="FOOT43" href="#DOCF43">(43)</a></h5>
<p>Which it was at the time of writing with GCC,
Intel and Clang compilers.  The count may include the thread
running the main process.</p>
<h5 class="footnote-body-heading"><a id="FOOT44" href="#DOCF44">(44)</a></h5>
<p>Be
careful not to declare <code class="code">nthreads</code> as <code class="code">const int</code>: the Oracle
compiler required it to be &lsquo;an lvalue&rsquo;.</p>
<h5 class="footnote-body-heading"><a id="FOOT45" href="#DOCF45">(45)</a></h5>
<p>A few OSes (<abbr class="abbr">AIX</abbr>, Windows) do not
need special flags for such code, but most do&mdash;although compilers will
often generate PIC code when not asked to do so.</p>
<h5 class="footnote-body-heading"><a id="FOOT46" href="#DOCF46">(46)</a></h5>
<p>Intel compilers do not by default but this is worked
around when using packages without a <samp class="file">src/Makefile</samp>.</p>
<h5 class="footnote-body-heading"><a id="FOOT47" href="#DOCF47">(47)</a></h5>
<p>Some changes are linked
from
<a class="uref" href="https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations">https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations</a>:
there were also additional deprecations.</p>
<h5 class="footnote-body-heading"><a id="FOOT48" href="#DOCF48">(48)</a></h5>
<p>Values <code class="code">201103L</code>, <code class="code">201402L</code>, <code class="code">201703L</code>
and <code class="code">202002L</code> are most commonly used for C++11, C++14, C++17 and
C++20 respectively, but some compilers set <code class="code">1L</code>. For C++23 all that
can currently be assumed is a value greater than that for C++20: for
example <code class="command">g++</code> 12 uses <code class="code">202100L</code> and <code class="command">clang++</code> (LLVM
15, Apple 14) uses <code class="code">202101L</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT49" href="#DOCF49">(49)</a></h5>
<p>Often historically used to mean &lsquo;not C++98&rsquo;</p>
<h5 class="footnote-body-heading"><a id="FOOT50" href="#DOCF50">(50)</a></h5>
<p>See
<a class="uref" href="https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations">https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations</a>
or
<a class="uref" href="https://en.cppreference.com/w/cpp/experimental/feature_test">https://en.cppreference.com/w/cpp/experimental/feature_test</a>.
It seems a reasonable assumption that any compiler promising some C++14
conformance will provide these&mdash;e.g. <code class="command">g++</code> 4.9.x did but
4.8.5 did not.</p>
<h5 class="footnote-body-heading"><a id="FOOT51" href="#DOCF51">(51)</a></h5>
<p>The <code class="code">__cplusplus</code> value for C++23 is not yet
finalized and all but some of the latest compilers use values from earlier
drafts.</p>
<h5 class="footnote-body-heading"><a id="FOOT52" href="#DOCF52">(52)</a></h5>
<p>On systems which use sub-architectures,
architecture-specific versions such as <samp class="file">~/.R/check.Renviron.x64</samp>
take precedence.</p>
<h5 class="footnote-body-heading"><a id="FOOT53" href="#DOCF53">(53)</a></h5>
<p>A suitable <code class="command">file.exe</code> is
part of the Windows toolset: it checks for <code class="command">gfile</code> if a suitable
<code class="command">file</code> is not found: the latter is available in the OpenCSW
collection for Solaris at <a class="uref" href="https://www.opencsw.org/">https://www.opencsw.org/</a>.  The source
repository is <a class="uref" href="http://ftp.astron.com/pub/file/">http://ftp.astron.com/pub/file/</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT54" href="#DOCF54">(54)</a></h5>
<p>An exception is made
for subdirectories with names starting &lsquo;<samp class="samp">win</samp>&rsquo; or &lsquo;<samp class="samp">Win</samp>&rsquo;.</p>
<h5 class="footnote-body-heading"><a id="FOOT55" href="#DOCF55">(55)</a></h5>
<p>on most other platforms such runtime
libraries are dynamic, but static libraries are currently used on
Windows because the toolchain is not a standard part of the OS.</p>
<h5 class="footnote-body-heading"><a id="FOOT56" href="#DOCF56">(56)</a></h5>
<p>or if option <samp class="option">--use-valgrind</samp> is
used or environment variable <code class="env">_R_CHECK_ALWAYS_LOG_VIGNETTE_OUTPUT_</code>
is set to a true value or if there are differences from a target output
file</p>
<h5 class="footnote-body-heading"><a id="FOOT57" href="#DOCF57">(57)</a></h5>
<p>for the most
comprehensive checking this should be 5.8.0 or later: any for which
<code class="command">tidy --version</code> does not report a version number will be too
old &ndash; this includes the 2006 version shipped with macOS.</p>
<h5 class="footnote-body-heading"><a id="FOOT58" href="#DOCF58">(58)</a></h5>
<p>For example, in early
2014 <a class="url" href="https://CRAN.R-project.org/package=gdata"><strong class="strong">gdata</strong></a> declared &lsquo;<samp class="samp">Imports: gtools</samp>&rsquo; and <a class="url" href="https://CRAN.R-project.org/package=gtools"><strong class="strong">gtools</strong></a>
declared &lsquo;<samp class="samp">Imports: gdata</samp>&rsquo;.</p>
<h5 class="footnote-body-heading"><a id="FOOT59" href="#DOCF59">(59)</a></h5>
<p>called <samp class="file">CVS</samp> or
<samp class="file">.svn</samp> or <samp class="file">.arch-ids</samp> or <samp class="file">.bzr</samp> or <samp class="file">.git</samp> (but not
files called <samp class="file">.git</samp>) or <samp class="file">.hg</samp>.</p>
<h5 class="footnote-body-heading"><a id="FOOT60" href="#DOCF60">(60)</a></h5>
<p>called <samp class="file">.metadata</samp>.</p>
<h5 class="footnote-body-heading"><a id="FOOT61" href="#DOCF61">(61)</a></h5>
<p>which is an error: GNU make uses
<samp class="file">GNUmakefile</samp>.</p>
<h5 class="footnote-body-heading"><a id="FOOT62" href="#DOCF62">(62)</a></h5>
<p>see <code class="code">tools:::.hidden_file_exclusions</code> and
<code class="code">tools:::get_exclude_patterns()</code> for further
excluded files and file patterns, respectively.</p>
<h5 class="footnote-body-heading"><a id="FOOT63" href="#DOCF63">(63)</a></h5>
<p>and to avoid problems with case-insensitive file
systems, lower-case versions of all these extensions.</p>
<h5 class="footnote-body-heading"><a id="FOOT64" href="#DOCF64">(64)</a></h5>
<p>unless inhibited by using
&lsquo;<samp class="samp">BuildVignettes: no</samp>&rsquo; in the <samp class="file">DESCRIPTION</samp> file.</p>
<h5 class="footnote-body-heading"><a id="FOOT65" href="#DOCF65">(65)</a></h5>
<p>provided the conditions of the
package&rsquo;s license are met: many, including <abbr class="acronym">CRAN</abbr>, see the
omission of source components as incompatible with an Open Source
license.</p>
<h5 class="footnote-body-heading"><a id="FOOT66" href="#DOCF66">(66)</a></h5>
<p><code class="code">R_HOME/bin</code> is prepended to the
<code class="env">PATH</code> so that references to <code class="command">R</code> or <code class="command">Rscript</code> in the
<samp class="file">Makefile</samp> do make use of the currently running version of R.</p>
<h5 class="footnote-body-heading"><a id="FOOT67" href="#DOCF67">(67)</a></h5>
<p>Note that
lazy-loaded datasets are <em class="emph">not</em> in the package&rsquo;s namespace so need
to be accessed <em class="emph">via</em> <code class="code">::</code>, e.g.
<code class="code">survival::survexp.us</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT68" href="#DOCF68">(68)</a></h5>
<p>they will be called
with two unnamed arguments, in that order.</p>
<h5 class="footnote-body-heading"><a id="FOOT69" href="#DOCF69">(69)</a></h5>
<p>NB: this will only be read in all versions of R if
the package contains R code in a <samp class="file">R</samp> directory.</p>
<h5 class="footnote-body-heading"><a id="FOOT70" href="#DOCF70">(70)</a></h5>
<p>Note that this is the
basename of the shared object, and the appropriate extension (<samp class="file">.so</samp>
or <samp class="file">.dll</samp>) will be added.</p>
<h5 class="footnote-body-heading"><a id="FOOT71" href="#DOCF71">(71)</a></h5>
<p><code class="code">Imports: methods</code> may suffice,
but package code is little exercised without the <strong class="strong">methods</strong> package
on the search path and may not be fully robust to this scenario.
</p>
<h5 class="footnote-body-heading"><a id="FOOT72" href="#DOCF72">(72)</a></h5>
<p>This defaults to the same
pattern as <code class="code">exportPattern</code>: use something like
<code class="code">exportClassPattern(&quot;^$&quot;)</code> to override this.</p>
<h5 class="footnote-body-heading"><a id="FOOT73" href="#DOCF73">(73)</a></h5>
<p>if it does, there will be opaque warnings about
replacing imports if the classes/methods are also imported.</p>
<h5 class="footnote-body-heading"><a id="FOOT74" href="#DOCF74">(74)</a></h5>
<p>People use <code class="code">dev.new()</code> to open a
device at a particular size: that is not portable but using
<code class="code">dev.new(noRStudioGD = TRUE)</code> helps.</p>
<h5 class="footnote-body-heading"><a id="FOOT75" href="#DOCF75">(75)</a></h5>
<p>Solaris <code class="command">make</code> did not accept
<abbr class="abbr">CRLF</abbr>-terminated Makefiles; Solaris warned about and some other
<code class="command">make</code>s ignore incomplete final lines.</p>
<h5 class="footnote-body-heading"><a id="FOOT76" href="#DOCF76">(76)</a></h5>
<p>This was apparently
introduced in SunOS 4, and is available elsewhere <em class="emph">provided</em> it is
surrounded by spaces.</p>
<h5 class="footnote-body-heading"><a id="FOOT77" href="#DOCF77">(77)</a></h5>
<p>GNU make,
BSD make and other variants of <code class="command">pmake</code> in FreeBSD, NetBSD and
formerly in macOS, and formerly AT&amp;T make as implemented on Solaris and
&lsquo;Distributed Make&rsquo; (<code class="code">dmake</code>), part of Oracle Developer Studio and
available in other versions including from Apache OpenOffice.</p>
<h5 class="footnote-body-heading"><a id="FOOT78" href="#DOCF78">(78)</a></h5>
<p>For example, <code class="command">test</code>
options <samp class="option">-a</samp> and <samp class="option">-e</samp> are not portable, and not supported
in the AT&amp;T Bourne shell used on Solaris 10/11, even though they are in
the POSIX standard.  Nor did Solaris support &lsquo;<samp class="samp">$(<var class="var">cmd</var>)</samp>&rsquo;.</p>
<h5 class="footnote-body-heading"><a id="FOOT79" href="#DOCF79">(79)</a></h5>
<p>as from
R 4.0.0 the default is <code class="command">bash</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT80" href="#DOCF80">(80)</a></h5>
<p>it was not in the Bourne shell, and was not supported
by Solaris 10.</p>
<h5 class="footnote-body-heading"><a id="FOOT81" href="#DOCF81">(81)</a></h5>
<p><a class="uref" href="https://fortranwiki.org/fortran/show/Modernizing+Old+Fortran">https://fortranwiki.org/fortran/show/Modernizing+Old+Fortran</a>
may help explain some of the warnings from <code class="command">gfortran -Wall
-pedantic</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT82" href="#DOCF82">(82)</a></h5>
<p>or where supported the variants <code class="code">_Exit</code> and
<code class="code">_exit</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT83" href="#DOCF83">(83)</a></h5>
<p>This and
<code class="code">srandom</code> are in any case not portable.  They are in POSIX but not
in the C99 standard, and not available on Windows.</p>
<h5 class="footnote-body-heading"><a id="FOOT84" href="#DOCF84">(84)</a></h5>
<p>including
macOS as from version 13.</p>
<h5 class="footnote-body-heading"><a id="FOOT85" href="#DOCF85">(85)</a></h5>
<p>in <samp class="file">libselinux</samp>.</p>
<h5 class="footnote-body-heading"><a id="FOOT86" href="#DOCF86">(86)</a></h5>
<p>At least Linux and Windows, but not macOS.</p>
<h5 class="footnote-body-heading"><a id="FOOT87" href="#DOCF87">(87)</a></h5>
<p>except perhaps the simplest kind as used by
<code class="code">download.file()</code> in non-interactive use.</p>
<h5 class="footnote-body-heading"><a id="FOOT88" href="#DOCF88">(88)</a></h5>
<p>Whereas the GNU linker reorders so <samp class="option">-L</samp> options
are processed first, the Solaris one did not.</p>
<h5 class="footnote-body-heading"><a id="FOOT89" href="#DOCF89">(89)</a></h5>
<p>some versions of macOS did not.</p>
<h5 class="footnote-body-heading"><a id="FOOT90" href="#DOCF90">(90)</a></h5>
<p>If a Java interpreter is
required directly (not <em class="emph">via</em> <a class="url" href="https://CRAN.R-project.org/package=rJava"><strong class="strong">rJava</strong></a>) this must be declared
and its presence tested like any other external command.</p>
<h5 class="footnote-body-heading"><a id="FOOT91" href="#DOCF91">(91)</a></h5>
<p>For example, the ability to handle &lsquo;<samp class="samp">https://</samp>&rsquo;
URLs.</p>
<h5 class="footnote-body-heading"><a id="FOOT92" href="#DOCF92">(92)</a></h5>
<p>Not
doing so is the default on Windows, overridden for the R
executables.</p>
<h5 class="footnote-body-heading"><a id="FOOT93" href="#DOCF93">(93)</a></h5>
<p>These are not needed for the default compiler settings
on &lsquo;<samp class="samp">x86_64</samp>&rsquo; but are likely to be needed on &lsquo;<samp class="samp">ix86</samp>&rsquo;.</p>
<h5 class="footnote-body-heading"><a id="FOOT94" href="#DOCF94">(94)</a></h5>
<p>Select &lsquo;Save as&rsquo;, and select
&lsquo;Reduce file size&rsquo; from the &lsquo;Quartz filter&rsquo; menu&rsquo;: this can be accessed
in other ways, for example by Automator.</p>
<h5 class="footnote-body-heading"><a id="FOOT95" href="#DOCF95">(95)</a></h5>
<p>except perhaps some
special characters such as backslash and hash which may be taken over
for currency symbols.</p>
<h5 class="footnote-body-heading"><a id="FOOT96" href="#DOCF96">(96)</a></h5>
<p>Typically on a Unix-alike this is
done by telling <code class="command">fontconfig</code> where to find suitable fonts to
select glyphs from.</p>
<h5 class="footnote-body-heading"><a id="FOOT97" href="#DOCF97">(97)</a></h5>
<p>which it is on all known
platforms, and is required as from R 4.0.0</p>
<h5 class="footnote-body-heading"><a id="FOOT98" href="#DOCF98">(98)</a></h5>
<p>Ubuntu provides 5 years of support (but
people were running 14.04 after 7 years) and RHEL provides 10 years full
support and up to 14 with extended support.</p>
<h5 class="footnote-body-heading"><a id="FOOT99" href="#DOCF99">(99)</a></h5>
<p>This is seen on Linux, Solaris
and FreeBSD, although each has other ways to turn on all extensions,
e.g. defining <code class="code">_GNU_SOURCE</code>, <code class="code">__EXTENSIONS__</code> or
<code class="code">_BSD_SOURCE</code>: the GCC compilers by default define
<code class="code">_GNU_SOURCE</code> unless a strict standard such as <samp class="option">-std=c99</samp> is
used.  On macOS extensions are declared unless one of these macros is
given too small a value.</p>
<h5 class="footnote-body-heading"><a id="FOOT100" href="#DOCF100">(100)</a></h5>
<p>often taken from
the toolchain&rsquo;s headers.</p>
<h5 class="footnote-body-heading"><a id="FOOT101" href="#DOCF101">(101)</a></h5>
<p>at the time of writing &lsquo;<samp class="samp">arm64</samp>&rsquo; macOS both warned
and did not supply a prototype in <samp class="file">math.h</samp> which resulted in a
compilation error.</p>
<h5 class="footnote-body-heading"><a id="FOOT102" href="#DOCF102">(102)</a></h5>
<p>also part of C++11 and later.</p>
<h5 class="footnote-body-heading"><a id="FOOT103" href="#DOCF103">(103)</a></h5>
<p>which often is the same as the header included by
the C compiler, but some compilers have wrappers for some of the C
headers.</p>
<h5 class="footnote-body-heading"><a id="FOOT104" href="#DOCF104">(104)</a></h5>
<p>Although this is expected
to be part of C23, full support of that is years away.</p>
<h5 class="footnote-body-heading"><a id="FOOT105" href="#DOCF105">(105)</a></h5>
<p><a class="uref" href="https://stackoverflow.com/questions/32739018/a-replacement-for-stdbind2nd">https://stackoverflow.com/questions/32739018/a-replacement-for-stdbind2nd</a></p>
<h5 class="footnote-body-heading"><a id="FOOT106" href="#DOCF106">(106)</a></h5>
<p>it is allowed
but ignored in system headers.</p>
<h5 class="footnote-body-heading"><a id="FOOT107" href="#DOCF107">(107)</a></h5>
<p>when using the
macOS 13 <abbr class="abbr">SDK</abbr> with a deployment target of macOS 13.</p>
<h5 class="footnote-body-heading"><a id="FOOT108" href="#DOCF108">(108)</a></h5>
<p>and at one time as DEC Fortran, hence the
<code class="code">DEC</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT109" href="#DOCF109">(109)</a></h5>
<p>see
<a class="uref" href="https://gcc.gnu.org/gcc-10/porting_to.html">https://gcc.gnu.org/gcc-10/porting_to.html</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT110" href="#DOCF110">(110)</a></h5>
<p>See
<a class="uref" href="https://prereleases.llvm.org/11.0.0/rc2/tools/clang/docs/ReleaseNotes.html#modified-compiler-flags">https://prereleases.llvm.org/11.0.0/rc2/tools/clang/docs/ReleaseNotes.html#modified-compiler-flags</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT111" href="#DOCF111">(111)</a></h5>
<p>In principle this could
depend on the OS, but has been checked on Linux and macOS.</p>
<h5 class="footnote-body-heading"><a id="FOOT112" href="#DOCF112">(112)</a></h5>
<p>discontinued in 2023.</p>
<h5 class="footnote-body-heading"><a id="FOOT113" href="#DOCF113">(113)</a></h5>
<p>There is a portable way to do this in Fortran 2003
(<code class="code">ieee_is_nan()</code> in module <code class="code">ieee_arithmetic</code>), but that was
not supported in the versions 4.x of GNU Fortran.  A pretty robust
alternative is to test <code class="code">if(my_var /= my_var)</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT114" href="#DOCF114">(114)</a></h5>
<p>e.g. <code class="code">\alias</code>, <code class="code">\keyword</code> and
<code class="code">\note</code> sections.</p>
<h5 class="footnote-body-heading"><a id="FOOT115" href="#DOCF115">(115)</a></h5>
<p>There can be exceptions: for example
<samp class="file">Rd</samp> files are not allowed to start with a dot, and have to be
uniquely named on a case-insensitive file system.</p>
<h5 class="footnote-body-heading"><a id="FOOT116" href="#DOCF116">(116)</a></h5>
<p>in the current locale, and with special
treatment for LaTeX special characters and with any
&lsquo;<samp class="samp"><var class="var">pkgname</var>-package</samp>&rsquo; topic moved to the top of the list.</p>
<h5 class="footnote-body-heading"><a id="FOOT117" href="#DOCF117">(117)</a></h5>
<p><code class="code">\describe</code> can still be used for more general
lists, including when <code class="code">\item</code> labels need special markup such as
<code class="code">\var</code> for metasyntactic variables, see <a class="ref" href="#Marking-text">Marking text</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT118" href="#DOCF118">(118)</a></h5>
<p>as defined by the R function <code class="code">trimws</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT119" href="#DOCF119">(119)</a></h5>
<p>Currently it is
rendered differently in <abbr class="acronym">HTML</abbr> conversions, and in LaTeX and text conversion
outside &lsquo;<samp class="samp">\usage</samp>&rsquo; and &lsquo;<samp class="samp">\examples</samp>&rsquo; environments.</p>
<h5 class="footnote-body-heading"><a id="FOOT120" href="#DOCF120">(120)</a></h5>
<p>There is only a fine
distinction between <code class="code">\dots</code> and <code class="code">\ldots</code>.  It is technically
incorrect to use <code class="code">\ldots</code> in code blocks and <code class="code">tools::checkRd</code>
will warn about this&mdash;on the other hand the current converters treat
them the same way in code blocks, and elsewhere apart from the small
distinction between the two in LaTeX.</p>
<h5 class="footnote-body-heading"><a id="FOOT121" href="#DOCF121">(121)</a></h5>
<p>See the
examples section in the file <samp class="file">Paren.Rd</samp> for an example.</p>
<h5 class="footnote-body-heading"><a id="FOOT122" href="#DOCF122">(122)</a></h5>
<p>R
2.9.0 added support for UTF-8 Cyrillic characters in LaTeX, but on
some OSes this will need Cyrillic support added to LaTeX, so
environment variable <code class="env">_R_CYRILLIC_TEX_</code> may need to be set to a
non-empty value to enable this.</p>
<h5 class="footnote-body-heading"><a id="FOOT123" href="#DOCF123">(123)</a></h5>
<p>R
has to be built to enable this, but the option
<samp class="option">--enable-R-profiling</samp> is the default.</p>
<h5 class="footnote-body-heading"><a id="FOOT124" href="#DOCF124">(124)</a></h5>
<p>For Unix-alikes by default these are intervals
of CPU time, and for Windows of elapsed (&lsquo;wall-clock&rsquo;) time.  As from
R 4.4.0, elapsed time is optional on Unix-alikes</p>
<h5 class="footnote-body-heading"><a id="FOOT125" href="#DOCF125">(125)</a></h5>
<p>With the exceptions of the commands
listed below: an object of such a name can be printed <em class="emph">via</em> an
explicit call to <code class="code">print</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT126" href="#DOCF126">(126)</a></h5>
<p>The macOS support is for long-obsolete
versions.</p>
<h5 class="footnote-body-heading"><a id="FOOT127" href="#DOCF127">(127)</a></h5>
<p>in some
distributions packaged separately, for example as <samp class="file">valgrind-devel</samp>.</p>
<h5 class="footnote-body-heading"><a id="FOOT128" href="#DOCF128">(128)</a></h5>
<p>Those in some numeric, logical,
integer, raw, complex vectors and in memory allocated by
<code class="code">R_alloc</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT129" href="#DOCF129">(129)</a></h5>
<p>including using the data sections of R vectors after
they are freed.</p>
<h5 class="footnote-body-heading"><a id="FOOT130" href="#DOCF130">(130)</a></h5>
<p>small
fixed-size arrays by default in <code class="command">gfortran</code>, for example.</p>
<h5 class="footnote-body-heading"><a id="FOOT131" href="#DOCF131">(131)</a></h5>
<p>currently on &lsquo;<samp class="samp">x86_64</samp>&rsquo;/&lsquo;<samp class="samp">ix86</samp>&rsquo; Linux and
FreeBSD, with some support for Intel macOS but not
with the toolchain normally used with R. (There is a faster variant,
HWASAN, for &lsquo;<samp class="samp">aarch64</samp>&rsquo; only.)  On some platforms the runtime
library, <strong class="strong">libasan</strong>, needs to be installed separately, and for
checking C++ you may also need <strong class="strong">libubsan</strong>.</p>
<h5 class="footnote-body-heading"><a id="FOOT132" href="#DOCF132">(132)</a></h5>
<p>see
<a class="uref" href="https://llvm.org/devmtg/2014-04/PDFs/LightningTalks/EuroLLVM%202014%20--%20container%20overflow.pdf">https://llvm.org/devmtg/2014-04/PDFs/LightningTalks/EuroLLVM%202014%20--%20container%20overflow.pdf</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT133" href="#DOCF133">(133)</a></h5>
<p>part of the LLVM project and
distributed in <code class="code">llvm</code> <abbr class="acronym">RPM</abbr>s and <samp class="file">.deb</samp>s on Linux.  It is not
currently shipped by Apple.</p>
<h5 class="footnote-body-heading"><a id="FOOT134" href="#DOCF134">(134)</a></h5>
<p>as Ubuntu has been said to
do.</p>
<h5 class="footnote-body-heading"><a id="FOOT135" href="#DOCF135">(135)</a></h5>
<p>installed on some Linux systems as
<code class="command">asan_symbolize</code>, and obtainable from
<a class="uref" href="https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/asan/scripts/asan_symbolize.py">https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/asan/scripts/asan_symbolize.py</a>:
it makes use of <code class="command">llvm-symbolizer</code> if available.</p>
<h5 class="footnote-body-heading"><a id="FOOT136" href="#DOCF136">(136)</a></h5>
<p>including <code class="command">gcc</code> 7.1 and
<code class="command">clang</code> 4.0.0: for <code class="command">gcc</code> it is implied by
<samp class="option">-fsanitize=address</samp>.</p>
<h5 class="footnote-body-heading"><a id="FOOT137" href="#DOCF137">(137)</a></h5>
<p>for
example, X11/GL libraries on Linux, seen when checking package
<a class="url" href="https://CRAN.R-project.org/package=rgl"><strong class="strong">rgl</strong></a> and some others using it&mdash;a workaround is to set
environment variable <code class="env">RGL_USE_NULL=true</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT138" href="#DOCF138">(138)</a></h5>
<p>On some
platforms the runtime library, <strong class="strong">libubsan</strong>, needs to be installed
separately.</p>
<h5 class="footnote-body-heading"><a id="FOOT139" href="#DOCF139">(139)</a></h5>
<p>but
works better if inlining and frame pointer optimizations are disabled.</p>
<h5 class="footnote-body-heading"><a id="FOOT140" href="#DOCF140">(140)</a></h5>
<p>By default as a security measure: see
<code class="command">man dyld</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT141" href="#DOCF141">(141)</a></h5>
<p>See
<a class="uref" href="https://svn.r-project.org/R-dev-web/trunk/CRAN/QA/Simon/R-build/fixpathR">https://svn.r-project.org/R-dev-web/trunk/CRAN/QA/Simon/R-build/fixpathR</a>:
&lsquo;<samp class="samp">@executable_path</samp>&rsquo; could be used rather than absolute paths.</p>
<h5 class="footnote-body-heading"><a id="FOOT142" href="#DOCF142">(142)</a></h5>
<p>possibly after some platform-specific
translation, e.g. adding leading or trailing underscores.</p>
<h5 class="footnote-body-heading"><a id="FOOT143" href="#DOCF143">(143)</a></h5>
<p>This is currently included by
<samp class="file">R.h</samp> but may not be in future, so it should be included by code
needing the type.</p>
<h5 class="footnote-body-heading"><a id="FOOT144" href="#DOCF144">(144)</a></h5>
<p>Note that this is then not checked for over-runs by
option <code class="code">CBoundsCheck = TRUE</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT145" href="#DOCF145">(145)</a></h5>
<p>Strictly this is OS-specific, but no exceptions have
been seen for many years.</p>
<h5 class="footnote-body-heading"><a id="FOOT146" href="#DOCF146">(146)</a></h5>
<p>For calls from within a namespace the search is confined to
the DLL loaded for that package.</p>
<h5 class="footnote-body-heading"><a id="FOOT147" href="#DOCF147">(147)</a></h5>
<p>For unregistered entry points the OS&rsquo;s <code class="code">dlsym</code>
routine is used to find addresses.  Its performance varies considerably
by OS and even in the best case it will need to search a much larger
symbol table than, say, the table of <code class="code">.Call</code> entry points.</p>
<h5 class="footnote-body-heading"><a id="FOOT148" href="#DOCF148">(148)</a></h5>
<p>Because it is a standard
package, one would need to rename it before attempting to reproduce the
account here.</p>
<h5 class="footnote-body-heading"><a id="FOOT149" href="#DOCF149">(149)</a></h5>
<p>whether or not &lsquo;<samp class="samp">LinkingTo</samp>&rsquo; is used.</p>
<h5 class="footnote-body-heading"><a id="FOOT150" href="#DOCF150">(150)</a></h5>
<p>so there needs to be a corresponding <code class="code">import</code> or
<code class="code">importFrom</code> entry in the <samp class="file">NAMESPACE</samp> file.</p>
<h5 class="footnote-body-heading"><a id="FOOT151" href="#DOCF151">(151)</a></h5>
<p>Even including C system headers in
such a block has caused compilation errors.</p>
<h5 class="footnote-body-heading"><a id="FOOT152" href="#DOCF152">(152)</a></h5>
<p><a class="uref" href="https://en.wikipedia.org/wiki/Application_binary_interface">https://en.wikipedia.org/wiki/Application_binary_interface</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT153" href="#DOCF153">(153)</a></h5>
<p>For
example, &lsquo;<samp class="samp">_GLIBCXX_USE_CXX11_ABI</samp>&rsquo; in <code class="command">g++</code> 5.1 and later:
<a class="uref" href="https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_dual_abi.html">https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_dual_abi.html</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT154" href="#DOCF154">(154)</a></h5>
<p><code class="command">dyld</code> on macOS,
and <code class="env">DYLD_LIBRARY_PATHS</code> below.</p>
<h5 class="footnote-body-heading"><a id="FOOT155" href="#DOCF155">(155)</a></h5>
<p>That is,
similar to those defined in S version 4 from the 1990s: these are
not kept up to date and are not recommended for new projects.</p>
<h5 class="footnote-body-heading"><a id="FOOT156" href="#DOCF156">(156)</a></h5>
<p>see <a class="pxref" href="#The-R-API">The R <abbr class="acronym">API</abbr>: entry points for C code</a>: note that these are not all part of
the API.</p>
<h5 class="footnote-body-heading"><a id="FOOT157" href="#DOCF157">(157)</a></h5>
<p>SEXP is an acronym for <em class="emph">S</em>imple
<em class="emph">EXP</em>ression, common in LISP-like language syntaxes.</p>
<h5 class="footnote-body-heading"><a id="FOOT158" href="#DOCF158">(158)</a></h5>
<p>If no coercion was required, <code class="code">coerceVector</code> would
have passed the old object through unchanged.</p>
<h5 class="footnote-body-heading"><a id="FOOT159" href="#DOCF159">(159)</a></h5>
<p>You can assign a <em class="emph">copy</em> of the object in the
environment frame <code class="code">rho</code> using <code class="code">defineVar(symbol,
duplicate(value), rho)</code>).</p>
<h5 class="footnote-body-heading"><a id="FOOT160" href="#DOCF160">(160)</a></h5>
<p>see <a class="pxref" href="#Character-encoding-issues">Character encoding issues</a> for why this
might not be what is required.</p>
<h5 class="footnote-body-heading"><a id="FOOT161" href="#DOCF161">(161)</a></h5>
<p>This is only guaranteed to show the
current interface: it is liable to change.</p>
<h5 class="footnote-body-heading"><a id="FOOT162" href="#DOCF162">(162)</a></h5>
<p>Known problems have been
defining <code class="code">LENGTH</code>, <code class="code">error</code>, <code class="code">length</code>, <code class="code">match</code>,
<code class="code">vector</code> and <code class="code">warning</code>: whether these matter depends on the OS
and toolchain, with many problem reports involving <code class="command">clang++</code>.</p>
<h5 class="footnote-body-heading"><a id="FOOT163" href="#DOCF163">(163)</a></h5>
<p>That was not
the case on Windows prior to R 4.2.0.</p>
<h5 class="footnote-body-heading"><a id="FOOT164" href="#DOCF164">(164)</a></h5>
<p>also part of
C++11.</p>
<h5 class="footnote-body-heading"><a id="FOOT165" href="#DOCF165">(165)</a></h5>
<p>The &lsquo;<samp class="samp">F77_</samp>&rsquo; in the names is historical and
dates back to usage in S.</p>
<h5 class="footnote-body-heading"><a id="FOOT166" href="#DOCF166">(166)</a></h5>
<p>It is an optional C11
extension.</p>
<h5 class="footnote-body-heading"><a id="FOOT167" href="#DOCF167">(167)</a></h5>
<p><a class="uref" href="https://en.wikipedia.org/wiki/Endianness">https://en.wikipedia.org/wiki/Endianness</a>.</p>
<h5 class="footnote-body-heading"><a id="FOOT168" href="#DOCF168">(168)</a></h5>
<p>It is defined by the Intel compilers,
but also hides unsatisfied references and so cannot be used with R.
It was not supported by the <abbr class="abbr">AIX</abbr> nor Solaris compilers.</p>
<h5 class="footnote-body-heading"><a id="FOOT169" href="#DOCF169">(169)</a></h5>
<p>This applies to the
compiler for the default C++ dialect (currently C++11) and not
necessarily to other dialects.</p>
<h5 class="footnote-body-heading"><a id="FOOT170" href="#DOCF170">(170)</a></h5>
<p>In some cases Fortran compilers accept the
flag but do not actually hide their symbols.</p>
<h5 class="footnote-body-heading"><a id="FOOT171" href="#DOCF171">(171)</a></h5>
<p>In the parlance of macOS
this is a <em class="emph">dynamic</em> library, and is the normal way to build R on
that platform.</p>
<h5 class="footnote-body-heading"><a id="FOOT172" href="#DOCF172">(172)</a></h5>
<p>but these
are not part of the automated test procedures and so little tested.</p>
<h5 class="footnote-body-heading"><a id="FOOT173" href="#DOCF173">(173)</a></h5>
<p>At least according to
POSIX 2004 and later.  Earlier standards prescribed <samp class="file">sys/time.h</samp>:
<samp class="file">R_ext/eventloop.h</samp> will include it if <code class="code">HAVE_SYS_TIME_H</code> is
defined.</p>
<h5 class="footnote-body-heading"><a id="FOOT174" href="#DOCF174">(174)</a></h5>
<p>at least on platforms where the values are
available, that is having <code class="code">getrlimit</code> and on Linux or having
<code class="code">sysctl</code> supporting <code class="code">KERN_USRSTACK</code>, including FreeBSD and
macOS.</p>
<h5 class="footnote-body-heading"><a id="FOOT175" href="#DOCF175">(175)</a></h5>
<p>An
attempt to use only threads in the late 1990s failed to work correctly
under Windows 95, the predominant version of Windows at that time.</p>
</div>



</body>
</html>