Guide to R Extensions and Packages
Guide to R Extensions and Packages
Table of Contents
Acknowledgements
1 Creating R packages
o 1.1 Package structure
1.1.1 The DESCRIPTION file
1.1.2 Licensing
1.1.3 Package Dependencies
[Link] Suggested packages
1.1.4 The INDEX file
1.1.5 Package subdirectories
1.1.6 Data in packages
1.1.7 Non-R scripts in packages
1.1.8 Specifying URLs
o 1.2 Configure and cleanup
1.2.1 Using Makevars
[Link] OpenMP support
[Link] Using pthreads
[Link] Compiling in sub-directories
1.2.2 Configure example
1.2.3 Using F9x code
1.2.4 Using C++ code
1.2.5 C standards
1.2.6 Using cmake
o 1.3 Checking and building packages
1.3.1 Checking packages
1.3.2 Building package tarballs
1.3.3 Building binary packages
o 1.4 Writing package vignettes
1.4.1 Encodings and vignettes
1.4.2 Non-Sweave vignettes
o 1.5 Package namespaces
1.5.1 Specifying imports and exports
1.5.2 Registering S3 methods
1.5.3 Load hooks
1.5.4 useDynLib
1.5.5 An example
1.5.6 Namespaces with S4 classes and methods
o 1.6 Writing portable packages
1.6.1 PDF size
1.6.2 Check timing
1.6.3 Encoding issues
1.6.4 Portable C and C++ code
[Link] Common symbols
[Link] C++17 issues
1.6.5 Binary distribution
o 1.7 Diagnostic messages
o 1.8 Internationalization
1.8.1 C-level messages
1.8.2 R messages
1.8.3 Preparing translations
o 1.9 CITATION files
o 1.10 Package types
1.10.1 Frontend
o 1.11 Services
2 Writing R documentation files
o 2.1 Rd format
2.1.1 Documenting functions
2.1.2 Documenting data sets
2.1.3 Documenting S4 classes and methods
2.1.4 Documenting packages
o 2.2 Sectioning
o 2.3 Marking text
o 2.4 Lists and tables
o 2.5 Cross-references
o 2.6 Mathematics
o 2.7 Figures
o 2.8 Insertions
o 2.9 Indices
o 2.10 Platform-specific documentation
o 2.11 Conditional text
o 2.12 Dynamic pages
o 2.13 User-defined macros
o 2.14 Encoding
o 2.15 Processing documentation files
o 2.16 Editing Rd files
3 Tidying and profiling R code
o 3.1 Tidying R code
o 3.2 Profiling R code for speed
o 3.3 Profiling R code for memory use
3.3.1 Memory statistics from Rprof
3.3.2 Tracking memory allocations
3.3.3 Tracing copies of an object
o 3.4 Profiling compiled code
3.4.1 Linux
[Link] oprofile and operf
[Link] sprof
3.4.2 macOS
4 Debugging
o 4.1 Browsing
o 4.2 Debugging R code
o 4.3 Checking memory access
4.3.1 Using gctorture
4.3.2 Using valgrind
4.3.3 Using the Address Sanitizer
[Link] Using the Leak Sanitizer
4.3.4 Using the Undefined Behaviour Sanitizer
4.3.5 Other analyses with ‘clang’
4.3.6 Other analyses with ‘gcc’
4.3.7 Using ‘Dr. Memory’
4.3.8 Fortran array bounds checking
o 4.4 Debugging compiled code
4.4.1 Finding entry points in dynamically loaded code
4.4.2 Inspecting R objects when debugging
4.4.3 Debugging on macOS
o 4.5 Using Link-time Optimization
5 System and foreign language interfaces
o 5.1 Operating system access
o 5.2 Interface functions .C and .Fortran
o 5.3 [Link] and [Link]
o 5.4 Registering native routines
5.4.1 Speed considerations
5.4.2 Example: converting a package to use registration
5.4.3 Linking to native routines in other packages
o 5.5 Creating shared objects
o 5.6 Interfacing C++ code
5.6.1 External C++ code
o 5.7 Fortran I/O
o 5.8 Linking to other packages
5.8.1 Unix-alikes
5.8.2 Windows
o 5.9 Handling R objects in C
5.9.1 Handling the effects of garbage collection
5.9.2 Allocating storage
5.9.3 Details of R types
5.9.4 Attributes
5.9.5 Classes
5.9.6 Handling lists
5.9.7 Handling character data
5.9.8 Finding and setting variables
5.9.9 Some convenience functions
[Link] Semi-internal convenience functions
5.9.10 Named objects and copying
o 5.10 Interface functions .Call and .External
5.10.1 Calling .Call
5.10.2 Calling .External
5.10.3 Missing and special values
o 5.11 Evaluating R expressions from C
5.11.1 Zero-finding
5.11.2 Calculating numerical derivatives
o 5.12 Parsing R code from C
5.12.1 Accessing source references
o 5.13 External pointers and weak references
5.13.1 An example
o 5.14 Vector accessor functions
o 5.15 Character encoding issues
6 The R API: entry points for C code
o 6.1 Memory allocation
6.1.1 Transient storage allocation
6.1.2 User-controlled memory
o 6.2 Error signaling
6.2.1 Error signaling from Fortran
o 6.3 Random number generation
o 6.4 Missing and IEEE special values
o 6.5 Printing
6.5.1 Printing from Fortran
o 6.6 Calling C from Fortran and vice versa
6.6.1 Fortran character strings
6.6.2 Fortran LOGICAL
6.6.3 Passing functions
o 6.7 Numerical analysis subroutines
6.7.1 Distribution functions
6.7.2 Mathematical functions
6.7.3 Numerical Utilities
6.7.4 Mathematical constants
o 6.8 Optimization
o 6.9 Integration
o 6.10 Utility functions
o 6.11 Re-encoding
o 6.12 Condition handling and cleanup code
o 6.13 Allowing interrupts
o 6.14 Platform and version information
o 6.15 Inlining C functions
o 6.16 Controlling visibility
o 6.17 Using these functions in your own C code
o 6.18 Organization of header files
7 Generic functions and methods
o 7.1 Adding new generics
8 Linking GUIs and other front-ends to R
o 8.1 Embedding R under Unix-alikes
8.1.1 Compiling against the R library
8.1.2 Setting R callbacks
8.1.3 Registering symbols
8.1.4 Meshing event loops
8.1.5 Threading issues
o 8.2 Embedding R under Windows
8.2.1 Using (D)COM
8.2.2 Calling [Link] directly
8.2.3 Finding R_HOME
Function and variable index
Concept index
Acknowledgements
The contributions to early versions of this manual by Saikat DebRoy (who wrote
the first draft of a guide to using .Call and .External) and Adrian Trapletti (who
provided information on the C++ interface) are gratefully acknowledged.
1 Creating R packages
Packages provide a mechanism for loading optional code, data and documentation
as needed. The R distribution itself includes about 30 packages.
In the following, we assume that you know the library() command, including
its [Link] argument, and we also assume basic knowledge of the R CMD
INSTALL utility. Otherwise, please look at R’s help pages on
?library
?INSTALL
before reading on.
For packages which contain code to be compiled, a computing environment
including a number of tools is assumed; the “R Installation and Administration”
manual describes what is needed for each OS.
Once a source package is created, it must be installed by the command R CMD
INSTALL. See Add-on-packages in R Installation and Administration.
Other types of extensions are supported (but rare): See Package types.
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.
A package is a directory of files which extend R, a source package (the master
files of a package), or a tarball containing the files of a source package, or
an installed package, the result of running R CMD INSTALL on a source package. On
some platforms (notably macOS and Windows) there are also binary packages, a
zip file or tarball containing the files of an installed package which can be
unpacked rather than installing from sources.
A package is not1 a library. The latter is used in two senses in R documentation.
A directory into which packages are installed,
e.g. /usr/lib/R/library: in that sense it is sometimes referred to as
a library directory or library tree (since the library is a directory which
contains packages as directories, which themselves contain directories).
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 ‘library’.
Installed packages may contain compiled code in what is known on Unix-
alikes as a shared object and on Windows as a DLL. The concept of
a shared library (dynamic library 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 .so) and dynamic libraries (extension .dylib).
There are a number of well-defined operations on source packages.
The most common is installation which takes a source package and installs
it in a library using R CMD INSTALL or [Link].
Source packages can be built. This involves taking a source directory and
creating a tarball ready for distribution, including cleaning it up and creating
PDF/HTML documentation from any vignettes it may contain. Source
packages (and most often tarballs) can be checked, 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.
Compilation 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 ‘byte’ compiling the R code in a package
(using the facilities of package compiler): nowadays this is enabled by
default for all packages. So compiling a package may come to mean byte-
compiling its R code.
It used to be unambiguous to talk about loading an installed package
using library(), but since the advent of package namespaces this has been
less clear: people now often talk about loading the package’s namespace and
then attaching the package so it becomes visible on the search path.
Function library performs both steps, but a package’s namespace can be
loaded without the package being attached (for example by calls
like splines::ns).
The concept of lazy loading 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 R 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 Lazy loading in R Internals.)
CRAN 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 CRAN: current instructions are linked
from [Link]
Package structure
Configure and cleanup
Checking and building packages
Writing package vignettes
Package namespaces
Writing portable packages
Diagnostic messages
Internationalization
CITATION files
Package types
Services
The DESCRIPTION file contains basic information about the package in the
following format:
Package: pkgname
Version: 0.5-1
Date: 2015-01-01
Title: My First Collection of Functions
Authors@R: c(person("Joe", "Developer", role = c("aut", "cre"),
email = "[Link]@[Link]"),
person("Pat", "Developer", role = "aut"),
person("A.", "User", role = "ctb",
email = "[Link]@[Link]"))
Author: Joe Developer [aut, cre],
Pat Developer [aut],
A. User [ctb]
Maintainer: Joe Developer <[Link]@[Link]>
Depends: R (>= 3.1.0), nlme
Suggests: MASS
Description: A (one paragraph) description of what
the package does and why it may be useful.
License: GPL (>= 2)
URL: [Link] [Link]
BugReports: [Link]
The format is that of a version of a ‘Debian Control File’ (see the help for
‘[Link]’ and [Link]
R does not require encoding in UTF-8 and does not support comments starting
with ‘#’). Fields start with an ASCII 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.
For maximal portability, the DESCRIPTION file should be written entirely
in ASCII — if this is not possible it must contain an ‘Encoding’ field (see
below).
Several optional fields take logical values: these can be specified as ‘yes’,
‘true’, ‘no’ or ‘false’: capitalized values are also accepted.
The ‘Package’, ‘Version’, ‘License’, ‘Description’, ‘Title’,
‘Author’, and ‘Maintainer’ fields are mandatory, all other fields are optional.
Fields ‘Author’ and ‘Maintainer’ can be auto-generated from ‘Authors@R’,
and may be omitted if the latter is provided: however if they are not ASCII we
recommend that they are provided.
The mandatory ‘Package’ field gives the name of the package. This should
contain only (ASCII) 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 ‘Description’ field (and not the ‘Title’ field).
The mandatory ‘Version’ field gives the version of the package. This is a
sequence of at least two (and usually three) non-negative integers separated by
single ‘.’ or ‘-’ characters. The canonical form is as shown in the example, and a
version such as ‘0.01’ or ‘0.01.0’ will be handled as if it were ‘0.1-0’. It
is not a decimal number, so for example 0.9 < 0.75 since 9 < 75.
The mandatory ‘License’ field is discussed in the next subsection.
The mandatory ‘Title’ field should give a short description of the package.
Some package listings may truncate the title to 65 characters. It should use title
case (that is, use capitals for the principal words: tools::toTitleCase can help you
with this), not use any markup, not have any continuation lines, and not end in a
period (unless part of …). 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.
The mandatory ‘Description’ field should give a comprehensive 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 CRAN package to all CRAN users). It is good practice not to start with the
package name, ‘This package’ or similar. As with the ‘Title’ 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.
‘<[Link] see also Specifying URLs.
The mandatory ‘Author’ field describes who wrote the package. 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
‘Authors@R’). Note that all significant contributors must be included: if you
wrote an R wrapper for the work of others included in the src directory, you are
not the sole (and maybe not even the main) author.
The mandatory ‘Maintainer’ field should give a single name followed by
a valid (RFC 2822) email address in angle brackets. It should not end in a period or
comma. This field is what is reported by the maintainer function and used
by [Link]. For a CRAN package it should be a person, 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.
Note that the display name (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.)
Both ‘Author’ and ‘Maintainer’ fields can be omitted if a suitable
‘Authors@R’ field is given. This field can be used to provide a refined and
machine-readable description of the package “authors” (in particular specifying
their precise roles), via suitable R code. It should create an object of
class "person", by either a call to person or a series of calls (one per “author”)
concatenated by c(): see the example DESCRIPTION file above. The roles can
include ‘"aut"’ (author) for full authors, ‘"cre"’ (creator) for the package
maintainer, and ‘"ctb"’ (contributor) for other contributors, ‘"cph"’ (copyright
holder, which should be the legal name for an institution or corporate body),
among others. See ?person for more information. Note that no role is assumed by
default. Auto-generated package citation information takes advantage of this
specification. The ‘Author’ and ‘Maintainer’ fields are auto-generated from it
if needed when building5 or installing.
An optional ‘Copyright’ 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 inst/COPYRIGHTS.
The optional ‘Date’ field gives the release date of the current version of the
package. It is strongly recommended6 to use the ‘yyyy-mm-dd’ format
conforming to the ISO 8601 standard.
The ‘Depends’, ‘Imports’, ‘Suggests’, ‘Enhances’, ‘LinkingTo’ and
‘Additional_repositories’ fields are discussed in a later subsection.
Dependencies external to the R system should be listed in the
‘SystemRequirements’ field, possibly amplified in a separate README file.
This includes specifying a non-default C++ standard and the need for GNU make.
The ‘URL’ field may give a list of URLs 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 URLs are converted to active hyperlinks
in CRAN package listings. See Specifying URLs.
The ‘BugReports’ field may contain a single URL to which bug reports about
the package should be submitted. This URL will be used by [Link] instead of
sending an email to the maintainer. A browser is opened for a ‘[Link] or
‘[Link] URL. To specify another email address for bug reports, use
‘Contact’ instead: however [Link] will try to extract an email address
(preferably from a ‘[Link] URL or enclosed in angle brackets) from
‘BugReports’.
Base and recommended packages (i.e., packages contained in the R source
distribution or available from CRAN and recommended to be included in every
binary distribution of R) have a ‘Priority’ field with value ‘base’ or
‘recommended’, respectively. These priorities must not be used by other
packages.
A ‘Collate’ 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 ‘C’ locale. If present, the collate specification must
list all R code files in the package (taking possible OS-specific subdirectories into
account, see Package subdirectories) as a whitespace separated list of file paths
relative to the R subdirectory. Paths containing white space or quotes need to be
quoted. An OS-specific collation field (‘[Link]’ or
‘[Link]’) will be used in preference to ‘Collate’.
The ‘LazyData’ logical field controls whether the R datasets use lazy-loading. A
‘LazyLoad’ field was used in versions prior to 2.14.0, but now is ignored.
The ‘KeepSource’ logical field controls if the package code is sourced
using [Link] = TRUE or FALSE: it might be needed exceptionally for a package
designed to always be used with [Link] = TRUE.
The ‘ByteCompile’ 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 --no-byte-compile.
The ‘UseLTO’ logical field is used to indicate if source code in the package7 is to
be compiled with Link-Time Optimization (see Using Link-time Optimization) if
R was installed with --enable-lto (default true) or --enable-
lto=R (default false) (or on Windows if LTO_OPT is set in MkRules). This can be
overridden by the flags --use-LTO and --no-use-LTO. LTO is said to give
most size and performance improvements for large and complex (heavily
templated) C++ projects.
The ‘StagedInstall’ logical field controls if package installation is ‘staged’,
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.
The ‘ZipData’ logical field has been ignored since R 2.13.0.
The ‘Biarch’ logical field is used on Windows to select the INSTALL option --
force-biarch for this package.
The ‘BuildVignettes’ logical field can be set to a false value to stop R CMD
8
build from attempting to build the vignettes, as well as preventing R CMD
check 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).
The ‘VignetteBuilder’ 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 ‘Depends’, ‘Suggests’ or ‘Imports’. The utils package is
always implicitly appended. See Non-Sweave vignettes for details. Note that if, for
example, a vignette has engine ‘knitr::rmarkdown’, then knitr provides the
engine but both knitr and rmarkdown are needed for using it, so both these
packages need to be in the ‘VignetteBuilder’ field and at least suggested
(as rmarkdown is only suggested by knitr, and hence not available automatically
along with it). Many packages using knitr also need the package formatR which it
suggests and so the user package needs to do so too and include this in
‘VignetteBuilder’.
If the DESCRIPTION file is not entirely in ASCII it should contain an
‘Encoding’ field specifying an encoding. This is used as the encoding of
the DESCRIPTION file itself and of the R and NAMESPACE files, and as the
default encoding of .Rd files. The examples are assumed to be in this encoding
when running R CMD check, and it is used for the encoding of the CITATION file.
Only encoding names latin1, latin2 and UTF-8 are known to be portable. (Do not
specify an encoding unless one is actually needed: doing so makes the
package less portable. If a package has a specified encoding, you should run R CMD
build etc in a locale using that encoding.)
Next: The INDEX file, Previous: Licensing, Up: Package structure [Contents]
[Index]
1.1.3 Package Dependencies
The ‘Depends’ field gives a comma-separated list of package names which this
package depends on. Those packages will be attached before the current package
when library or require 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.
‘MASS (>= 3.1-20)’.
The ‘Depends’ field can also specify a dependence on a certain version of R —
e.g., if the package works only with R version 4.0.0 or later, include ‘R (>=
4.0)’ in the ‘Depends’ 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. ‘R (>= 2.14.0), R (>= r56550)’ requires a
version later than R-devel of late July 2011 (including released versions of 2.14.0).
It makes no sense to declare a dependence on R without a version specification, nor
on the package base: this is an R package and package base is always available.
A package or ‘R’ can appear more than once in the ‘Depends’ field, for example
to give upper and lower bounds on acceptable versions.
It is inadvisable to use a dependence on R with patchlevel (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.
Both library and the R package checking facilities use this field: hence it is an
error to use improper syntax or misuse the ‘Depends’ field for comments on
other software that might be needed. The R INSTALL 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.
The ‘Imports’ field lists packages whose namespaces are imported from (as
specified in the NAMESPACE file) but which do not need to be attached.
Namespaces accessed by the ‘::’ and ‘:::’ operators must be listed here, or in
‘Suggests’ or ‘Enhances’ (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 DESCRIPTION file is used to decide
which packages to re-install when this happens). Packages declared in the
‘Depends’ field should not also be in the ‘Imports’ field. Version requirements
can be specified and are checked when the namespace is loaded.
The ‘Suggests’ field uses the same syntax as ‘Depends’ and lists packages that
are not necessarily needed. This includes packages used only in examples, tests or
vignettes (see Writing package vignettes), and packages loaded in the body of
functions. E.g., suppose an example12 from package foo uses a dataset from
package bar. Then it is not necessary to have bar use foo unless one wants to
execute all the examples/tests/vignettes: it is useful to have bar, but not necessary.
Version requirements can be specified but should be checked by the code which
uses the package.
Finally, the ‘Enhances’ field lists packages “enhanced” 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 ‘Enhances: chron’
because they can handle datetime objects from chron even though they prefer R’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 ‘Suggests’ and not
‘Enhances’.)
The general rules are
A package should be listed in only one of these fields.
Packages whose namespace only is needed to load the package
using library(pkgname) should be listed in the ‘Imports’ field and not in
the ‘Depends’ field. Packages listed in import or importFrom directives in
the NAMESPACE file should almost always be in ‘Imports’ and not
‘Depends’.
Packages that need to be attached to successfully load the package
using library(pkgname) must be listed in the ‘Depends’ field.
All packages that are needed13 to successfully run R CMD check on the
package must be listed in one of ‘Depends’ or ‘Suggests’ or
‘Imports’. Packages used to run examples or tests conditionally
(e.g. via if(require(pkgname))) should be listed in ‘Suggests’ or
‘Enhances’. (This allows checkers to ensure that all the packages needed
for a complete check are installed.)
Packages needed to use datasets from the package should be in ‘Imports’:
this includes those needed to define S4 classes used.
In particular, packages providing “only” data for examples or vignettes should be
listed in ‘Suggests’ rather than ‘Depends’ in order to make lean installations
possible.
Version dependencies in the ‘Depends’ and ‘Imports’ fields are used
by library when it loads the package, and [Link] checks versions for
the ‘Depends’, ‘Imports’ and (for dependencies = TRUE) ‘Suggests’ fields.
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.
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.
Field ‘Depends’ 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 latticeExtra would want the functions of package lattice made available.
Almost always packages mentioned in ‘Depends’ should also be imported from
in the NAMESPACE file: this ensures that any needed parts of those packages are
available when some other package imports the current package.
The ‘Imports’ field should not contain packages which are not imported from
(via the NAMESPACE file or :: or ::: operators), as all the packages listed in that
field need to be installed for the current package to be installed. (This is checked
by R CMD check.)
R code in the package should call library or require only exceptionally. Such
calls are never needed for packages listed in ‘Depends’ as they will already be on
the search path. It used to be common practice to use require calls for packages
listed in ‘Suggests’ in functions which used their functionality, but nowadays it
is better to access such functionality via :: calls.
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
‘LinkingTo’ in the DESCRIPTION file. For example
LinkingTo: link1, link2
The ‘LinkingTo’ field can have a version requirement which is checked at
installation.
Specifying a package in ‘LinkingTo’ 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 ‘Depends’ or ‘Imports’
fields. This includes CRAN package BH and almost all users
of RcppArmadillo and RcppEigen. Note that ‘LinkingTo’ 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 ‘Suggests’ or perhaps
‘Depends’.
For another use of ‘LinkingTo’ see Linking to native routines in other packages.
The ‘Additional_repositories’ 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 R CMD check to check that the packages can be found, at least as
source packages (which can be installed on any platform).
Suggested packages
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 via if(require("pkgname")): this is OK if that conditioning is done in
examples/tests/vignettes, although using if(requireNamespace("pkgname")) is
preferred, if possible.
However, using require for conditioning in package code 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 require or library calls. It is better practice to
use code like
if (requireNamespace("rgl", quietly = TRUE)) {
rgl::plot3d(...)
} else {
## do something else not involving rgl.
}
Note the use of rgl:: as that object would not necessarily be visible (and if it is, it
need not be the one from that namespace: plot3d occurs in several other packages).
If the intention is to give an error if the suggested package is not available, simply
use e.g. rgl::plot3d.
If the conditional code produces print output, function withAutoprint can be
useful.
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 testthat which in version 1.0.0 contained illegal C++ code and hence could
not be installed on standards-compliant platforms.
Some people have assumed that a ‘recommended’ package in ‘Suggests’ can
safely be used unconditionally, but this is not so. (R can be installed without
recommended packages, and which packages are ‘recommended’ may change.)
As noted above, packages in ‘Enhances’ must be used conditionally and hence
objects within them should always be accessed via ::.
On most systems, R CMD check can be run with only those packages declared in
‘Depends’ and ‘Imports’ by setting environment
variable _R_CHECK_DEPENDS_ONLY_=true, whereas
setting _R_CHECK_SUGGESTS_ONLY_=true also allows suggested packages, but not
those in ‘Enhances’ nor those not mentioned in the DESCRIPTION file. It is
recommended that a package is checked with each of these set, as well as with
neither.
WARNING: Be extremely careful if you do things which would be run at
installation time depending on whether suggested packages are available or not—
this includes top-level code in R code files, .onLoad 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.
The optional file INDEX 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 tools::Rdindex()) when installing from source.
The file is part of the information given by library(help = pkgname).
Rather than editing this file, it is preferable to put customized information about
the package into an overview help page (see Documenting packages) and/or a
vignette (see Writing package vignettes).
Next: Data in packages, Previous: The INDEX file, Up: Package structure
[Contents][Index]
1.1.5 Package subdirectories
The R subdirectory contains R code files, only. The code files to be installed must
start with an ASCII (lower or upper case) letter or digit and have one of the
extensions14 .R, .S, .q, .r, or .s. We recommend using .R, as this extension
seems to be not used by any other software. It should be possible to read in the
files using source(), 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 require and options. If computations
are required to create objects these can use code ‘earlier’ in the package (see the
‘Collate’ field) plus functions in the ‘Depends’ packages provided that the
objects created do not depend on those packages except via namespace imports.
Extreme care is needed if top-level computations are made to depend on
availability or not of other packages. In particular this applies
to setMethods and setClass calls. Nor should they depend on the availability of
external resources such as downloads.
Two exceptions are allowed: if the R subdirectory contains a
file [Link] (a saved image of one or more R objects: please use suitable
compression as suggested by tools::resaveRdaFiles, and see also the
‘SysDataCompression’ DESCRIPTION field.) this will be lazy-loaded into
the namespace environment – this is intended for system datasets that are not
intended to be user-accessible via data. Also, files ending in ‘.in’ will be allowed
in the R directory to allow a configure script to generate suitable files.
Only ASCII characters (and the control characters tab, formfeed, LF and CR)
should be used in code files. Other characters are accepted in comments15, but then
the comments may not be readable in e.g. a UTF-8 locale. Non-ASCII characters
in object names will normally16 fail when the package is installed. Any byte will be
allowed in a quoted character string but ‘\uxxxx’ escapes should be used for non-
ASCII characters. However, non-ASCII character strings may not be usable in
some locales and may display incorrectly in others.
Various R functions in a package can be used to initialize and clean up. See Load
hooks.
The man subdirectory should contain (only) documentation files for the objects in
the package in R documentation (Rd) format. The documentation filenames must
start with an ASCII (lower or upper case) letter or digit and have the
extension .Rd (the default) or .rd. Further, the names must be valid in
‘[Link] URLs, which means17 they must be entirely ASCII and not contain
‘%’. See Writing R documentation files, for more information. Note that all user-
level objects in a package should be documented; if a package pkg contains user-
level objects which are for “internal” use only, it should provide a file pkg-
[Link] 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 grid 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 Package namespaces).
Having a man directory containing no documentation files may give an installation
error.
The man subdirectory may contain a subdirectory named macros; this will
contain source for user-defined Rd macros. (See User-defined macros.) These use
the Rd format, but may not contain anything but macro definitions, comments and
whitespace.
The R and man subdirectories may contain OS-specific subdirectories
named unix or windows.
The sources and headers for the compiled code are in src, plus optionally a
file Makevars or Makefile (or for use on Windows, with
extension .win or .ucrt). When a package is installed using R CMD
INSTALL, make is used to control compilation and linking into a shared object for
loading into R. There are default make variables and rules for this (determined
when R is configured and recorded in R_HOME/etcR_ARCH/Makeconf),
providing support for C, C++, fixed- or free-form Fortran, Objective C and
Objective C++18 with associated
extensions .c, .cc or .cpp, .f, .f90 or .f95, .m, and .mm, respectively. We
recommend using .h for headers, also for C++19 or Fortran 9x include files. (Use
of extension .C for C++ is no longer supported.) Files in the src directory should
not be hidden (start with a dot), and hidden files will under some versions of R be
ignored.
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’s native compilers.
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) ‘_WIN32’ will be
defined: on 64-bit Windows builds also ‘_WIN64’. On macOS ‘__APPLE__’ is
defined20; for an ‘Apple Silicon’ platform, test for both ‘__APPLE__’ and
‘__arm64__’.
The default rules can be tweaked by setting macros21 in a
file src/Makevars (see Using Makevars). Note that this mechanism should
be general enough to eliminate the need for a package-specific src/Makefile.
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 ‘all’ and a (possibly empty) target ‘clean’ which
removes all files generated by running make (to be used by ‘R CMD INSTALL
--clean’ and ‘R CMD INSTALL --preclean’). There are platform-specific
file names on Windows: src/[Link] takes precedence
over src/Makevars and src/[Link] must be used. Since R
4.2.0, src/[Link] takes precedence
over src/[Link] and src/[Link] takes precedence
over src/[Link]. src/[Link] and src/[Link]
rt will be ignored by earlier versions of R, and hence can be used to provide
content specific to UCRT or Rtools42 and newer, but the support for .ucrt 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 .win. Some make programs require makefiles to have a complete final line,
including a newline.
A few packages use the src directory for purposes other than making a shared
object (e.g. to create executables). Such packages should have
files src/Makefile and src/[Link] or src/[Link] (u
nless intended for only Unix-alikes or only Windows). Note that on Unix such
makefiles are included after R_HOME/etc/R_ARCH/Makeconf so all the usual
R macros and make rules are available – 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.
The order of inclusion of makefiles for a package which does not have
a src/Makefile file is
Unix-alike Windows
src/Makevars src/[Link], src/[Link]
R_HOME/etc/R_ARCH/
R_HOME/etc/R_ARCH/Makeconf
Makeconf
R_MAKEVARS_SITE, R_HOME/ R_MAKEVARS_SITE, R_HOME/etc/R_ARCH/
etc/R_ARCH/[Link] [Link]
R_HOME/share/make/
R_HOME/share/make/[Link]
[Link]
R_MAKEVARS_USER, ~/.R/
R_MAKEVARS_USER,
~/.R/[Link], ~/.R/
Makevars-platform, ~/.R/
Makevars.win64, ~/.R/[Link]
Makevars
For those which do, it is
R_HOME/etc/R_ARCH/
R_HOME/etc/R_ARCH/Makeconf
Makeconf
R_MAKEVARS_SITE, R_HOME/ R_MAKEVARS_SITE, R_HOME/etc/R_ARCH/
etc/R_ARCH/[Link] [Link]
src/Makefile src/[Link], src/[Link]
R_MAKEVARS_USER, ~/.R/ R_MAKEVARS_USER, ~/.R/[Link], ~/.R/
Makevars-platform, ~/.R/ Makevars.win64, ~/.R/[Link]
Makevars
Items in capitals are environment variables: those separated by commas are
alternatives looked for in the order shown.
In very special cases packages may create binary files other than the shared
objects/DLLs in the src directory. Such files will not be installed in a multi-
architecture setting since R CMD INSTALL --libs-only 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 src/[Link].R which will be run as part of the installation in
the src build directory instead of copying the shared objects/DLLs. The script is
run in a separate R environment containing the following
variables: R_PACKAGE_NAME (the name of the package), R_PACKAGE_SOURCE (the path to
the source directory of the package), R_PACKAGE_DIR (the path of the target
installation directory of the package), R_ARCH (the arch-dependent part of the path,
often empty), SHLIB_EXT (the extension of shared objects) and WINDOWS (TRUE on
Windows, FALSE elsewhere). Something close to the default behavior could be
replicated with the following src/[Link].R file:
files <- [Link](paste0("*", SHLIB_EXT))
dest <- [Link](R_PACKAGE_DIR, paste0('libs', R_ARCH))
[Link](dest, recursive = TRUE, showWarnings = FALSE)
[Link](files, dest, overwrite = TRUE)
if([Link]("[Link]"))
[Link]("[Link]", dest, overwrite = TRUE)
On the other hand, executable programs could be installed along the lines of
execs <- c("one", "two", "three")
if(WINDOWS) execs <- paste0(execs, ".exe")
if ( any([Link](execs)) ) {
dest <- [Link](R_PACKAGE_DIR, paste0('bin', R_ARCH))
[Link](dest, recursive = TRUE, showWarnings = FALSE)
[Link](execs, dest, overwrite = TRUE)
}
Note the use of architecture-specific subdirectories of bin where needed.
(Executables should installed under a bin directory and not under libs. It is
good practice to check that they can be executed as part of the installation script, so
a broken package is not installed.)
The data subdirectory is for data files: See Data in packages.
The demo subdirectory is for R scripts (for running via demo()) 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 tests directory to
achieve this. The script files must start with a (lower or upper case) letter and have
one of the extensions .R or .r. If present, the demo subdirectory should also have
a 00Index 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 ASCII file (see Encoding issues). Function demo() will use the package
encoding if there is one, but this is mainly useful for non-ASCII comments.
The contents of the inst subdirectory will be copied recursively to the installation
directory. Subdirectories of inst should not interfere with those used by R
(currently, R, data, demo, exec, libs, man, help, html and Meta, and
earlier versions used latex, R-ex). The copying of the inst happens
after src is built so its Makefile can create files to be installed. To exclude files
from being installed, one can specify a list of exclude patterns in
file .Rinstignore in the top-level source directory. These patterns should be
Perl-like regular expressions (see the help for regexp in R for the precise details),
one per line, to be matched case-insensitively against the file and directory paths,
e.g. doc/.*[.]png$ will exclude all PNG files in inst/doc based on the
extension.
Note that with the exceptions of INDEX, LICENSE/LICENCE and NEWS,
information files at the top level of the package will not be installed and so not be
known to users of Windows and macOS compiled packages (and not seen by those
who use R CMD INSTALL or [Link]() on the tarball). So any information
files you wish an end user to see should be included in inst. Note that if the
named exceptions also occur in inst, the version in inst will be that seen in the
installed package.
Things you might like to add to inst are a CITATION file for use by
the citation function, and a [Link] file for use by the news function. See its
help page for the specific format restrictions of the [Link] file.
Another file sometimes needed in inst is AUTHORS or COPYRIGHTS to specify
the authors or copyright holders when this is too complex to put in
the DESCRIPTION file.
Subdirectory tests 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 .R (or .r as from R 3.4.0) file, or via a .Rin file containing code
which in turn creates the corresponding .R file (e.g., by collecting all function
objects in the package and then calling them with the strangest arguments). The
results of running a .R file are written to a .Rout file. If there is a
corresponding22 .[Link] file, these two are compared, with differences
being reported but not causing an error. The directory tests is copied to the
check area, and the tests are run with the copy as the working directory and
with R_LIBS set to ensure that the copy of the package installed during testing will
be found by library(pkg_name). 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).
If directory tests has a subdirectory Examples containing a file pkg-
[Link], this is compared to the output file for running the examples when
the latter are checked. Reference output should be produced without having the --
timings option set (and note that --as-cran sets it).
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 ‘IGNORE_RDIFF’ 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 zapsmall.
Subdirectory exec 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 exec are installed (and those with names starting with a dot
are ignored), and they are all marked as executable (mode 755, moderated by
‘umask’) on POSIX platforms. Note too that this is not suitable for
executable programs since some platforms (including Windows) support multiple
architectures using the same installed package directory.
Subdirectory po is used for files related to localization: see Internationalization.
Subdirectory tools is the preferred place for auxiliary files needed during
configuration, and also for sources need to re-create scripts (e.g. M4 files
for autoconf: some prefer to put those in a subdirectory m4 of tools).
The data subdirectory is for data files, either to be made available via lazy-
loading or for loading using data(). (The choice is made by the ‘LazyData’ field
in the DESCRIPTION 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 inst/extdata for such files.
Data files can have one of three types as indicated by their extension: plain R code
(.R or .r), tables (.tab, .txt, or .csv, see ?data for the file formats, and note
that .csv is not the standard23 CSV format), or save() images
(.RData or .rda). The files should not be hidden (have names starting with a
dot). Note that R code should be if possible “self-sufficient” 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 search() path by attaching packages or other
environments.
Images (extensions .RData24 or .rda) 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 Depends and Imports 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 str() on all the datasets, and look at the output of loadedNamespaces().
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 Imports or Depends (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 .R form and use that to create the dataset object when needed
(loading package namespaces but not attaching them by
using requireNamespace(pkg, quietly = TRUE) and using pkg:: to refer to objects
in the namespace).
If you are not using ‘LazyData’ and either your data files are large or e.g., you
use data/foo.R scripts to produce your data, loading your namespace, you can
speed up installation by providing a file datalist in the data subdirectory.
This should have one line per topic that data() will find, in the format ‘foo’
if data(foo) provides ‘foo’, or ‘foo: bar bah’ if data(foo) provides ‘bar’
and ‘bah’. R CMD build will automatically add a datalist file
to data directories of over 1Mb, using the function tools::add_datalist.
Tables (.tab, .txt, or .csv files) can be compressed by gzip, bzip2 or xz,
optionally with additional extension .gz, .bz2 or .xz.
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 .rda images prepared by save(,
compress = TRUE) (the default). Using bzip2 or xz 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.
Package tools has a couple of functions to help with data
images: checkRdaFiles reports on the way the image was saved,
and resaveRdaFiles will re-save with a different type of compression, including
choosing the best type for that particular image.
Many packages using ‘LazyData’ will benefit from using a form of compression
other than gzip in the installed lazy-loading database. This can be selected by
the --data-compress option to R CMD INSTALL or by using the
‘LazyDataCompression’ field in the DESCRIPTION file. Useful values
are bzip2, xz and the default, gzip: value none is also accepted. The only way to
discover which is best is to try them all and look at the size of
the pkgname/data/[Link] file. A function to do that (quoting sizes in
KB) is
CheckLazyDataCompression <- function(pkg)
{
pkg_name <- sub("_.*", "", pkg)
lib <- tempfile(); [Link](lib)
zs <- c("gzip", "bzip2", "xz")
res <- integer(3); names(res) <- zs
for (z in zs) {
opts <- c(paste0("--data-compress=", z),
"--no-libs", "--no-help", "--no-demo", "--no-exec", "--
no-test-load")
[Link](pkg, lib, INSTALL_opts = opts, repos = NULL, quiet
= TRUE)
res[z] <- [Link]([Link](lib, pkg_name, "data", "[Link]"))
}
ceiling(res/1024)
}
(applied to a source package without any ‘LazyDataCompression’ field). R
CMD check will warn if it finds a pkgname/data/[Link] file of more than
5MB without ‘LazyDataCompression’ being set. If you see that,
run CheckLazyDataCompression() and set the field – to gzip in the unlikely
event25 that is the best choice.
The analogue for [Link] is field ‘SysDataCompression’: the default
is xz for files bigger than 1MB otherwise gzip.
Lazy-loading is not supported for very large datasets (those which when serialized
exceed 2GB, the limit for the format on 32-bit platforms).
Next: Checking and building packages, Previous: Package structure, Up: Creating
R packages [Contents][Index]
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 not safe to just use pkg-config --
static --libs, as that will often include further libraries that are not necessarily
installed on the user’s system (or maybe only the versioned library such
as [Link].2.1 is installed and not [Link] which would be needed
to use -ljbig sometimes included in pkg-config --static --libs libtiff-4).
Another issue is that pkg-config --exists may not be reliable. It checks not only
that the ‘module’ is available but all of the dependencies, including those in
principle needed for static linking. (XQuartz 2.8.x only distributed dynamic
libraries and not some of the .pc files needed for --exists.)
Sometimes the name by which the software is known to pkg-config is not what one
might expect (e.g. ‘libxml-2.0’ even for 2.9.x). To get a complete list use
pkg-config --list-all | sort
Some external software provides a -config command to do a similar job to pkg-
config, including
curl-config freetype-config gdal-config geos-config
gsl-config iodbc-config libpng-config nc-config
pcre-config pcre2-config xml2-config xslt-config
(curl-config is for libcurl not curl. nc-config is for netcdf.) Most have an option
to use static libraries.
N.B. 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.)
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 R CMD check --
32
as-cran). This will include the file [Link] in the top-level directory of
the package. If extensions written in m4 are needed, these should be included under
the directory tools and included from [Link] via e.g.,
m4_include([tools/ax_pthread.m4])
Alternatively, Autoconf can be asked to search all .m4 files in a directory by
including something like33
AC_CONFIG_MACRO_DIR([tools/m4])
One source of such extensions is the ‘Autoconf Archive’
([Link] It is not safe to assume this is
installed on users’ machines, so the extension should be shipped with the package
(taking care to comply with its licence).
Using Makevars
Configure example
Using F9x code
Using C++ code
C standards
Using cmake
Next: Configure example, Previous: Configure and cleanup, Up: Configure and
cleanup [Contents][Index]
1.2.1 Using Makevars
all: $(SHLIB)
slamc.o: slamc.f
$(FC) $(SLAMC_FFLAGS) -c -o slamc.o slamc.f
needed to ensure that the LAPACK routines find some constants without infinite
looping. The Windows equivalent was
all: $(SHLIB)
slamc.o: slamc.f
$(FC) $(SAFE_FFLAGS) -c -o slamc.o slamc.f
(since the other macros are all empty on that platform, and R’s internal BLAS was
not used). Note that the first target in Makevars will be called, but for back-
compatibility it is best named all.
If you want to create and then link to a library, say using code in a subdirectory,
use something like
.PHONY: all mylibs
all: $(SHLIB)
$(SHLIB): mylibs
mylibs:
(cd subdir; $(MAKE))
Be careful to create all the necessary dependencies, as there is no guarantee that the
dependencies of all will be run in a particular order (and some of the CRAN build
machines use multiple CPUs and parallel makes). In particular,
all: mylibs
does not suffice. GNU make does allow the construct
.NOTPARALLEL: all
all: mylibs $(SHLIB)
but that is not portable. dmake and pmake allow the similar .NO_PARALLEL, also not
portable: some variants of pmake accept .NOTPARALLEL as an alias for .NO_PARALLEL.
Note that on Windows it is required that Makevars[.win, .ucrt] 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 src directory for some purpose other than
building a DLL, use a [Link] or [Link] file.
It is sometimes useful to have a target ‘clean’
in Makevars, [Link] or [Link]: this will be used by R
CMD build to clean up (a copy of) the package sources. When it is run by build it
will have fewer macros set, in particular not $(SHLIB), nor $(OBJECTS) unless set in
the file itself. It would also be possible to add tasks to the target ‘shlib-clean’
which is run by R CMD INSTALL and R CMD SHLIB with options --clean and --
preclean.
An unfortunately common error is to have
all: $(SHLIB) clean
which asks make 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.
If you want to run R code in Makevars, e.g. to find configuration information,
please do ensure that you use the correct copy of R or Rscript: 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 via
"$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" filename
"$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e ‘R expression’
where $(R_ARCH_BIN) is only needed currently on Windows.
Environment or make variables can be used to select different macros for 32- and
64-bit code, for example (GNU make syntax, allowed on Windows)
ifeq "$(WIN)" "64"
PKG_LIBS = value for 64-bit Windows
else
PKG_LIBS = value for 32-bit Windows
endif
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
PKG_LIBS = -L$(XML_DIR)/lib -lxml2
one can use
PKG_LIBS = -L$(XML_DIR)/bin -lxml2
since on Windows -lxxx will look in turn for
[Link].a
[Link].a
libxxx.a
[Link]
[Link]
[Link]
where the first and second are conventionally import libraries, the third and fourth
often static libraries (with .lib intended for Visual C++), but might be import
libraries. See for
example [Link]
The fly in the ointment is that the DLL might not be named [Link], and in
fact on 32-bit Windows there is a [Link] whereas on one build for 64-bit
Windows the DLL is called [Link]. Using import libraries can cover
over these differences but can cause equal difficulties.
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 (via [Link] or [Link]) to ship them in
the same directory as the package DLL.
OpenMP support
Using pthreads
Compiling in sub-directories
There is no direct support for the POSIX threads (more commonly known
as pthreads): 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 (hence not Windows).
For reasonably recent versions of gcc and clang the correct specification is
PKG_CPPFLAGS = -pthread
PKG_LIBS = -pthread
(and the plural version is also accepted on some systems/versions). For other
platforms the specification is
PKG_CPPFLAGS = -D_REENTRANT
PKG_LIBS = -lpthread
(and note that the library name is singular). This is what -pthread does on all
known current platforms (although earlier versions of OpenBSD used a different
library name).
For a tutorial see [Link]
POSIX threads are not normally used on Windows, which has its own native
concepts of threads. However, there are two projects implementing pthreads on top
of Windows, pthreads-w32 and winpthreads (part of the MinGW-w64 project).
Whether Windows toolchains implement pthreads is up to the toolchain provider.
A make variable SHLIB_PTHREAD_FLAGS is available for use
in src/[Link] or [Link]: this should be included in
both PKG_CPPFLAGS (or the Fortran compiler flags) and PKG_LIBS.
The presence of a working pthreads implementation cannot be unambiguously
determined without testing for yourself: however, that ‘_REENTRANT’ is
defined43 in C/C++ code is a good indication.
Note that not all pthreads implementations are equivalent as parts are optional
(see [Link]
for example, macOS lacks the ‘Barriers’ option.
See also the comments on thread-safety and performance under OpenMP: on all
known R platforms OpenMP is implemented via pthreads and the known
performance issues are in the latter.
Package authors fairly often want to organize code in sub-directories of src, for
example if they are including a separate piece of external software to which this is
an R interface.
One simple way is simply to set OBJECTS to be all the objects that need to be
compiled, including in sub-directories. For example, CRAN package RSiena has
SOURCES = $(wildcard data/*.cpp network/*.cpp utils/*.cpp model/*.cpp
model/*/*.cpp model/*/*/*.cpp)
$(SHLIB): Csdp/lib/libsdp.a
Csdp/lib/libsdp.a:
@(cd Csdp/lib && $(MAKE) libsdp.a \
CC="$(CC)" CFLAGS="$(CFLAGS) $(CPICFLAGS)" AR="$(AR)" RANLIB="$
(RANLIB)")
Note the quotes: the macros can contain spaces, e.g. CC = "gcc -m64 -std=gnu99".
Several authors have forgotten about parallel makes: the static library in the
subdirectory must be made before the shared object ($(SHLIB)) and so the latter
must depend on the former. Others forget the need44 for position-independent code.
We really do not recommend using src/Makefile instead of src/Makevars,
and as the example above shows, it is not necessary.
Next: Using F9x code, Previous: Using Makevars, Up: Configure and cleanup
[Contents][Index]
1.2.2 Configure example
dnl for 64-bit ODBC need SQL[U]LEN, and it is unclear where they are
defined.
AC_CHECK_TYPES([SQLLEN, SQLULEN], , , [# include <sql.h>])
dnl for unixODBC header
AC_CHECK_SIZEOF(long, 4)
Next: Using C++ code, Previous: Configure example, Up: Configure and cleanup
[Contents][Index]
1.2.3 Using F9x code
R assumes that source files with extension .f are fixed-form Fortran 90 (which
includes Fortran 77), and passes them to the compiler specified by macro ‘FC’. On
known platforms the Fortran compiler will also accept free-form Fortran 90/95
code with extension .f90 or .f95, but those are not used by R itself so this is not
required.
The same compiler is used45 for both fixed-form and free-form Fortran code (with
different file extensions and possibly different flags). Macro PKG_FFLAGS 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 PKG_FCFLAGS is also available for free-form Fortran.
The code used to build R allows a ‘Fortran 90’ compiler to be selected as ‘FC’, so
platforms might be encountered which only support Fortran 90. However, Fortran
95 is widely supported.
Some compilers specified by ‘FC’ will accept Fortran 2003, 2008 or 2018 code:
such code should still use file extension .f90 or .f95. Almost all current
platforms use gfortran where you may need to include -std=f2003, -
std=f2008 or (from version 8) -std=f2018 in PKG_FFLAGS or PKG_FCFLAGS: the
default is ‘GNU Fortran’, Fortran 95 with non-standard extensions. Intel Fortran
had full Fortran 2008 support from version 17.0, and some 2018 support in version
16.0 and more in version 19.0. It is good practice to describe the requirement
in DESCRIPTION’s ‘SystemRequirements’ field.
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 .mod extension: they do depend on the compiler used and so should never be
included in a package.) This creates a dependence which make will not know about
and often causes installation with a parallel make to fail. Thus it is necessary to add
explicit dependencies to src/Makevars to tell make the constraints on the order
of compilation. For example, if file iface.f90 creates a module ‘iface’ used
by files cmi.f90 and dmi.f90 then src/Makevars needs to contain
something like
cmi.o dmi.o: iface.o
Note that it is not portable (although some platforms do accept it) to define a
module of the same name in multiple source files.
Next: C standards, Previous: Using F9x code, Up: Configure and cleanup
[Contents][Index]
1.2.4 Using C++ code
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 (‘C++11’). A minor
update46 (‘C++14’) was published in December 2014 and was used by default as
from R 4.1.0 if supported. Further revisions ‘C++17’ (in December 2017) and ‘C+
+20’ (with many new features in December 2020) have been published since. The
next revision, ‘C++23’, is expected in 2023 and several compilers already have
extensive partial support for the current drafts.
The default standard for compiling R packages was changed to C++17 in R 4.3.0 if
supported (and for rather old compilers, C++14 or even C++11 would be used as
the default).
What standard a C++ compiler aims to support can be hard to determine: the
value47 of __cplusplus 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 configure will try to identify a compiler and flags for
each of the standards: this relies heavily on the reported values of __cplusplus.
The webpage [Link] gives some
information on which compilers are known to support recent C++ features.
C++ standards have deprecated and later removed features. Be aware that some
current compilers still accept removed features in C++17 mode, such
as std::unary_function (deprecated in C++11, removed in C++17).
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 Makevars file
(or [Link] or [Link] on Windows) should include the line
CXX_STD = CXX14
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+
+1148 when the code is valid under C++14 or C++17 reduces future portability.
Packages without a src/Makevars or src/Makefile file may specify a C++
standard for code in the src directory by including something like ‘C++14’ in the
‘SystemRequirements’ field of the DESCRIPTION file, e.g.
SystemRequirements: C++14
If a package does have a src/Makevars[.win] file then also setting the make
variable ‘CXX_STD’ there is recommended, as it allows R CMD SHLIB to work
correctly in the package’s src directory.
A requirement of C++17 or later should always be declared in the
‘SystemRequirements’ field (as well as
in src/Makevars or src/Makefile) so this is shown on the package’s
summary pages on CRAN 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.
Essentially complete C++14 support is available from GCC 5, LLVM clang 3.4
and currently-used versions of Apple clang (10.0.0 for High Sierra).
Code needing C++14 features can check for their presence via ‘SD-6 feature
tests’49. Such a check could be
#include <memory> // header where this is defined
#if defined(__cpp_lib_make_unique) && (__cpp_lib_make_unique >= 201304)
using std::make_unique;
#else
// your emulation
#endif
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 14 by 17, 20 or 23) 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 g++’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 ‘devtoolset’.
Note that C++17 or later ‘support’ does not mean complete support: use feature
tests as well as resources such
as [Link] [Link]
projects/[Link] and [Link] to see if the
features you want to use are widely implemented.
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.
If a package using C++ has a configure script it is essential that the script selects
the correct C++ compiler and standard, via something like
CXX17=`"${R_HOME}/bin/R" CMD config CXX17`
if test -z "$CXX17"; then
AC_MSG_ERROR([No C++17 compiler is available])
fi
CXX17STD=`"${R_HOME}/bin/R" CMD config CXX17STD`
CXX="${CXX17} ${CXX17STD}"
CXXFLAGS=`"${R_HOME}/bin/R" CMD config CXX17FLAGS`
## for an [Link] file
AC_LANG(C++)
if C++17 was specified, but using
CXX=`"${R_HOME}/bin/R" CMD config CXX`
CXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS`
## for an [Link] file
AC_LANG(C++)
if no standard was specified.
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 src/Makevars
sublibs:
@(cd libs && $(MAKE) \
CXX="$(CXX17) $(CXX17STD)" CXXFLAGS="$(CXX17FLAGS) $
(CXX17PICFLAGS)")
The discussion above is about the standard R ways of compiling C++: it will not
apply to packages using src/Makefile or building in a subdirectory that do not
set the C++ standard. And compilers’ default C++ standards varies widely and gets
changed frequently by vendors – for example Apple clang 14 defaults to C++98,
LLVM clang 14–15 to C++14, LLVM clang 16 to C++17 and g++ 11–13 to C+
+17.
For a package with a src/Makefile (or a Windows analogue), a non-default
C++ compiler can be selected by including something like
CXX14 = `"${R_HOME}/bin/R" CMD config CXX14`
CXX14STD = `"${R_HOME}/bin/R" CMD config CXX14STD`
CXX = ${CXX14} ${CXX14STD}
CXXFLAGS = `"${R_HOME}/bin/R" CMD config CXX14FLAGS`
CXXPICFLAGS = `"${R_HOME}/bin/R" CMD config CXX14PICFLAGS`
SHLIB_LD = "${R_HOME}/bin/R" CMD config SHLIB_CXX14LD`
SHLIB_LDFLAGS = "${R_HOME}/bin/R" CMD config SHLIB_CXX14LDFLAGS`
and ensuring these values are used in relevant compilations, after checking they are
non-empty. A common use of src/Makefile is to compile an executable, when
likely something like (for example for C++14)
CXX14 = `"${R_HOME}/bin/R" CMD config CXX14`
CXX14STD = `"${R_HOME}/bin/R" CMD config CXX14STD`
CXX = ${CXX14} ${CXX14STD}
CXXFLAGS = `"${R_HOME}/bin/R" CMD config CXX14FLAGS`
suffices. On Unix (and on Windows from R 4.3.0) this can be simplified to
CXX = ${CXX14} ${CXX14STD}
CXXFLAGS = ${CXX14FLAGS}
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 ‘if available’, so
platforms using very old OSes might have used the previous default. Even older
versions of R defaulted to the compiler’s default, almost certainly C++98 for
compilers of comparable vintage.
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.
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.
Next: Using cmake, Previous: Using C++ code, Up: Configure and cleanup
[Contents][Index]
1.2.5 C standards
C has had standards C89/C90, C99, C11, C17 (also known as C18) and C23 is in
final draft and expected to be publishedd in early 2024. C11 was a minor change to
C99 which introduced some new features and made others optional, and C17 is a
‘bug-fix’ update to C11. On the other hand, C23 makes extensive changes,
including making bool, true and false reserved words, finally disallowing K&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 [Link]
The configure script in recent versions of R aims to choose a C compiler which
supports C11: as the default in recent versions of gcc, LLVM clang and
Apple clang 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.
Packages may want to either avoid or embrace the changes in C23, and can do
so via specifying ‘USE_Cnn’ for 17, 23, 90 or 99 in the
‘SystemRequirements’ field of their DESCRIPTION file of a package
depending on ‘R (>= 4.3.0)’. Those using a configure script should set the
corresponding compiler and flags, for example using
CC=`"${R_HOME}/bin/R" CMD config CC23`
CFLAGS=`"${R_HOME}/bin/R" CMD config C23FLAGS`
CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS`
LDFLAGS=`"${R_HOME}/bin/R" CMD config LDFLAGS`
The (claimed) C standard in use can be checked by the macro __STDC_VERSION__.
This is undefined in C89/C90 and should have
values 199901L, 201112L and 201710L for C99, C11 and C17. As C23 is not yet
published there is as yet no definitive value: compilers are currently using 202000L.
C23 has macros similar to C++ ‘feature tests’ for many of its changes, for
example __STDC_VERSION_LIMITS_H__.
However, note the ‘claimed’ as no compiler had 100% conformance, and it is
better to use configure to test for the feature you want to use than to condition on
the value of __STDC_VERSION__. In particular, C11 alignment functionality such
as _Alignas and aligned_alloc is not implemented on Windows.
End users can specify a standard by something like R CMD INSTALL --use-C17. This
overrides the ‘SystemRequirements’ field, but not for any configure file.
Packages often wish to include the sources of other software and compile that for
inclusion in their .so or .dll, which is normally done by including (or
unpacking) the sources in a subdirectory of src, as considered above.
Further issues arise when the external software uses another build system such
as cmake, principally to ensure that all the settings for compilers, include and load
paths etc are made. This section has already mentioned the need to set at least
some of
CC CFLAGS CXX CXXFLAGS CPPFLAGS LDFLAGS
CFLAGS and CXXFLAGS will need to include CPICFLAGS and CXXPICFLAGS respectively
unless (as below) cmake is asked to generate PIC code.
Setting these (and more) as environment variables controls the behaviour
of cmake ([Link]
[Link]#manual:cmake-env-variables(7)), but it may be desirable to
translate these into native settings such as
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
and it is often necessary to ensure a static library of PIC code is built by
-DBUILD_SHARED_LIBS:bool=OFF
-DCMAKE_POSITION_INDEPENDENT_CODE:bool=ON
If R is to be detected or used, this must be the build being used for package
installation – "${R_HOME}"/bin/R.
To fix ideas, consider a package with sources for a
library myLib under src/libs. 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) – this is illustrated in the first
approach.
1. Use the package’s configure script to create a static
library src/build/libmyLib.a. This can then be treated in the same
way as external software, for example having in src/Makevars
2. PKG_CPPFLAGS = -Ilibs/include
3. PKG_LIBS = build/libmyLib.a
(-Lbuild -lmyLib could also be used but this explicit specification avoids
any confusion with dynamic libraries of the same name.)
The configure script will need to contain something like (for C code)
: ${R_HOME=`R RHOME`}
if test -z "${R_HOME}"; then
echo "could not determine R_HOME"
exit 1
fi
CC=`"${R_HOME}/bin/R" CMD config CC`
CFLAGS=`"${R_HOME}/bin/R" CMD config CFLAGS`
CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS`
LDFLAGS=`"${R_HOME}/bin/R" CMD config LDFLAGS`
cd src
mkdir build && cd build
cmake ../libs \
-DCMAKE_BUILD_TYPE=Release \
-DBUILD_SHARED_LIBS:bool=OFF \
-DCMAKE_POSITION_INDEPENDENT_CODE:bool=ON
${MAKE}
4. Use src/Makevars (or src/[Link] or [Link])
to build within the subdirectory. This could be something like (for C code)
5. PKG_CPPFLAGS = -Ilibs/include
6. PKG_LIBS = libs/libmyLib.a
7.
8. $(SHLIB): mylibs
9.
10. mylibs:
11. (cd libs; \
12. CC="$(CC)" CFLAGS="$(CFLAGS)" \
13. CPPFLAGS="$(CPPFLAGS)" LDFLAGS="$(LDFLAGS)" \
14. cmake . \
15. -DCMAKE_BUILD_TYPE=Release \
16. -DBUILD_SHARED_LIBS:bool=OFF \
17. -DCMAKE_POSITION_INDEPENDENT_CODE:bool=ON; \
18. $(MAKE))
19.
the compiler and other settings having been set as Make variables by an R
makefile included by INSTALL before src/Makevars.
A complication is that on macOS cmake (where installed) is commonly not on the
path but at /Applications/[Link]/Contents/bin/cmake. One
way to work around this is for the package’s configure script to include
if test -z "$CMAKE"; then CMAKE="`which cmake`"; fi
if test -z "$CMAKE"; then CMAKE=/Applications/[Link]/Contents/bin/cmake;
fi
if test -f "$CMAKE"; then echo "no ‘cmake’ command found"; exit 1; fi
and for the second approach to substitute CMAKE into src//Makevars.
Next: Writing package vignettes, Previous: Configure and cleanup, Up: Creating R
packages [Contents][Index]
Next: Building binary packages, Previous: Checking packages, Up: Checking and
building packages [Contents][Index]
1.3.2 Building package tarballs
To exclude files from being put into the package, one can specify a list of exclude
patterns in file .Rbuildignore in the top-level source directory. These patterns
should be Perl-like regular expressions (see the help for regexp 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 systems57 or from eclipse58, directories with
names check, chm, or ending .Rcheck or Old or old and
files GNUMakefile59, Read-and-delete-me or with base names starting
with ‘.#’, or starting and ending with ‘#’, or ending in ‘~’, ‘.bak’ or ‘.swp’, are
excluded by default60. 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 R, demo and man directories which are flagged by R CMD
check as having invalid names.
Use R CMD build --help to obtain more information about the usage of the R
package builder.
Unless R CMD build is invoked with the --no-build-vignettes option (or
the package’s DESCRIPTION contains ‘BuildVignettes: no’ or similar), it
will attempt to (re)build the vignettes (see Writing package vignettes) 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).
Similarly, if the .Rd documentation files contain any \Sexpr macros (see Dynamic
pages), the package will be temporarily installed to execute them. Post-execution
binary copies of those pages containing build-time macros will be saved
in build/[Link]. If there are any install-time or render-time macros,
a .pdf version of the package manual will be built and installed in
the build subdirectory. (This allows CRAN or other repositories to display the
manual even if they are unable to install the package.) This can be suppressed by
the option --no-manual or if package’s DESCRIPTION contains
‘BuildManual: no’ or similar.
One of the checks that R CMD build runs is for empty source directories. These are
in most (but not all) cases unintentional, if they are intentional use the option --
keep-empty-dirs (or set the environment
variable _R_BUILD_KEEP_EMPTY_DIRS_ to ‘TRUE’, or have a ‘BuildKeepEmpty’
field with a true value in the DESCRIPTION file).
The --resave-data option allows saved images (.rda and .RData files) in
the data directory to be optimized for size. It will also compress tabular files and
convert .R files to saved images. It can take values no, gzip (the default if this
option is not supplied, which can be changed by setting the environment
variable _R_BUILD_RESAVE_DATA_) and best (equivalent to giving it without a value),
which chooses the most effective compression. Using best adds a dependence on R
(>= 2.10) to the DESCRIPTION file if bzip2 or xz compression is selected for any
of the files. If this is thought undesirable, --resave-data=gzip (which is the
default if that option is not supplied) will do what compression it can with gzip. A
package can control how its data is resaved by supplying a ‘BuildResaveData’
field (with one of the values given earlier in this paragraph) in
its DESCRIPTION file.
The --compact-vignettes option will run tools::compactPDF over the PDF
files in inst/doc (and its subdirectories) to losslessly compress them. This is not
enabled by default (it can be selected by environment
variable _R_BUILD_COMPACT_VIGNETTES_) and
needs qpdf ([Link] to be available.
It can be useful to run R CMD check --check-subdirs=yes on the built tarball as a
final check on the contents.
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
‘mode’ of the file recorded in the tarball will be whatever [Link]() returns. On
Windows this will record only directories as having execute permission and on
other OSes it is likely that all files have reported ‘mode’ 0777. A particular issue is
packages being built on Windows which are intended to contain executable scripts
such as configure and cleanup: R CMD build ensures those two are recorded
with execute permission.
Directory build of the package sources is reserved for use by R CMD build: 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).
where location is the chosen directory with write access. The package will be
installed as a subdirectory of location, and the package binary will be created
in the current directory.
Other options for R CMD INSTALL can be found using R CMD INSTALL --help, and
platform-specific details for special cases are discussed in the platform-specific
FAQs.
Finally, at least one web-based service is available for building binary packages
from (checked) source code: WinBuilder (see [Link] is
able to build 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.
%.pdf: %.tex
texi2dvi --pdf $*
clean:
rm *.tex ABC-details-*.pdf
which will start removing the source files whilst pdflatex is working.
Metadata lines can be placed in the source file, preferably in LaTeX comments in
the preamble. One such is a \VignetteIndexEntry of the form
%\VignetteIndexEntry{Using Animal}
Others you may see are \VignettePackage (currently ignored), \VignetteDepends (a
comma-separated list of package names) and \VignetteKeyword (which replaced \
VignetteKeywords). These are processed at package installation time to create the
saved data frame Meta/[Link]. The \VignetteEngine statement is
described in Non-Sweave vignettes. Vignette metadata can be extracted from a
source file using tools::vignetteInfo.
At install time an HTML index for all vignettes in the package is automatically
created from the \VignetteIndexEntry statements unless a
file [Link] exists in directory inst/doc. This index is linked from
the HTML help index for the package. If you do supply
a inst/doc/[Link] file it should contain relative links only to files
under the installed doc directory, or perhaps (not really an index) to HTML help
files or to the DESCRIPTION file, and be valid HTML as confirmed via the W3C
Markup Validation Service or [Link].
Sweave/Stangle allows the document to specify the split=TRUE 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 .R.
Do watch that PDFs are not too large – one in a CRAN 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.
When R CMD build builds the vignettes, it copies these and the vignette sources
from directory vignettes to inst/doc. To install any other files from
the vignettes directory, include a
file vignettes/.install_extras which specifies these as Perl-like regular
expressions on one or more lines. (See the description of the .Rinstignore file
for full details.)
Encodings and vignettes
Non-Sweave vignettes
Vignettes in formats other than Sweave are supported via “vignette engines”. For
example knitr version 1.1 or later can create .tex files from a variation on
Sweave format, and .html files from a variation on “markdown” format. These
engines replace the Sweave() function with other functions to convert vignette
source files into LaTeX files for processing into .pdf, or directly
into .pdf or .html files. The Stangle() function is replaced with a function that
extracts the R source from a vignette.
R recognizes non-Sweave vignettes using filename extensions specified by the
engine. For example, the knitr package supports the extension .Rmd (standing for
“R markdown”). The user indicates the vignette engine within the vignette source
using a \VignetteEngine line, for example
%\VignetteEngine{knitr::knitr}
This specifies the name of a package and an engine to use in place of Sweave in
processing the vignette. As Sweave is the only engine supplied with the R
distribution, the package providing any other engine must be specified in the
‘VignetteBuilder’ field of the package DESCRIPTION file, and also
specified in the ‘Suggests’, ‘Imports’ or ‘Depends’ 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 utils package is always implicitly appended to the list of builder packages, but
may be included earlier to change the search order.
Note that a package with non-Sweave vignettes should always have a
‘VignetteBuilder’ field in the DESCRIPTION file, since this is how R CMD
check recognizes that there are vignettes to be checked: packages listed there are
required when the package is checked.
The vignette engine can produce .tex, .pdf, or .html files as output. If it
produces .tex files, R will call texi2pdf to convert them to .pdf for display to
the user (unless there is a Makefile in the vignettes directory).
Package writers who would like to supply vignette engines need to register those
engines in the package .onLoad function. For example, that function could make
the call
tools::vignetteEngine("knitr", weave = vweave, tangle = vtangle,
pattern = "[.]Rmd$", package = "knitr")
(The actual registration in knitr is more complicated, because it supports other
input formats.) See the ?tools::vignetteEngine help topic for details on engine
registration.
Exports are specified using the export directive in the NAMESPACE file. A
directive of the form
export(f, g)
specifies that the variables f and g are to be exported. (Note that variable names
may be quoted, and reserved words and non-standard names such
as [<-.fractions must be.)
For packages with many variables to export it may be more convenient to specify
the names to export with a regular expression using exportPattern. The directive
exportPattern("^[^\\.]")
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. ‘.__S3MethodsTable__.’ (and
loading excludes known cases).
Packages implicitly import the base namespace. Variables exported from other
packages with namespaces need to be imported explicitly using the
directives import and importFrom. The import directive imports all exported
variables from the specified package(s). Thus the directives
import(foo, bar)
specifies that all exported variables in the packages foo and bar are to be imported.
If only some of the exported variables from a package are needed, then they can be
imported using importFrom. The directive
importFrom(foo, f, g)
specifies that the exported variables f and g of the package foo are to be imported.
Using importFrom selectively rather than import 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).
To import every symbol from a package but for a few exceptions, pass
the except argument to import. The directive
import(foo, except=c(bar, baz))
imports every symbol from foo except bar and baz. The value of except should
evaluate to something coercible to a character vector, after substituting each
symbol for its corresponding string.
It is possible to export variables from a namespace which it has imported from
other namespaces: this has to be done explicitly and not via exportPattern.
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 f in package foo is of the form foo::f. This is
slightly less efficient than a formal import and also loses the advantage of
recording all dependencies in the NAMESPACE file (but they still need to be
recorded in the DESCRIPTION file). Evaluating foo::f will cause package foo to
be loaded, but not attached, if it was not loaded already—this can be an advantage
in delaying the loading of a rarely used package. However, if foo is listed only in
‘Suggests’ or ‘Enhances’ this also delays the check that it is installed: it is
good practice to use such imports conditionally (e.g. via requireNamespace("foo",
quietly = TRUE)).
Using the foo::f form will be necessary when a package needs to use a function of
the same name from more than one namespace.
Using foo:::f instead of foo::f 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.
Next: Load hooks, Previous: Specifying imports and exports, Up: Package
namespaces [Contents][Index]
1.5.2 Registering S3 methods
The standard method for S3-style UseMethod 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 S3method directives. If a package defines a function [Link] intended to be
used as a print method for class foo, then the directive
S3method(print, foo)
ensures that the method is registered and available for UseMethod dispatch, and the
function [Link] does not need to be exported. Since the generic print is defined
in base it does not need to be imported explicitly.
(Note that function and class names may be quoted, and reserved words and non-
standard names such as [<- and function must be.)
It is possible to specify a third argument to S3method, the function to be used as
the method, for example
S3method(print, check_so_symbols, .[Link])
when print.check_so_symbols is not needed.
As from R 3.6.0 one can also use S3method() directives to
perform delayed registration. With
if(getRversion() >= "3.6.0") {
S3method(pkg::gen, cls)
}
function [Link] will get registered as an S3 method for class cls and
generic gen from package pkg only when the namespace of pkg is loaded. This can
be employed to deal with situations where the method is not “immediately”
needed, and having to pre-load the namespace of pkg (and all its strong
dependencies) in order to perform immediate registration is considered too
onerous.
There are a number of hooks called as packages are loaded, attached, detached, and
unloaded. See help(".onLoad") for more details.
Since loading and attaching are distinct operations, separate hooks are provided for
each. These hook functions are called .onLoad and .onAttach. They both take
arguments66 libname and pkgname; they should be defined in the namespace but not
exported.
Packages can use a .onDetach or .[Link] function (provided the latter is exported
from the namespace) when detach is called on the package. It is called with a
single argument, the full path to the installed package. There is also a
hook .onUnload which is called when the namespace is unloaded (via a call
to unloadNamespace, perhaps called by detach(unload = TRUE)) with argument the
full path to the installed package’s directory.
Functions .onUnload and .onDetach should be defined in the namespace and not
exported, but .[Link] does need to be exported.
Packages are not likely to need .onAttach (except perhaps for a start-up banner);
code to set options and load shared objects should be placed in a .onLoad function,
or use made of the useDynLib directive described next.
User-level hooks are also available: see the help on function setHook.
These hooks are often used incorrectly. People forget to export .[Link].
Compiled code should be loaded in .onLoad (or via a useDynLb directive: see
below) and unloaded in .onUnload. Do remember that a package’s namespace can
be loaded without the namespace being attached (e.g. by pkgname::fun) and that a
package can be detached and re-attached whilst its namespace remains loaded.
It is good practice for these functions to be quiet. Any messages should
use packageStartupMessage so users (include check scripts) can suppress them if
desired.
A NAMESPACE file can contain one or more useDynLib directives which allows
shared objects that need to be loaded.67 The directive
useDynLib(foo)
registers the shared object foo68 for loading with [Link]. 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 useDynLib directive instead.
The useDynLib directive also accepts the names of the native routines that are to be
used in R via the .C, .Call, .Fortran and .External interface functions. These are
given as additional arguments to the directive, for example,
useDynLib(foo, myRoutine, myOtherRoutine)
By specifying these names in the useDynLib directive, the native symbols are
resolved when the package is loaded and R variables identifying these symbols are
added to the package’s namespace with these names. These can be used in
the .C, .Call, .Fortran and .External calls in place of the name of the routine and
the PACKAGE argument. For instance, we can call the routine myRoutine from R with
the code
.Call(myRoutine, x, y)
rather than
.Call("myRoutine", x, y, PACKAGE = "foo")
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).
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 myRoutine. In this case, it is necessary to map the native symbol to
a different R variable name. This can be done in the useDynLib directive by using
named arguments. For instance, to map the native symbol name myRoutine to the R
variable myRoutine_sym, we would use
useDynLib(foo, myRoutine_sym = myRoutine, myOtherRoutine)
We could then call that routine from R using the command
.Call(myRoutine_sym, x, y)
Symbols without explicit names are assigned to the R variable with that name.
In some cases, it may be preferable not to create R variables in the package’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 dll, we can call the routine myRoutine using the
expression
.Call(dll$myRoutine, x, y)
The $ operator resolves the routine with the given name in the DLL using a call
to getNativeSymbol. 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 dll$myRoutine.
In order to use this dynamic approach (e.g., dll$myRoutine), 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 variable = dllName format used above for mapping
symbols to R variables. For example, if we wanted to assign the DLL reference for
the DLL foo in the example above to the variable myDLL, we would use the
following directive in the NAMESPACE file:
myDLL = useDynLib(foo, myRoutine_sym = myRoutine, myOtherRoutine)
Then, the R variable myDLL is in the package’s namespace and available for calls
such as myDLL$dynRoutine to access routines that are not explicitly resolved at load
time.
If the package has registration information (see Registering native routines), then
we can use that directly rather than specifying the list of symbols again in
the useDynLib directive in the NAMESPACE 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 .registration argument of useDynLib, 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 myDLL:
static R_NativePrimitiveArgType foo_t[] = {
REALSXP, INTSXP, STRSXP, LGLSXP
};
As an example consider two packages named foo and bar. The R code for
package foo in file foo.R is
x <- 1
f <- function(y) c(x,y)
foo <- function(x) .Call("foo", x, PACKAGE="foo")
[Link] <- function(x, ...) cat("<a foo>\n")
Some C code defines a C function compiled into DLL foo (with an appropriate
extension). The NAMESPACE file for this package is
useDynLib(foo)
export(f, foo)
S3method(print, foo)
Calling library(bar) loads bar and attaches its exports to the search path.
Package foo is also loaded but not attached to the search path. A call to g produces
> g(6)
[1] 1 13
This is consistent with the definitions of c in the two settings: in bar the
function c is defined to be equivalent to sum, but in foo the variable c refers to the
standard function c in base.
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 Depends: methods in
its DESCRIPTION and import(methods) or importFrom(methods, ...) plus any
classes and methods which are to be exported need to be declared in
the NAMESPACE file. For example, the stats4 package has
export(mle) # exporting methods implicitly exports the generic
importFrom("stats", approx, optim, pchisq, predict, qchisq, qnorm, spline)
## For these, we define methods or (AIC, BIC, nobs) an implicit generic:
importFrom("stats", AIC, BIC, coef, confint, logLik, nobs, profile,
update, vcov)
exportClasses(mle, [Link], [Link])
## 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)
All S4 classes to be used outside the package need to be listed in
an exportClasses directive. Alternatively, they can be specified
using exportClassPattern69 in the same style as for exportPattern. To export
methods for generics from other packages an exportMethods directive can be used.
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 coef in the example above), it can
be declared via either or both of export or exportMethods, but the latter is clearer
(and is used in the stats4 example above). In particular, for primitive functions
there is no generic function, so export 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 export(), and this must be done if an implicit
generic is created without setting any methods for it (as is the case
for AIC in stats4).
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 undoc in
package tools will not report them.
If a package uses S4 classes and methods exported from another package, but does
not import the entire namespace of the other package70, it needs to import the
classes and methods explicitly, with directives
importClassesFrom(package, ...)
importMethodsFrom(package, ...)
listing the classes and functions with methods respectively. Suppose we had two
small packages A and B with B using A. Then they could have NAMESPACE files
export(f1, ng1)
exportMethods("[")
exportClasses(c1)
and
importFrom(A, ng1)
importClassesFrom(A, c1)
importMethodsFrom(A, f1)
export(f4, f5)
exportMethods(f6, "[")
exportClasses(c1, c2)
respectively.
Note that importMethodsFrom will also import any generics defined in the
namespace on those methods.
It is important if you export S4 methods that the corresponding generics are
available. You may for example need to import coef from stats 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 stats4 as this enables multiple packages to
unambiguously set methods on those generics.
Next: Check timing, Previous: Writing portable packages, Up: Writing portable
packages [Contents][Index]
1.6.1 PDF size
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).
qpdf ([Link] can compress losslessly. It is fairly readily
available (e.g. it has binaries for Windows and packages in Debian/Ubuntu/Fedora,
and is installed as part of the CRAN macOS distribution of R). R CMD build has an
option to run qpdf over PDF files under inst/doc and replace them if at least
10Kb and 10% is saved. The full path to the qpdf command can be supplied as
environment variable R_QPDF (and is on the CRAN binary of R for macOS). It
seems MiKTeX does not use PDF object compression and so qpdf can reduce
considerably the sizes of files it outputs: MiKTeX’s defaults can be overridden by
code in the preamble of an Sweave or LaTeX file — see how this is done for the R
reference manual at [Link]
Other tools can reduce the size of PDFs containing bitmap images at excessively
high resolution. These are often best re-generated (for example Sweave defaults to
300 ppi, and 100–150 is more appropriate for a package manual). These tools
include Adobe Acrobat (not Reader), Apple’s Preview92 and Ghostscript (which
converts PDF to PDF by
ps2pdf options -dAutoRotatePages=/None -dPrinted=false [Link] [Link]
and suitable options might be
-dPDFSETTINGS=/ebook
-dPDFSETTINGS=/screen
See [Link] for more such
and consider all the options for image downsampling). There have been examples
in CRAN packages for which current versions of Ghostscript produced much
bigger reductions than earlier ones (e.g. at the upgrades from 9.50 to 9.52,
from 9.55 to 9.56 and then to 10.00.0).
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.
Option --compact-vignettes to R CMD build defaults to value ‘qpdf’: use
‘both’ to try harder to reduce the size, provided you have Ghostscript available
(see the help for tools::compactPDF).
Next: Encoding issues, Previous: PDF size, Up: Writing portable packages
[Contents][Index]
1.6.2 Check timing
There are several ways to find out where time is being spent in the check process.
Start by setting the environment variable _R_CHECK_TIMINGS_ to ‘0’. 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.
Setting _R_CHECK_TIMINGS_ to a positive value sets a threshold (in seconds elapsed
time) for reporting timings.
If you need to look in more detail at the timings for examples, use option --
timings to R CMD check (this is set by --as-cran). 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 [Link]/[Link] containing
timings for each help file: it is a tab-delimited file which can be read into R for
further analysis.
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 _R_CHECK_ALWAYS_LOG_VIGNETTE_OUTPUT_ is set to a true value.
Next: Portable C and C++ code, Previous: Check timing, Up: Writing portable
packages [Contents][Index]
1.6.3 Encoding issues
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.
Care is needed if your package contains non-ASCII 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 DESCRIPTION file and in .Rd files, as discussed elsewhere in this
manual.
First, consider carefully if you really need non-ASCII 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 ASCII.93. Other characters
may not be rendered at all, rendered incorrectly, or cause your R code to give an
error. For .Rd documentation, marking the encoding and
including ASCII 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, …) are still often problematic
and those with double-width characters (Chinese, Japanese, Korean, emoji) often
need specialist fonts to render correctly.
Several CRAN 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.
Function showNonASCIIfile in package tools can help in finding non-ASCII bytes
in files.
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 ‘\uxxxx’ escapes (or, rarely needed
except for emojis, ‘\Uxxxxxxxx’ 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 ‘\uxxxx’ escapes or encoded in UTF-8 in a UTF-8 locale, or even
converted to UTF-8 via iconv(). If you do this, make sure you have ‘R (>=
2.10)’ (or later) in the ‘Depends’ field of the DESCRIPTION file.
R sessions running in non-UTF-8 locales will if possible re-encode such strings for
display (and this is done by RGui on older versions of Windows, for example).
Suitable fonts will need to be selected or made available94 both for the
console/terminal and graphics devices such as ‘X11()’ and ‘windows()’. Using
‘postscript’ or ‘pdf’ 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 ‘encoding’ argument.
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 NAMESPACE 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 ‘don't’ instead of the
correct apostrophe.
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’ CP1252 locale, for performance
reasons these should be converted to UTF-8.
If you want to run R CMD check on a Unix-alike over a package that sets a package
encoding in its DESCRIPTION file and do not use a UTF-8 locale you may need
to specify a suitable locale via environment variable R_ENCODING_LOCALES. The
default is equivalent to the value
"latin1=en_US:latin2=pl_PL:UTF-8=en_US.UTF-8:latin9=fr_FR.iso885915@euro"
(which is appropriate for a system based on glibc: macOS
requires latin9=fr_FR.ISO8859-15) 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.
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 — this typically means using flags -Wall and -pedantic for both
C and C++ and additionally -Werror=implicit-function-
declaration and -Wstrict-prototypes for C (on some platforms and
compiler versions) these are part of -Wall or -pedantic).
C++ standards: From version 3.6.0 (3.6.2 on Windows), R defaulted to C++11
where available95; R 4.1.0 and later default to C++14 (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 Using C++ code) or be tested under
all of C++11, C++98 and C++14. (Specifying C++14 will limit portability.)
Note that the ‘TR1’ C++ extensions are not part of any of these standards and
the <tr1/name> headers are not supplied by some of the compilers used for R,
including on macOS. (Use the C++11 versions instead.)
A common error is to assume recent versions of compilers or OSes. In production
environments ‘long term support’ versions of OSes may be in use for many
years,96 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.
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
combinations97 they are not declared otherwise. So you may need to include
something like one of
#define _XOPEN_SOURCE 600
or
#ifdef __GLIBC__
# define _POSIX_C_SOURCE 200809L
#endif
before any headers. (strdup, strncasecmp and strnlen are such functions – there
were several older platforms which did not have the POSIX 2008
function strnlen.)
However, some common errors are worth pointing out here. It can be helpful to
look up functions
at [Link] or [Link] and compare
what is defined in the various standards.
More care is needed for functions such as mallinfo which are not specified by any
of these standards—hopefully the man 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 [Link] allow you to select many OSes) should
reveal useful information but a configure script is likely to be needed to check
availability and functionality.
Both the compiler and OS (via 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, clang, Intel and Oracle Developer Studio suites
have been used with R, and both LLVM clang 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.
Mathematical functions such as sqrt are defined in C++11 for floating-point
arguments: float, double, long double 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 ‘overloading ambiguity’: this
was commonly seen on Solaris, but for pow also seen on macOS and other
platforms using clang++.
A not-uncommonly-seen problem is to mistakenly
call floor(x/y) or ceil(x/y) for int arguments x and y. Since x/y does
integer division, the result is of type int and ‘overloading ambiguity’ may
be reported. Some people have (pointlessly) called floor and ceil on
arguments of integer type, which may have an ‘overloading ambiguity’.
A surprising common misuse is things like pow(10, -3): this should be the
constant 1e-3. Note that there are constants such
as M_SQRT2 defined via Rmath.h98 for sqrt(2.0), frequently mis-coded
as sqrt(2).
Function fabs is defined only for floating-point types, except in C++11 and
later which have overloads for std::fabs in <cmath> for integer types.
Function abs is defined in C99’s <stdlib.h> for int and in C+
+’s <cstdlib> for integer types, overloaded in <cmath> for floating-
point types. C++11 has additional overloads for std::abs in <cmath> for
integer types. The effect of calling abs with a floating-point type is
implementation-specific: it may truncate to an integer. For clarity and to
avoid compiler warnings, use abs for integer types and fabs for double
values, and when using C++ include <cmath> and use the std:: prefix.
It is an error (and make little sense, although has been seen) to call
macros/functions isnan, isinf and isfinite for integer arguments: a few
compilers give a compilation error. Function finite is obsolete, and some
compilers will warn about its use99.
The GNU C/C++ compilers support a large number of non-portable
extensions. For example, INFINITY (which is a float value in C99 and C+
+11), for which R provides the portable double
value R_PosInf (and R_NegInf for -INFINITY). And NAN100 is just one
NaN float value: for use with R, NA_REAL is often what is intended,
but R_NaN is also available.
Some (but not all) extensions are listed
at [Link] and https://
[Link]/onlinedocs/gcc/C_002b_002b-[Link].
Other GNU extensions which have bitten package writers are the use of
non-portable characters such as ‘$’ in identifiers and use of C++ headers
under ext.
The GNU Fortran compiler also supports a large number of non-portable
extensions, the most commonly encountered one being ISNAN101. Some are
listed at [Link]
[Link]. 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.
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 [Link]
Including C-style headers in C++ code is not portable. Including the legacy
header102 math.h in C++ code may conflict with cmath which may be
included by other headers. In C++11, functions like sqrt and isnan are
defined for double arguments in math.h and for a range of types
including double in cmath. Similar issues have been seen
for stdlib.h and cstdlib. Including the C++ header first used to be a
sufficient workaround but for some 2016 compilers only one could be
included.
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 <random> which is
indirectly included by <algorithm> by g++. Another issue is the C
header <time.h> which is included by other headers on Linux and Windows
but not macOS.) g++ 11 often needs explicit inclusion of the C++
headers <limits> (for numeric_limits)
or <exception> (for set_terminate and similar), whereas earlier versions
included these in other headers. g++ 13 requires the explicit inclusion
of <cstdint> for types such as uint32_t which was previously included
implicitly. (For more such, see [Link]
Note that malloc, calloc, realloc and free are defined by C99 in the
header stdlib.h and (in the std:: namespace) by C++ header cstdlib.
Some earlier implementations used a header malloc.h, but that is not
portable and does not exist on macOS.
This also applies to types such as ssize_t. The POSIX standards say that is
declared in headers unistd.h and sys/types.h, and the latter is often
included indirectly by other headers on some but not all systems.
Similarly for constants: for example SIZE_MAX is defined
in stdint.h alongside size_t.
Some headers are not portable: we have just mentioned malloc.h and
often CRAN submissions attempt to use endian.h. The latter is
a glibc extension: some OSs
have machine/endian.h or sys/endian.h but some have neither.
Use #include "my.h" not #include <my.h> 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, types.h.
For C++ code, be careful to specify namespaces where needed. Many
functions are defined by the standards to be in the std namespace, but g+
+ puts many such also in the C++ main namespace. One way to do so is to
use declarations such as
using std::floor;
but it is usually preferable to use explicit namespace prefixes in the code.
Examples seen in CRAN packages include
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
This problem is less common than it used to be, but in 2019
LLVM clang did not have bind in the main namespace. Also seen has been
type size_t defined only in the std namespace.
NB: These functions are only guaranteed to be in the std namespace if the
correct C++ header is included, e.g. <cmath> rather than <math.h>.
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 std::make_unique from C++14
and std::byte, std::data, std::sample and std::size from C++17.
In C++ code
using namesapace std;
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 std:: prefixes for all functions
declared by the C++ standard to be in that namespace.
Some C++ compilers refuse to compile constructs such as
if(ptr > 0) { ....}
which compares a pointer to the integer 0. This could just
use if(ptr) (pointer addresses cannot be negative) but if needed pointers
can be tested against nullptr (C++11) or NULL.
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 _POSIX_C_SOURCE 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.
typedefs in OS headers can conflict with those in the package: examples
have included ulong, index_t, single and thread. (Note that these may
conflict with other uses as identifiers, e.g. defining a C++ function
called single.) The POSIX standard reserves (in §2.2.2) all identifiers
ending in _t.
Some compilers do not allow a space between -D and the macro to be
defined. Similarly for -U.
If you use OpenMP, check carefully that you have followed the advice in
the subsection on OpenMP support. In particular, any use of OpenMP in
C/C++ code will need to use
#ifdef _OPENMP
# include <omp.h>
#endif
Any use of OpenMP functions, e.g. omp_set_num_threads, also needs to be
conditioned. To avoid incessant warnings such as
warning: ignoring #pragma omp parallel [-Wunknown-pragmas]
uses of such pragmas should also be conditioned (or commented out if they
are used in code in a package not enabling OpenMP on any platform).
Do not hardcode -lgomp: 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.
Package authors commonly assume things are part of C/C++ when they are
not: the most common example is POSIX103 function strdup. The most
common C library on Linux, glibc, will hide the declarations of such
extensions unless a ‘feature-test macro’ is defined before (almost) any
system header is included. So for strdup you need
#define _POSIX_C_SOURCE 200809L
...
#include <string.h>
...
strdup call(s)
where the appropriate value can be found by man strdup on Linux. (Use
of strncasecmp is similar.)
However, modes of gcc with ‘GNU EXTENSIONS’ (which are the default,
either -std=gnu99 or -std=gnu11) declare enough macros to ensure
that missing declarations are rarely seen.
This applies also to constants such as M_PI and M_LN2, which are part of the
X/Open standard: to use these define _XOPEN_SOURCE before including any
headers, or include the R header Rmath.h.
Using alloca portably is tricky: it is neither an ISO C/C++ nor a POSIX
function. An adequately portable preamble is
#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 <alloca.h>
#endif
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 – it can be hard to know what they are but the most common
warnings are
'register' storage class specifier is deprecated and
incompatible with C++17
ISO C++11 does not allow conversion from string literal to
‘char *’
(where conversion should be to const char *). Keyword register was not
mentioned in C++98, deprecated in C++11 and removed in C++17.
There are quite a lot of other C++98 features deprecated in C++11 and
removed in C++17, and LLVM clang 9 and later warn about them.
Examples include bind1st/bind2nd (use std::bind or
lambdas104) std::auto_ptr (replaced
by std::unique_ptr), std::mem_fun_ref and std::ptr_fun.
Later versions of standards may add reserved words: for
example bool, false and true became keywords in C23 and are no longer
available as variable names. As noted above, C++17
uses byte, data, sample and size.
So avoid common words and keywords in other programming languages.
Be careful about including C headers in C++ code. Issues include
Use of the register storage class specifier (see the previous but one
item).
105
The C99 keyword restrict is not part of any C++ standard and is
rejected by some C++ compilers.
Inclusion by such headers of C-style headers such as math.h (see
above).
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).
reinterpret_cast in C++ is not safe for pointers: for example the types may
have different alignment requirements. Use memcpy to copy the contents to a
fresh variable of the destination type.
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, __unix__ is not
defined on all Unix-alikes, in particular not on macOS. A reasonably
portable way to condition code for a Unix-alike is
#if defined (__unix__) || (defined (__APPLE__) && defined
(__MACH__))
#endif
but
#ifdef _WIN32
// Windows-specific code
#else
// Unix-alike code
#endif
would be better. For a Unix-alike it is much better to use configure 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 — and some forget macOS).
Headers in subdirectories are often not portable. For C++, this
includes bits/, tr1/ and tr2/, none of which exist on macOS
(and ext/ exists there but with different content from g++-based platforms).
Header bits/stdc++.h is both not portable and not recommended for
end-user code even on platforms which include it.
Be careful if using malloc or calloc. First, their return value must always be
checked to see if the allocation succeeded – it is almost always easier to use
R’s R_Calloc, which does check. Second, the first argument is of
type size_t and recent compilers are warning about passing signed
arguments (which could get promoted to ridiculously large values).
For C code, consider using the flag -Wstrict-prototypes which is
supported by gcc and LLVM and Apple clang. 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 clang in C23 mode.) Note that using f() for a function without any
parameters was deprecated in C99 and C11, but it expected to be non-
deprecated in C23. However, f(void) is supported by all standards and
avoids any uncertainty.
LLVM clang has a separate warning -Wdeprecated-non-
prototype which is enabled by -Wstrict-prototypes. This warns
on K&R-style usage, which will not be accepted in C23.
Several C entry points are warned against in their man pages on most
systems, often in very strong terms such as ’Do not use these functions’.
macOS has started to warn106 if these are used
for sprintf, vsprintf, gets, mktemp, tempmam and tmpnam. It is highly
recommended that you use safer alternatives (on any platform) but the
warning can be avoided by defining ‘_POSIX_C_SOURCE’ to for example
‘200809L’ before including the (C or C++) header which defines them.
(However, this may hide other extensions.)
Some additional information for C++ is available
at [Link] by
Martyn Plummer.
Common symbols
C++17 issues
Next: C++17 issues, Previous: Portable C and C++ code, Up: Portable C and C++
code [Contents][Index]
[Link] Common symbols
Most OSes (including all those commonly used for R) have the concept of
‘tentative definitions’ 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, gcc 10107 and LLVM clang 11108 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 extern — which means that any such variables
included in header files need to be declared extern. A commonly used idiom
(including by R itself) is to define all global variables as extern in a header,
say globals.h (and nowhere else), and then in one (and one only) source file
use
#define extern
# include "globals.h"
#undef extern
A cleaner approach is not to have global variables at all, but to place in a single file
common variables (declared static) followed by all the functions which make use
of them: this may result in more efficient code.
The ‘modern’ behaviour can be seen109 by using compiler flag -fno-common as
part of ‘CFLAGS’ in earlier versions of gcc and clang.
-fno-common is said to be particularly beneficial for ARM cpus.
This is not pertinent to C++ which does not permit tentative definitions.
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 clang with
its libc++ runtime library finally started to do so in 2023 – some others warn but
some do not.
The principal offender is the ‘Boost’ collection of C++ headers and libraries. There
are two little-documented ways to work around aspects of its outdated code. One is
to add
-D_HAS_AUTO_PTR_ETC=0
to PKG_CPPLAGS in src/Makevars, src/[Link] and src/
[Link]. This covers the removal of
std::auto_ptr
std::unary_function
std::binary_function
std::random_shuffle
std::binder1st
std::binder2nd
with most issues seen with code that includes boost/[Link],
usually indirectly.
A rarer issue is the use of illegal values for enum types, usually negative ones such
as
BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (value - 1));
in boost/mpl/aux_/integral_wrapper.hpp. Adding
-Wno-error=enum-constexpr-conversion
to PKG_CXXFLAGS will allow this, but that flag is only accepted by recent versions of
LLVM clang so needs a configure test.
Pre=built versions of current clang/libc++ are usually available
from [Link] for a wide range of platforms
(but the Windows builds there are not compatible with Rtools and the macOS ones
are unsigned). To select libc++ add -stdlib=libc++ to CXX, for example by
having
CXX="/path/to/clang/clang++ -std=gnu++17 -stdlib=libc++"
in ~/.R/Makevars.
Another build for Windows which may be sufficiently compatible with Rtools can
be found at [Link] this uses libc++.
Previous: Portable C and C++ code, Up: Writing portable packages [Contents]
[Index]
1.6.5 Binary distribution
1.8 Internationalization
There are mechanisms to translate the R- and C-level error and warning messages.
There are only available if R is compiled with NLS support (which is requested
by configure option --enable-nls, the default).
The procedures make use of msgfmt and xgettext which are part
of GNU gettext and this will need to be installed: Windows users can find pre-
compiled binaries at [Link]
[Link].
C-level messages
R messages
Preparing translations
Once the template files have been created, translations can be made. Conventional
translations have file extension .po and are placed in the po subdirectory of the
package with a name that is either ‘[Link]’ or ‘[Link]’ for translations of the
C and R messages respectively to language with code ‘ll’.
See Localization of messages in R Installation and Administration, for details of
language codes.
There is an R function, update_pkg_po in package tools, to automate much of the
maintenance of message translations. See its help for what it does in detail.
If this is called on a package with no existing translations, it creates the
directory pkgdir/po, creates a template file of R messages, pkgdir/po/R-
[Link], within it, creates the ‘en@quot’ translation and installs that. (The
‘en@quot’ pseudo-language interprets quotes in their directional forms in suitable
(e.g. UTF-8) locales.)
If the package has C source files in its src directory that are marked for
translation, use
touch pkgdir/po/[Link]
to create a dummy template file, then call update_pkg_po again (this can also be
done before it is called for the first time).
When translations to new languages are added in the pkgdir/po directory,
running the same command will check and then install the translations.
If the package sources are updated, the same command will update the template
files, merge the changes into the translation .po files and then installed the
updated translations. You will often see that merging marks translations as ‘fuzzy’
and this is reported in the coverage statistics. As fuzzy translations are not used,
this is an indication that the translation files need human attention.
The merged translations are run through tools::checkPofile to check that C-style
formats are used correctly: if not the mismatches are reported and the broken
translations are not installed.
This function needs the GNU gettext-tools installed and on the path: see its help
page.
## NLME book
bibentry(bibtype = "Book",
title = "Mixed-Effects Models in S and S-PLUS",
author = c(person(c("José", "C."), "Pinheiro"),
person(c("Douglas", "M."), "Bates")),
year = "2000", publisher = "Springer", address = "New York",
doi = "10.1007/b98882")
Note how the first call auto-generates citation information from object meta, a
parsed version of the DESCRIPTION file – it is tempting to hardcode such
information, but it normally then gets outdated. How the first entry would look like
as a bibentry call can be seen from print(citation("pkgname", auto = TRUE),
style = "R") for any installed package. Auto-generated information is returned by
default if no CITATION file is present.
See ?bibentry 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 via the textVersion argument to bibentry. E.g., earlier versions
of nlme additionally used something like
textVersion =
paste0("Jose Pinheiro, Douglas Bates, Saikat DebRoy, ",
"Deepayan Sarkar and the R Core Team (",
sub("-.*", "", meta$Date),
"). nlme: Linear and Nonlinear Mixed Effects Models. ",
sprintf("R package version %s", meta$Version), ".")
The CITATION file should itself produce no output when source-d.
It is desirable (and essential for CRAN) that the CITATION file does not contain
calls to functions such as packageDescription which assume the package is
installed in a library tree on the package search path.
This is a rather general mechanism, designed for adding new front-ends such as the
former gnomeGUI package (see the Archive area on CRAN). If
a configure file is found in the top-level directory of the package it is executed,
and then if a Makefile is found (often generated by configure), make is
called. If R CMD INSTALL --clean is used make clean is called. No other action is
taken.
R CMD build can package up this type of extension, but R CMD check will check the
type and skip it.
Many packages of this type need write permission for the R installation directory.
Next: Tidying and profiling R code, Previous: Creating R packages, Up: Writing R
Extensions [Contents][Index]
An Rd 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’s arguments and return value, as in the above
example). Finally, there is an optional footer with keyword information. The
header is mandatory.
Information is given within a series of sections with standard names (and user-
defined sections are also allowed). Unless otherwise specified110 these should occur
only once in an Rd file (in any order), and the processing software will retain only
the first occurrence of a standard section in the file, with a warning.
See “Guidelines for Rd files” for guidelines for writing documentation
in Rd format which should be useful for package writers. The R generic
function prompt is used to construct a bare-bones Rd 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 promptData, promptPackage, promptClass, and promptMethods for other
types of Rd file.
The general syntax of Rd files is summarized below. For a detailed technical
discussion of current Rd syntax, see “Parsing Rd files”.
Rd 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. \alias), and braces used to indicate
arguments (e.g. {load}). The least common type of text is ‘verbatim’ text, where
no markup other than the comment marker (%) is processed. There is also a rare
variant of ‘verbatim’ text (used in \eqn, \deqn, \figure, and \newcommand) 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 \n may be entered as-is. Only
markup starting with \l (e.g. \link) or \v (e.g. \var) will be recognized within
quoted strings. The rarely used vertical tab \v must be entered as \\v.
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 \description section, but the \
usage section uses R-like syntax, and the \alias macro uses ‘verbatim’ syntax.
Comments run from a percent symbol % to the end of the line in all types of text
except the rare ‘verbatim’ variant (as on the first line of the load example).
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
‘verbatim’ variant. For the complete list of macros and rules for escapes,
see “Parsing Rd files”.
Documenting functions
Documenting data sets
Documenting S4 classes and methods
Documenting packages
The basic markup commands used for documenting R objects (in particular,
functions) are given in this subsection.
\name{name}
name typically111 is the basename of the Rd file containing the
documentation. It is the “name” of the Rd 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 ‘!’ ‘|’ nor ‘@’, and to avoid possible problems
with the HTML help system it should not contain ‘/’ nor a space. (LaTeX
special characters are allowed, but may not be collated correctly in the
index.) There can only be one \name entry in a file, and it must not contain
any markup. Entries in the package manual will be in alphabetic112 order of
the \name entries.
\alias{topic}
The \alias sections specify all “topics” the file documents. This information
is collected into index data bases for lookup by the on-line (plain text
and HTML) help systems. The topic 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.
There may be several \alias entries. Quite often it is convenient to
document several R objects in one file. For example,
file [Link] documents the density, distribution function, quantile
function and generation of random variates for the normal distribution, and
hence starts with
\name{Normal}
\alias{Normal}
\alias{dnorm}
\alias{pnorm}
\alias{qnorm}
\alias{rnorm}
Also, it is often convenient to have several different ways to refer to an R
object, and an \alias does not need to be the name of an object.
Note that the \name is not necessarily a topic documented, and if so desired it
needs to have an explicit \alias entry (as in this example).
\title{Title}
Title information for the Rd file. This should be capitalized and not end in a
period; try to limit its length to at most 65 characters for widest
compatibility.
Markup is supported in the text, but use of characters other than English text
and punctuation (e.g., ‘<’) may limit portability.
There must be one (and only one) \title section in a help file.
\description{…}
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.
\usage{fun(arg1, arg2, …)}
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.
The usage information specified should match the function
definition exactly (such that automatic checking for consistency between
code and documentation is possible).
To indicate that a function can be used in several different ways, depending
on the named arguments specified, use section \details.
E.g., [Link] contains
\details{
Typical usages are
\preformatted{abline(a, b, ...)
......
}
Use \method{generic}{class} to indicate the name of an S3 method for the
generic function generic for objects inheriting from class "class". In the
printed versions, this will come out as generic (reflecting the understanding
that methods should not be invoked directly but via method dispatch),
but codoc() and other QC tools always have access to the full name.
For example, [Link] contains
\usage{
\method{print}{ts}(x, calendar, \dots)
}
which will print as
Usage:
For example,
x <- runif(10) # Shown and run.
\dontrun{plot(x)} # Only shown.
\dontshow{log(x)} # Only run.
Thus, example code not included in \dontrun 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 \dontrun is indicated by comments in the processed help
files: it need not be valid R code but the escapes must still be used
for %, \ and unpaired braces as in other ‘verbatim’ text.
Example code must be capable of being run by example, which uses source.
This means that it should not access stdin, e.g. to scan() data from the
example file.
Data needed for making the examples executable can be obtained by random
number generation (for example, x <- rnorm(100)), or by using standard
data sets listed by data() (see ?data for more info).
Finally, there is \donttest, used (at the beginning of a separate line) to mark
code that should be run by example() but not by R CMD check (by default: the
option --run-donttest 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. capabilities() or nzchar([Link]("someprogram")) to test for
features needed in the examples wherever possible, and you can also
use try() or tryCatch(). Use interactive() to condition examples which
need someone to interact with.) Note that code included in \donttest must
be correct R code, and any packages used should be declared in
the DESCRIPTION file. It is good practice to include a comment in the \
donttest section explaining why it is needed.
The structure of Rd files which document R data sets is slightly different. Sections
such as \arguments and \value are not needed but the format and source of the data
should be explained.
As an example, let us look
at src/library/datasets/man/[Link] which documents the
standard R data set rivers.
\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}
There are special ways to use the ‘?’ operator, namely ‘class?topic’ and
‘methods?topic’, to access documentation for S4 classes and methods,
respectively. This mechanism depends on conventions for the topic names used
in \alias entries. The topic names for S4 classes and methods respectively are of
the form
class-class
generic,signature_list-method
where signature_list contains the names of the classes in the signature of the
method (without quotes) separated by ‘,’ (without whitespace), with ‘ANY’ used
for arguments without an explicit specification. E.g., ‘genericFunction-
class’ is the topic name for documentation for the S4 class "genericFunction",
and ‘coerce,ANY,NULL-method’ is the topic name for documentation for the
S4 method for coerce for signature c("ANY", "NULL").
Skeletons of documentation for S4 classes and methods can be generated by using
the functions promptClass() and promptMethods() from package methods. If it is
necessary or desired to provide an explicit function declaration (in a \
usage section) for an S4 method (e.g., if it has “surprising arguments” to be
mentioned explicitly), one can use the special markup
\S4method{generic}{signature_list}(argument_list)
(e.g., ‘\S4method{coerce}{ANY,NULL}(from, to)’).
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 \
alias entry in one of the package’s Rd 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.
An S4 replacement method is documented in the same way as an S3 one: see the
description of \method in Documenting functions.
See help("Documentation", package = "methods") for more information on using
and creating on-line documentation for S4 classes and methods.
Packages may have an overview help page with an \alias pkgname-package, e.g.
‘utils-package’ for the utils package, when package?pkgname will open that
help page. If a topic named pkgname does not exist in another Rd file, it is helpful to
use this as an additional \alias.
Skeletons of documentation for a package can be generated using the
function promptPackage(). If the final = LIBS argument is used, then the Rd file
will be generated in final form, containing the information that would be produced
up to library(help = pkgname). Otherwise (the default) comments will be inserted
giving suggestions for content.
Apart from the mandatory \name and \title and the pkgname-package alias, the
only requirement for the package overview page is that it include a \
docType{package} 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 Writing package vignettes) and referenced from this page, or
into individual man pages for the functions, datasets, or classes.
2.2 Sectioning
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 \cr.
In addition to the predefined sections (such as \description{}, \value{}, etc.), you
can “define” arbitrary ones by \section{section_title}{…}. For example
\section{Warning}{
You must not call this function unless …
}
For consistency with the pre-assigned sections, the section name (the first
argument to \section) should be capitalized (but not all upper case). Whitespace
between the first and second braced expressions is not allowed. Markup (e.g. \
code) within the section title may cause problems with the latex conversion
(depending on the version of macro packages such as ‘hyperref’) and so should
be avoided.
The \subsection macro takes arguments in the same format as \section, 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).
Note that additional named sections are always inserted at a fixed position in the
output (before \note, \seealso and the examples), no matter where they appear in
the input (but in the same order amongst themselves as in the input).
Next: Lists and tables, Previous: Sectioning, Up: Writing R documentation files
[Contents][Index]
Next: Mathematics, Previous: Lists and tables, Up: Writing R documentation files
[Contents][Index]
2.5 Cross-references
The markup \link{foo} (usually in the combination \code{\link{foo}}) produces
a hyperlink to the help for foo. Here foo is a topic, that is the argument of \
alias markup in another Rd file (possibly in another package). Hyperlinks are
supported in some of the formats to which Rd files are converted, for
example HTML and PDF, but ignored in others, e.g. the text format.
One main usage of \link is in the \seealso section of the help page, see Rd format.
Note that whereas leading and trailing spaces are stripped when extracting a topic
from a \alias, they are not stripped when looking up the topic of a \link.
You can specify a link to a different topic than its name by \link[=dest]
{name} which links to topic dest with name name. This can be used to refer to the
documentation for S3/4 classes, for example \code{"\link[=abc-class]
{abc}"} would be a way to refer to the documentation of an S4 class "abc" defined
in your package, and \code{"\link[=[Link]]{terms}"} to the
S3 "terms" class (in package stats). To make these easy to read in the source file, \
code{"\linkS4class{abc}"} expands to the form given above.
There are two other forms with an optional argument, specified as \link[pkg]
{foo} and \link[pkg:bar]{foo}, to link to topics foo and bar respectively in the
package pkg. They are currently only used in HTML 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.
Historically (before R version 4.1.0), links of the form \link[pkg]{foo} and \
link[pkg:bar]{foo} used to be interpreted as links
to files [Link] and [Link] in package pkg, respectively. For this reason,
the HTML help system looks for file [Link] in package pkg if it does not find
topic foo, 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 _R_HELP_LINKS_TO_TOPICS_=false.
Packages referred to by these ‘other forms’ should be declared in
the DESCRIPTION file, in the ‘Depends’, ‘Imports’, ‘Suggests’ or
‘Enhances’ fields.
2.6 Mathematics
Mathematical formulae should be set beautifully for printed documentation yet we
still want something useful for text and HTML online help. To this end, the two
commands \eqn{latex}{ascii} and \deqn{latex}{ascii} are used. Whereas \
eqn is used for “inline” formulae (corresponding to TeX’s $…$), \deqn gives
“displayed equations” (as in LaTeX’s displaymath environment, or TeX’s $$…$$).
Both arguments are treated as ‘verbatim’ text.
Both commands can also be used as \eqn{latexascii} (only one argument) which
then is used for both latex and ascii. No whitespace is allowed between command
and the first argument, nor between the first and second arguments.
The following example is from [Link]:
\deqn{p(x) = \frac{\lambda^x e^{-\lambda}}{x!}}{%
p(x) = \lambda^x exp(-\lambda)/x!}
for \eqn{x = 0, 1, 2, \ldots}.
For text on-line help we get
p(x) = lambda^x exp(-lambda)/x!
for x = 0, 1, 2, ....
Greek letters (both cases) will be rendered in HTML if preceded by a backslash, \
dots and \ldots will be rendered as ellipses and \sqrt, \ge and \le as
mathematical symbols.
Note that only basic LaTeX can be used, there being no provision to specify
LaTeX style files such as the AMS extensions.
2.7 Figures
To include figures in help pages, use the \figure markup. There are three forms.
The two commonly used simple forms are \figure{filename} and \
figure{filename}{alternate text}. This will include a copy of the figure in
either HTML 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 HTML or LaTeX.
The expert form is \figure{filename}{options: string}. (The word ‘options:’
must be typed exactly as shown and followed by at least one space.) In this form,
the string is copied into the HTML img tag as attributes following the src attribute,
or into the second argument of the \Figure macro in LaTeX, which by default is
used as options to an \includegraphics 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 HTML/LaTeX is used.
For example, to include a logo in both HTML (using the simple form) and LaTeX
(using the expert form), the following could be used:
\if{html}{\figure{[Link]}{options: width=100 alt="R logo"}}
\if{latex}{\figure{[Link]}{options: width=0.5in}}
The files containing the figures should be stored in the directory man/figures.
Files with extensions .jpg, .jpeg, .pdf, .png and .svg from that directory
will be copied to the help/figures directory at install time. (Figures in PDF
format will not display in most HTML browsers, but might be the best choice in
reference manuals.) Specify the filename relative to man/figures in the \
figure directive.
2.8 Insertions
Use \R for the R system itself. Use \dots for the dots in function argument lists ‘…’,
and \ldots for ellipsis dots in ordinary text.116 These can be followed by {}, and
should be unless followed by whitespace.
After an unescaped ‘%’, 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 “help” invisible.
You can produce a backslash (‘\’) by escaping it by another backslash. (Note
that \cr is used for generating line breaks.)
The “comment” character ‘%’ and unpaired braces117 almost always need to be
escaped by ‘\’, and ‘\\’ 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 “Parsing Rd files” for details – in particular braces should
not be escaped in quoted strings.
All of ‘% { } \’ should be escaped in LaTeX-like text.
Text which might need to be represented differently in different encodings should
be marked by \enc, e.g. \enc{Jöreskog}{Joreskog} (with no whitespace between
the braces) where the first argument will be used where encodings are allowed and
the second should be ASCII (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.)
2.9 Indices
The \alias command (see Documenting functions) is used to specify the “topics”
documented, which should include all R objects in a package such as functions and
variables, data sets, and S4 classes and methods (see Documenting S4 classes and
methods). The on-line help system searches the index data base consisting of all
alias topics.
In addition, it is possible to provide “concept index entries” using \concept, which
can be used for [Link]() lookups. E.g., file [Link] in the standard
package stats contains
\concept{Kendall correlation coefficient}
\concept{Pearson correlation coefficient}
\concept{Spearman correlation coefficient}
so that e.g. ??Spearman will succeed in finding the help page for the test for
association between paired samples using Spearman’s rho.
(Note that [Link]() only uses “sections” of documentation objects with no
additional markup.)
Each \concept entry should give a single index term (word or phrase), and not use
any Rd markup.
If you want to cross reference such items from other help files via \link, you need
to use \alias and not \concept.
Packages may also define their own common macros; these would be stored in
an .Rd file in man/macros in the package source and will be installed
into help/macros when the package is installed. A package may also use the
macros from a different package by listing the other package in the ‘RdMacros’
field in the DESCRIPTION file.
2.14 Encoding
Rd files are text files and so it is impossible to deduce the encoding they are
written in unless ASCII: files with 8-bit characters could be UTF-8, Latin-1, Latin-
9, KOI8-R, EUC-JP, etc. So an \encoding{} section must be used to specify the
encoding if it is not ASCII. (The \encoding{} section must be on a line by itself,
and in particular one containing no non-ASCII characters. The encoding declared
in the DESCRIPTION file will be used if none is declared in the file.) The Rd files
are converted to UTF-8 before parsing and so the preferred encoding for the files
themselves is now UTF-8.
Wherever possible, avoid non-ASCII chars in Rd files, and even symbols such as
‘<’, ‘>’, ‘$’, ‘^’, ‘&’, ‘|’, ‘@’, ‘~’, and ‘*’ outside ‘verbatim’ environments (since
they may disappear in fonts designed to render text).
(Function showNonASCIIfile in package tools can help in finding non-ASCII bytes
in the files.)
For convenience, encoding names ‘latin1’ and ‘latin2’ are always
recognized: these and ‘UTF-8’ 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 characters118 is fairly low. Using LaTeX inputenx (see ?Rd2pdf in R) will
give greater coverage of UTF-8.
The \enc command (see Insertions) can be used to provide transliterations which
will be used in conversions that do not support the declared encoding.
The LaTeX conversion converts the file to UTF-8 from the declared encoding, and
includes a
\inputencoding{utf8}
command, and this needs to be matched by a suitable invocation of the \
usepackage{inputenc} command. The R utility R CMD Rd2pdf looks at the converted
code and includes the encodings used: it might for example use
\usepackage[utf8]{inputenc}
(Use of utf8 as an encoding requires LaTeX dated 2003/12/01 or later. Also, the
use of Cyrillic characters in ‘UTF-8’ appears to also need ‘\
usepackage[T2A]{fontenc}’, and R CMD Rd2pdf includes this conditionally
on the file [Link] being present and environment
variable _R_CYRILLIC_TEX_ being set.)
Note that this mechanism works best with Latin letters: the coverage of UTF-8 in
LaTeX is quite low.
Next: Profiling R code for speed, Previous: Tidying and profiling R code,
Up: Tidying and profiling R code [Contents][Index]
Next: Profiling R code for memory use, Previous: Tidying R code, Up: Tidying
and profiling R code [Contents][Index]
% self % total
self seconds total seconds name
5.7 1.44 7.5 1.88 "inherits"
4.0 1.02 96.3 24.30 "nls"
3.6 0.92 3.6 0.92 "$"
3.5 0.88 28.1 7.10 "[Link]"
3.2 0.80 15.0 3.78 "nlsModel"
2.8 0.70 9.8 2.46 "[Link]"
2.7 0.68 12.3 3.10 "assign"
2.5 0.64 2.5 0.64 ".Fortran"
2.5 0.62 7.1 1.80 "[Link]"
2.2 0.56 33.9 8.56 "<Anonymous>"
2.1 0.54 5.9 1.48 "unlist"
2.1 0.52 7.9 2.00 "FUN"
...
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.
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.
Profiling short runs can sometimes give misleading results. R from time to time
performs garbage collection 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 gc() with a profiling run without a preceding call to gc.
More detailed analysis of the output can be achieved by the tools in
the CRAN packages proftools and profr: in particular these allow call graphs to
be studied.
Next: Profiling compiled code, Previous: Profiling R code for speed, Up: Tidying
and profiling R code [Contents][Index]
Next: Tracking memory allocations, Previous: Profiling R code for memory use,
Up: Profiling R code for memory use [Contents][Index]
3.3.1 Memory statistics from Rprof
The sampling profiler Rprof described in the previous section can be given the
option [Link]=TRUE. 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 duplicate, which is
called to copy R objects. summaryRprof 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 gctorture 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.
Previous: Tracking memory allocations, Up: Profiling R code for memory use
[Contents][Index]
3.3.3 Tracing copies of an object
The third method of memory profiling involves tracing copies made of a specific
(presumably large) R object. Calling tracemem on an object marks it so that a
message is printed to standard output when the object is copied via duplicate 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 tracemem on these components.
In the example above we can run tracemem on the data frame st
> tracemem(st)
[1] "<0x9abd5e0>"
> [Link] <- boot(rs, [Link], R = 4)
memtrace[0x9abd5e0->0x92a6d08]: statistic boot
memtrace[0x92a6d08->0x92a6d80]: $<-.[Link] $<- statistic boot
memtrace[0x92a6d80->0x92a6df8]: $<-.[Link] $<- statistic boot
memtrace[0x9abd5e0->0x9271318]: statistic boot
memtrace[0x9271318->0x9271390]: $<-.[Link] $<- statistic boot
memtrace[0x9271390->0x9271408]: $<-.[Link] $<- statistic boot
memtrace[0x9abd5e0->0x914f558]: statistic boot
memtrace[0x914f558->0x914f5f8]: $<-.[Link] $<- statistic boot
memtrace[0x914f5f8->0x914f670]: $<-.[Link] $<- statistic boot
memtrace[0x9abd5e0->0x972cbf0]: statistic boot
memtrace[0x972cbf0->0x972cc68]: $<-.[Link] $<- statistic boot
memtrace[0x972cc68->0x972cd08]: $<-.[Link] $<- statistic boot
memtrace[0x9abd5e0->0x98ead98]: statistic boot
memtrace[0x98ead98->0x98eae10]: $<-.[Link] $<- statistic boot
memtrace[0x98eae10->0x98eae88]: $<-.[Link] $<- statistic boot
The object is duplicated fifteen times, three times for each of the R+1 calls
to [Link]. This is surprising, since none of the duplications happen inside nls.
Stepping through [Link] in the debugger shows that all three happen in the line
st$Time <- st$fit + rs[i]
Data frames are slower than matrices and this is an example of why.
Using tracemem(st$Viscosity) does not reveal any additional copying.
Previous: Profiling R code for memory use, Up: Tidying and profiling R code
[Contents][Index]
Next: macOS, Previous: Profiling compiled code, Up: Profiling compiled code
[Contents][Index]
3.4.1 Linux
The oprofile project has two modes of operation. In what is now called ‘legacy’
mode, it is uses a daemon to collect information on a process (see below). Since
version 0.9.8 (August 2012), the preferred mode is to use operf, so we discuss that
first. The modes differ in how the profiling data is collected: it is analysed by tools
such as opreport and oppannote in both.
Here is an example on x86_64 Linux using R 3.0.2. File pvec.R contains the part
of the examples from pvec in package parallel:
library(parallel)
N <- 1e6
dates <- sprintf('%04d-%02d-%02d', [Link](2000+rnorm(N)),
[Link](runif(N, 1, 12)), [Link](runif(N, 1, 28)))
[Link](a <- [Link](dates, format = "%Y-%m-%d"))
with timings from the final step
user system elapsed
0.371 0.237 0.612
R-level profiling by Rprof shows
[Link] [Link] [Link] [Link]
"strptime" 1.70 41.06 1.70 41.06
"[Link]" 1.40 33.82 1.42 34.30
"sprintf" 0.74 17.87 0.98 23.67
...
so the conversion from character to POSIXlt takes most of the time.
This can be run under operf and analysed by
operf R -f pvec.R
opreport
opreport -l /path/to/R_HOME/bin/exec/R
opannotate --source /path/to/R_HOME/bin/exec/R
## And for the system time
opreport -l /lib64/[Link].6
The first report shows where (which library etc) the time was spent:
CPU_CLK_UNHALT...|
samples| %|
------------------
166761 99.9161 Rdev
CPU_CLK_UNHALT...|
samples| %|
------------------
70586 42.3276 no-vmlinux
56963 34.1585 [Link]
36922 22.1407 R
1584 0.9499 [Link]
624 0.3742 [Link]
...
The rest of the output is voluminous, and only extracts are shown below.
Most of the time within R is spent in
samples % image name symbol name
10397 28.5123 R R_gc_internal
5683 15.5848 R do_sprintf
3036 8.3258 R do_asPOSIXct
2427 6.6557 R do_strptime
2421 6.6392 R Rf_mkCharLenCE
1480 4.0587 R w_strptime_internal
1202 3.2963 R Rf_qnorm5
1165 3.1948 R unif_rand
675 1.8511 R mktime0
617 1.6920 R makelt
617 1.6920 R validate_tm
584 1.6015 R day_of_the_week
...
opannotate shows that 31% of the time in R is spent in memory.c, 21%
in datetime.c and 7% in Rstrptime.h. The analysis for libc showed that
calls to wcsftime dominated, so those calls were cached for R 3.0.3: the time spent
in no-vmlinux (the kernel) was reduced dramatically.
On platforms which support it, call graphs can be produced by opcontrol --
callgraph if collected via operf --callgraph.
You can select shared objects to be profiled with sprof by setting the environment
variable LD_PROFILE. For example
% setenv LD_PROFILE /path/to/R_HOME/library/stats/libs/[Link]
R
... run the boot example
% sprof /path/to/R_HOME/library/stats/libs/[Link] \
/var/tmp/path/to/R_HOME/library/stats/libs/[Link]
Flat profile:
rm /var/tmp/path/to/R_HOME/library/stats/libs/[Link]
... to clean up ...
It is possible that root access is needed to create the directories used for the profile
data.
Next: System and foreign language interfaces, Previous: Tidying and profiling R
code, Up: Writing R Extensions [Contents][Index]
4 Debugging
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.
Browsing
Debugging R code
Checking memory access
Debugging compiled code
Using Link-time Optimization
4.1 Browsing
Most of the R-level debugging facilities are based around the built-in browser. This
can be used directly by inserting a call to browser() into the code of a function (for
example, using fix(my_function) ). When code execution reaches that point in the
function, control returns to the R console with a special prompt. For example
> fix([Link]) ## insert browser() call after for() loop
> summary(women)
Called from: [Link](women)
Browse[1]> ls()
[1] "digits" "i" "lbs" "lw" "maxsum" "nm" "nr" "nv"
[9] "object" "sms" "z"
Browse[1]> maxsum
[1] 7
Browse[1]>
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
> rm([Link])
At the browser prompt one can enter any R expression, so for example ls() lists
the objects in the current frame, and entering the name of an object will121 print it.
The following commands are also accepted
n
Enter ‘step-through’ mode. In this mode, hitting return executes the next line
of code (more precisely one line and any continuation lines). Typing c will
continue to the end of the current context, e.g. to the end of the current loop
or function.
c
In normal mode, this quits the browser and continues execution, and just
return works in the same way. cont is a synonym.
where
This prints the call stack. For example
> summary(women)
Called from: [Link](women)
Browse[1]> where
where 1: [Link](women)
where 2: summary(women)
Browse[1]>
Q
Quit both the browser and the current expression, and return to the top-level
prompt.
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 <<- if the name is not already in
scope).
Selection:
which is very similar to [Link]. However, we can examine the state of the
program directly, without dumping and re-loading the dump. As its help page
says, recover can be routinely used as the error action in place
of [Link] and [Link], since it behaves like [Link] in non-interactive
use.
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 debug. 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
> debug([Link])
> glm(resp ~ 0 + predictor, family = binomial(link ="log"))
debugging in: [Link](x = X, y = Y, weights = weights, start = start,
etastart = etastart,
mustart = mustart, offset = offset, family = family, control = control,
intercept = attr(mt, "intercept") > 0)
debug: {
## lists the whole function
Browse[1]>
debug: x <- [Link](x)
...
Browse[1]> start
[1] -2.235357e-06
debug: eta <- drop(x %*% start)
Browse[1]> 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]>
debug: mu <- linkinv(eta <- eta + offset)
Browse[1]> 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
(The prompt Browse[1]> 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 browser().)
debug can be used for hidden functions and S3 methods by
e.g. debug(stats:::[Link]). (It cannot be used for S4 methods, but an
alternative is given on the help page for debug.) Sometimes you want to debug a
function defined inside another function, e.g. the function arimafn defined
inside arima. To do so, set debug on the outer function (here arima) and step
through it until the inner function has been defined. Then call debug on the inner
function (and use c to get out of step-through mode in the outer function).
To remove debugging of a function, call undebug with the argument previously
given to debug; debugging otherwise lasts for the rest of the R session (or until the
function is edited or otherwise replaced).
trace can be used to temporarily insert debugging code into a function, for
example to insert a call to browser() just before the point of the error. To return to
our running example
## first get a numbered listing of the expressions of the function
> page([Link](body([Link])), method="print")
> trace([Link], browser, at=22)
Tracing function "[Link]" in package "stats"
[1] "[Link]"
> glm(resp ~ 0 + predictor, family = binomial(link ="log"))
Tracing [Link](x = X, y = Y, weights = weights, start = start,
etastart = etastart, .... step 22
Called from: eval(expr, envir, enclos)
Browse[1]> n
## and single-step from here.
> untrace([Link])
For your own functions, it may be as easy to use fix to insert temporary code,
but trace can help with functions in a namespace (as can fixInNamespace).
Alternatively, use trace(,edit=TRUE) to insert code visually.
Next: Using valgrind, Previous: Checking memory access, Up: Checking memory
access [Contents][Index]
4.3.1 Using gctorture
The function gctorture2 provides more refined control over the GC torture
process. Its arguments step, wait and inhibit_release are documented on its help
page. Environment variables can also be used at the start of the R session to turn on
GC torture: R_GCTORTURE corresponds to the step argument
to gctorture2, R_GCTORTURE_WAIT to wait,
and R_GCTORTURE_INHIBIT_RELEASE to inhibit_release.
If R is configured with --enable-strict-barrier then a variety of tests for
the integrity of the write barrier are enabled. In addition tests to help detect protect
issues are enabled:
All GCs are full GCs.
New nodes in small node pages are marked as NEWSXP on creation.
After a GC all free nodes that are not of type NEWSXP are marked as
type FREESXP and their previous type is recorded.
Most calls to accessor functions check their SEXP inputs and SEXP outputs
and signal an error if a FREESXP is found. The address of the node and the old
type are included in the error message.
R CMD check --use-gct can be set to use gctorture2(n) rather
than gctorture(TRUE) by setting environment variable _R_CHECK_GCT_N_ to a
positive integer value to be used as n.
Used with a debugger and with gctorture or gctorture2 this mechanism can be
helpful in isolating memory protect problems.
Next: Using the Address Sanitizer, Previous: Using gctorture, Up: Checking
memory access [Contents][Index]
4.3.2 Using valgrind
Previous: Using the Address Sanitizer, Up: Using the Address Sanitizer
[Contents][Index]
[Link] Using the Leak Sanitizer
For x86_64 Linux there is a leak sanitizer, ‘LSan’:
see [Link] This
is available on recent versions of gcc and clang, and where available is compiled in
as part of ASan.
One way to invoke this from an ASan-enabled build is by the environment variable
ASAN_OPTIONS='detect_leaks=1'
However, this was made the default as from clang 3.5 and gcc 5.1.0.
When LSan is enabled, leaks give the process a failure error status (by default 23).
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 ASan all runs will have a
failure error status (which may include running R as part of building R itself).
To disable this, allocation-mismatch checking and some strict C++ checking use
setenv ASAN_OPTIONS
‘alloc_dealloc_mismatch=0:detect_leaks=0:detect_odr_violation=0’
LSan also has a ‘stand-alone’ mode where it is compiled in using -
fsanitize=leak and avoids the run-time overhead of ASan.
Next: Other analyses with ‘clang’, Previous: Using the Address Sanitizer,
Up: Checking memory access [Contents][Index]
4.3.4 Using the Undefined Behaviour Sanitizer
‘Undefined behaviour’ is where the language standard does not require particular
behaviour from the compiler. Examples include division by zero (where for
doubles R requires the ISO/IEC 60559 behaviour but C/C++ do not), use of zero-
length arrays, shifts too far for signed types (e.g. int x, y; y = x << 31;), 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 NaN or infinity to
type int or NA_INTEGER to an unsigned type such as size_t. Also common is y[x -
1] forgetting that x might be NA_INTEGER.
Next: Other analyses with ‘gcc’, Previous: Using the Undefined Behaviour
Sanitizer, Up: Checking memory access [Contents][Index]
4.3.5 Other analyses with ‘clang’
Next: Using ‘Dr. Memory’, Previous: Other analyses with ‘clang’, Up: Checking
memory access [Contents][Index]
4.3.6 Other analyses with ‘gcc’
GCC 10 introduced a new flag -fanalyzer which does static analysis during
compilation, currently for C code. It is regarded as experimental 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.
See [Link] (o
r the documentation for your version of gcc if later)
and [Link]
Next: Fortran array bounds checking, Previous: Other analyses with ‘gcc’,
Up: Checking memory access [Contents][Index]
4.3.7 Using ‘Dr. Memory’
Most of the Fortran compilers used with R allow code to be compiled with
checking of array bounds: for example gfortran has option -fbounds-check.
This will give an error when the upper or lower bound is exceeded, e.g.
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
One does need to be aware that lazy programmers often specify Fortran dimensions
as 1 rather than * or a real bound and these will be reported (as may * dimensions)
It is easy to arrange to use this check on just the code in your package: add
to ~/.R/Makevars something like (for gfortran)
FFLAGS = -g -O2 -mtune=native -fbounds-check
when you run R CMD check.
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 Fortran character strings).
Traceback:
1: .identC(class1[[1]], class2)
2: possibleExtends(class(sloti), classi, ClassDef2 = getClassDef(classi,
where = where))
3: validObject(t(cu))
4: stopifnot(validObject(cu <- as(tu, "dtCMatrix")), 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
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.)
A fairly common cause of such crashes is a package which uses .C or .Fortran and
writes beyond (at either end) one of the arguments it is passed. There is a good way
to detect this: using options(CBoundsCheck = TRUE) (which can be selected via the
environment variable R_C_BOUNDS_CHECK=yes) changes the
way .C and .Fortran work to check if the compiled code writes in the 64 bytes at
either end of an argument.
Another cause of a ‘crash’ 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
> .C("aaa")
Error: segfault from C stack overflow
>
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.
If you have a crash which gives a core dump you can use something like
gdb /path/to/R/bin/exec/R core.12345
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
$ R -d gdb --vanilla
...
gdb> run
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
> for(i in 1:1e7) x <- rnorm(100)
[hit Ctrl-C]
Program received signal SIGINT, Interrupt.
0x00397682 in _int_free () from /lib/tls/[Link].6
(gdb) where
#0 0x00397682 in _int_free () from /lib/tls/[Link].6
#1 0x00397eba in free () from /lib/tls/[Link].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
...
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
gdb -p pid
where pid is the id of the R executable or front-end process and can be found from
within a running R process by calling [Link]() or from a process monitor.
This stops the process so its state can be examined: use continue to resume
execution.
Some “tricks” worth knowing follow:
Finding entry points in dynamically loaded code
Inspecting R objects when debugging
Debugging on macOS
$[Link]
[1] "1" "2" "3"
$class
[1] "[Link]"
$3 = void
To find out where exactly the corresponding information is stored, one needs to go
“deeper”:
(gdb) set $a = $1->attrib
(gdb) p $a->[Link]->[Link]->[Link].c
$4 = 0x405d40e8 "names"
(gdb) p $a->[Link]->[Link].s[1]->[Link].c
$5 = 0x40634378 "b"
(gdb) p $1->[Link].s[0]->[Link].i[0]
$6 = 1
(gdb) p $1->[Link].s[1]->[Link].i[1]
$7 = 5
Another alternative is the R_inspect function which shows the low-level structure
of the objects recursively (addresses differ from the above as this example is
created on another machine):
(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] "names"
@100954dc0 16 STRSXP g0c2 [NAM(2)] (len=2, tl=0)
@10099df28 09 CHARSXP g0c1 [MARK,gp=0x21] "a"
@10095e518 09 CHARSXP g0c1 [MARK,gp=0x21] "b"
TAG: @100859e60 01 SYMSXP g0c0 [MARK,NAM(2),gp=0x4000] "[Link]"
@102a6f868 13 INTSXP g0c1 [NAM(2)] (len=2, tl=1) -2147483648,-3
TAG: @10083c948 01 SYMSXP g0c0 [MARK,gp=0x4000] "class"
@102a6f838 16 STRSXP g0c1 [NAM(2)] (len=1, tl=1)
@1008c6d48 09 CHARSXP g0c2 [MARK,gp=0x21,ATT] "[Link]"
In general the representation of each object follows the format:
@<address> <type-nr> <type-name> <gc-info> [<flags>] ...
For a more fine-grained control over the depth of the recursion and the output of
vectors R_inspect3 takes additional two character() parameters: maximum depth
and the maximal number of elements that will be printed for scalar vectors. The
defaults in R_inspect are currently -1 (no limit) and 5 respectively.
*info, work1)
1
Warning: Missing actual argument for argument ‘dum’ at (1)
and
all.f:1663:72:
Next: The R API: entry points for C code, Previous: Debugging, Up: Writing R
Extensions [Contents][Index]
Next: Interface functions .C and .Fortran, Previous: System and foreign language
interfaces, Up: System and foreign language interfaces [Contents][Index]
Next: [Link] and [Link], Previous: Operating system access, Up: System
and foreign language interfaces [Contents][Index]
These two functions provide an interface to compiled code that has been linked
into R, either at build time or via [Link] (see [Link] and [Link]). They are
primarily intended for compiled C and Fortran code respectively, but
the .C function can be used with other languages which can generate C interfaces,
for example C++ (see Interfacing C++ code).
The first argument to each function is a character string specifying the symbol
name as known137 to C or Fortran, that is the function or subroutine name. (That the
symbol is loaded can be tested by, for example, [Link]("cg"). Use the name
you pass to .C or .Fortran rather than the translated symbol name.)
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).
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.
R storage mode C type Fortran type
logical int * INTEGER
integer int * INTEGER
double double * DOUBLE PRECISION
complex Rcomplex * DOUBLE COMPLEX
character char ** CHARACTER(255)
raw unsigned char * none
On all R platforms int and INTEGER are 32-bit. Code ported from S-PLUS (which
uses long * for logical and integer) will not work on all 64-bit platforms
(although it may appear to work on some, including 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.
C type Rcomplex is a structure with double members r and i defined in the header
file R_ext/Complex.h.138 (On most platforms this is stored in a way compatible
with the C99 double complex type: however, it may not be possible to
pass Rcomplex to a C99 function expecting a double complex argument. Nor need it
be compatible with a C++ complex type. Moreover, the compatibility can depend
on the optimization level set for the compiler.)
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 .C, but it is much
better to use one of the other interfaces.
It is possible to pass numeric vectors of storage mode double to C as float * or to
Fortran as REAL by setting the attribute Csingle, most conveniently by using the R
functions [Link], single or mode. This is intended only to be used to aid
interfacing existing C or Fortran code.
Logical values are sent as 0 (FALSE), 1 (TRUE) or INT_MIN = -2147483648 (NA, but
only if NAOK is true), and the compiled code should return one of these three values.
(Non-zero values other than INT_MIN are mapped to TRUE.) Note that the use of int
* 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.
Unless formal argument NAOK is true, all the other arguments are checked for
missing values NA and for the IEEE special values NaN, Inf and -Inf, and the
presence of any of these generates an error. If it is true, these values are passed
unchecked.
Argument PACKAGE confines the search for the symbol name to a specific shared
object (or use "base" 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) useDynLib directive will be used.)
Note that the compiled code should not return anything except through its
arguments: C functions should be of type void and Fortran subprograms should be
subroutines.
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 .C by
void convolve(double *a, int *na, double *b, int *nb, double *ab)
{
int nab = *na + *nb - 1;
void
R_init_mylib(DllInfo *info)
{
/* Register routines,
allocate resources. */
}
void
R_unload_mylib(DllInfo *info)
{
/* Release resources. */
}
If a shared object/DLL is loaded more than once the most recent version is
used.140 More generally, if the same symbol name appears in several shared
objects, the most recently loaded occurrence is used. The PACKAGE argument and
registration (see the next section) provide good ways to avoid any ambiguity in
which occurrence is meant.
On Unix-alikes the paths used to resolve dynamically linked dependent libraries
are fixed (for security reasons) when the process is launched, so [Link] will only
look for such libraries in the locations set by the R shell script
(via etc/ldpaths) and in the OS-specific defaults.
Windows allows more control (and less security) over where dependent DLLs are
looked for. On all versions this includes the PATH 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 via the DLLpath argument to [Link]. This is (by default) used
by [Link] to include the package’s libs/x64 directory in the DLL search
path.
Next: Creating shared objects, Previous: [Link] and [Link], Up: System and
foreign language interfaces [Contents][Index]
The splines package was converted to use symbol registration in 2001, but we can
use it as an example143 of what needs to be done for a small package.
Find the relevant entry points. This is somewhat OS-specific, but something
like the following should be possible at the OS command-line
nm -g /path/to/[Link] | grep " T "
0000000000002670 T _spline_basis
0000000000001ec0 T _spline_value
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 .Call.
Alternatively, examine the package’s R code for
all .C, .Fortran, .Call and .External calls.
Construct the registration table. First write skeleton registration code,
conventionally in file src/init.c (or at the end of the only C source file
in the package: if included in a C++ file the ‘R_init’ function would need
to be declared extern "C"):
#include <stdlib.h> // for NULL
#include <R_ext/Rdynload.h>
#define CALLDEF(name, n) {#name, (DL_FUNC) &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);
}
and then replace the ? in the skeleton with the actual numbers of arguments.
You will need to add declarations (also known as ‘prototypes’) 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 init.c, for example splines.h containing
#include <Rinternals.h> // 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);
Tools are available to extract declarations, at least for C and C++ code: see
the help file for package_native_routine_registration_skeleton in
package tools. Here we could have used
cproto -I/path/to/R/include -e splines.c
For examples of registering other types of calls, see
packages graphics and stats. In particular, when registering entry points
for .Fortran one needs declarations as if called from C, such as
#include <R_ext/RS.h>
void F77_NAME(supsmu)(int *n, double *x, double *y,
double *w, int *iper, double *span,
double *alpha,
double *smo, double *sc, double *edf);
gfortran 8.4, 9.2 and later can help generate such prototypes with its flag -
fc-prototypes-external (although one will need to replace the
hard-coded trailing underscore with the F77_NAME macro).
One can get away with inaccurate argument lists in the declarations: it is
easy to specify the arguments for .Call (all SEXP) and .External (one SEXP)
and as the arguments for .C and .Fortran are all pointers, specifying them
as void * 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 – and C23 will require correct arguments.)
Using -fc-prototypes-external will give a prototype
using int_least32_t *lgl for Fortran LOGICAL LGL, but this is not portable
and traditionally it has been assumed that the C/C++ equivalent was int
*lgl. If adding a declaration just to register a .Fortran call, the most
portable version is void *lgl.
(Optional but highly recommended.) Restrict .Call etc to use the symbols
you chose to register by editing src/init.c to contain
void R_init_splines(DllInfo *dll)
{
R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
A skeleton for the steps so far can be made
using package_native_routine_registration_skeleton in package tools. This will
optionally create declarations based on the usage in the R code.
The remaining steps are optional but recommended.
Edit the NAMESPACE file to create R objects for the registered symbols:
useDynLib(splines, .registration = TRUE, .fixes = "C_")
Find all the relevant calls in the R code and edit them to use the R objects.
This entailed changing the lines
temp <- .Call("spline_basis", knots, ord, x, derivs, PACKAGE =
"splines")
y[accept] <- .Call("spline_value", knots, coeff, ord,
x[accept], deriv, PACKAGE = "splines")
y = .Call("spline_value", knots, coef(object), ord, x, deriv,
PACKAGE = "splines")
to
temp <- .Call(C_spline_basis, knots, ord, x, derivs)
y[accept] <- .Call(C_spline_value, knots, coeff, ord,
x[accept], deriv)
y = .Call(C_spline_value, knots, coef(object), ord, x, deriv)
Check that there is no exportPattern directive which unintentionally exports
the newly created R objects.
Restrict .Call to use the R symbols by editing src/init.c to contain
void R_init_splines(DllInfo *dll)
{
R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
R_forceSymbols(dll, TRUE);
}
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
nm -g /path/to/[Link] | grep " T "
0000000000002e00 T _R_init_splines
00000000000025e0 T _spline_basis
0000000000001e20 T _spline_value
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 static.
Now that the two relevant entry points are only accessed via the registration
table, we can hide them. There are two ways to do so on some Unix-alikes.
We can hide individual entry points via
#include <R_ext/Visibility.h>
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)
…
Alternatively, we can change the default visibility for all C symbols by
including
PKG_CFLAGS = $(C_VISIBILITY)
in src/Makevars, and then we need to allow registration by
declaring R_init_splines to be visible:
#include <R_ext/Visibility.h>
void attribute_visible
R_init_splines(DllInfo *dll)
…
See Controlling visibility for more details, including using Fortran code and
ways to restrict visibility on Windows.
We end up with a file src/init.c containing
#include <stdlib.h>
#include <R_ext/Rdynload.h>
#include <R_ext/Visibility.h> // optional
#include "splines.h"
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);
}
Next: Interfacing C++ code, Previous: Registering native routines, Up: System and
foreign language interfaces [Contents][Index]
Next: Fortran I/O, Previous: Creating shared objects, Up: System and foreign
language interfaces [Contents][Index]
class X {
public: X (); ~X ();
};
class Y {
public: Y (); ~Y ();
};
// [Link]
#include <R.h>
#include "X.h"
static Y y;
To use with R, the only thing we have to do is writing a wrapper function and
ensuring that the function is enclosed in
extern "C" {
}
For example,
// X_main.cpp:
#include "X.h"
extern "C" {
void X_main () {
X x;
}
} // extern "C"
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 Y) are not called. On a properly
configured system, one can simply use
R CMD SHLIB [Link] X_main.cpp
to create the shared object, typically [Link] (the file name extension may be
different on your platform). Now starting R yields
R version 2.14.1 Patched (2012-01-16 r58124)
Copyright (C) 2012 The R Foundation for Statistical Computing
...
Type "q()" to quit R.
Quite a lot of external C++ software is header-only (e.g. most of the Boost
‘libraries’ including all those supplied by package BH, and most of Armadillo as
supplied by package RcppArmadillo) and so is compiled when an R package
which uses it is installed. This causes few problems.
A small number of external libraries used in R packages have a C++ interface to a
library of compiled code, e.g. packages sf and rjags. This raises many more
problems! The C++ interface uses name-mangling and the ABI147 may depend on
the compiler, version and even C++ defines148, so requires the package C++ code to
be compiled in exactly the same way as the library (and what that was is often
undocumented).
Even fewer external libraries use C++ internally but present a C interface, such
as rgeos. These require the C++ runtime library to be linked into the package’s
shared object/DLL, and this is best done by including a dummy C++ file in the
package sources.
There is a trend to link to the C++ interfaces offered by C software such
as hdf5, pcre and ImageMagick. 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.
Next: Linking to other packages, Previous: Interfacing C++ code, Up: System and
foreign language interfaces [Contents][Index]
#ifdef _WIN32
// gfortran I/O initialization sets these to _O_BINARY
setmode(1, _O_TEXT); /* stdout */
setmode(2, _O_TEXT); /* stderr */
#endif
}
in the file used for native symbol registration.)
Next: Handling R objects in C, Previous: Fortran I/O, Up: System and foreign
language interfaces [Contents][Index]
before: [Link].a
[Link].a: [Link]
and then installing package packA will make and use the import library
for [Link]. (One way to prepare the exports file is to
use [Link].)
loading [Link] which depends on [Link].
If [Link] was used by package packB (because it is in
fact [Link] or [Link] depends on it) and packB has been
loaded before packA, then nothing more needs to be done as [Link] will
already be loaded into the R executable. (This is the most common
scenario.)
More generally, we can use the DLLpath argument to [Link] to
ensure that [Link] is found, for example by setting
[Link]("packA", pkg, lib,
DLLpath = [Link]("libs", package="packB"))
Note that DLLpath can only set one path, and so for linking to two or more
packages you would need to resort to setting environment variable PATH.
SEXP ab;
....
ab = PROTECT(allocVector(REALSXP, 2));
REAL(ab)[0] = 123.45;
REAL(ab)[1] = 67.89;
UNPROTECT(1);
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 ab 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.
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 PROTECT everything in sight
and UNPROTECT 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.
There is a less-used macro UNPROTECT_PTR(s) that unprotects the object pointed to
by the SEXP s, 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 PROTECT and UNPROTECT. However, UNPROTECT_PTR is dangerous to use in
combination with UNPROTECT when the same object has been protected multiple
times. It has been superseded by multi-set based
functions R_PreserveInMSet and R_ReleaseFromMSet, which protect objects in a
multi-set created by R_NewPreciousMSet and typically itself protected
using PROTECT. These functions should not be needed outside parsers.
Sometimes an object is changed (for example duplicated, coerced or grown) yet the
current value needs to be protected. For these cases PROTECT_WITH_INDEX saves an
index of the protection location that can be used to replace the protected value
using REPROTECT. For example (from the internal code for optim)
PROTECT_INDEX ipx;
....
PROTECT_WITH_INDEX(s = eval(OS->R_fcall, OS->R_env), &ipx);
REPROTECT(s = coerceVector(s, REALSXP), ipx);
Note that it is dangerous to mix UNPROTECT_PTR also with PROTECT_WITH_INDEX, as
the former changes the protection locations of objects that were protected after the
one being unprotected.
There is another way to avoid the effects of garbage collection: a call
to R_PreserveObject adds an object to an internal list of objects not to be collects,
and a subsequent call to R_ReleaseObject 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’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.
For functions from packages as well as R to safely co-operate in protecting objects,
certain rules have to be followed:
Pointer-protection balance. Calls to PROTECT and UNPROTECT should balance in
each function. A function may only call UNPROTECT or REPROTECT on objects it
has itself protected. Note that the pointer protection stack balance is restored
automatically on non-local transfer of control (See Condition handling and
cleanup code.), as if a call to UNPROTECT was invoked with the right
argument.
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 PROTECT and UNPROTECT calls.
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.
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.
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. PROTECT and PROTECT_WITH_INDEX can be safely
called with unprotected arguments and UNPROTECT does not allocate.
For many purposes it is sufficient to allocate R objects and manipulate those. There
are quite a few allocXxx functions defined in Rinternals.h—you may want to
explore them.
One that is commonly used is allocVector, the C-level equivalent of R-
level vector() and its wrappers such as integer() and character(). One
distinction is that whereas the R functions always initialize the elements of the
vector, allocVector only does so for lists, expressions and character vectors (the
cases where the elements are themselves R objects).
If storage is required for C objects during the calculations this is best allocating by
calling R_alloc; see Memory allocation. 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.
Many R objects have attributes: some of the most useful are classes and
the dim and dimnames that mark objects as matrices or arrays. It can also be helpful
to work with the names attribute of vectors.
To illustrate this, let us write code to take the outer product of two vectors
(which outer and %o% already do). As usual the R code is simple
out <- function(x, y)
{
[Link](x) <- [Link](y) <- "double"
.Call("out", x, y)
}
where we expect x and y to be numeric vectors (possibly integer), possibly with
names. This time we do the coercion in the calling R code.
C code to do the computations is
#include <R.h>
#include <Rinternals.h>
UNPROTECT(2);
return ans;
}
This example introduces several new features.
The getAttrib and setAttrib functions get and set individual attributes. Their
second argument is a SEXP defining the name in the symbol table of the attribute we
want; these and many such symbols are defined in the header
file Rinternals.h.
There are shortcuts here too: the
functions namesgets, dimgets and dimnamesgets are the internal versions of the
default methods of names<-, dim<- and dimnames<- (for vectors and arrays), and
there are functions such
as GetColNames, GetRowNames, GetMatrixDimnames and GetArrayDimnames.
What happens if we want to add an attribute that is not pre-defined? We need to
add a symbol for it via a call to install. Suppose for illustration we wanted to add
an attribute "version" with value 3.0. We could use
SEXP version;
version = PROTECT(allocVector(REALSXP, 1));
REAL(version)[0] = 3.0;
setAttrib(ans, install("version"), version);
UNPROTECT(1);
Using install 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
static SEXP VerSymbol = NULL;
...
if (VerSymbol == NULL) VerSymbol = install("version");
if it is to be done frequently.
This example can be simplified by another convenience function:
SEXP version = PROTECT(ScalarReal(3.0));
setAttrib(ans, install("version"), version);
UNPROTECT(1);
In R the class is just the attribute named "class" so it can be handled as such, but
there is a shortcut classgets. Suppose we want to give the return value in our
example the class "mat". We can use
#include <R.h>
#include <Rinternals.h>
....
SEXP ans, dim, dimnames, class;
....
class = PROTECT(allocVector(STRSXP, 1));
SET_STRING_ELT(class, 0, mkChar("mat"));
classgets(ans, class);
UNPROTECT(4);
return ans;
}
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 mkChar.
Some care is needed with lists, as R moved early on from using LISP-like lists
(now called “pairlists”) to S-like generic vectors. As a result, the appropriate test
for an object of mode list is isNewList, and we need allocVector(VECSXP, n)
and not allocList(n).
List elements can be retrieved or set by direct access to the elements of the generic
vector. Suppose we have a list object
a <- list(f = 1, g = 2, h = 3)
Then we can access a$g as a[[2]] by
double g;
....
g = REAL(VECTOR_ELT(a, 1))[0];
This can rapidly become tedious, and the following function (based on one in
package stats) is very useful:
/* get the list element named str, or return NULL */
Next: Finding and setting variables, Previous: Handling lists, Up: Handling R
objects in C [Contents][Index]
5.9.7 Handling character data
R character vectors are stored as STRSXPs, a vector type like VECSXP where every
element is of type CHARSXP. The CHARSXP elements of STRSXPs are accessed
using STRING_ELT and SET_STRING_ELT.
CHARSXPs are read-only objects and must never be modified. In particular, the C-
style string contained in a CHARSXP should be treated as read-only and for this
reason the CHAR function used to access the character data of
a CHARSXP returns (const char *) (this also allows compilers to issue warnings
about improper use). Since CHARSXPs are immutable, the same CHARSXP can be
shared by any STRSXP needing an element representing the same string. R maintains
a global cache of CHARSXPs so that there is only ever one CHARSXP representing a
given string in memory.
You can obtain a CHARSXP by calling mkChar and providing a nul-terminated C-style
string. This function will return a pre-existing CHARSXP 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 mkCharLen can be used to create
a CHARSXP from part of a buffer and will ensure null-termination.
Note that R character strings are restricted to 2^31 - 1 bytes, and hence so should
the input to mkChar be (C allows longer strings on 64-bit platforms).
It will be usual that all the R objects needed in our C computations are passed as
arguments to .Call or .External, 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 get(name, envir = rho).
SEXP getvar(SEXP name, SEXP rho)
{
SEXP ans;
if(!isString(name) || length(name) != 1)
error("name is not a single string");
if(!isEnvironment(rho))
error("rho should be an environment");
ans = findVar(installChar(STRING_ELT(name, 0)), rho);
Rprintf("first value is %f\n", REAL(ans)[0]);
return R_NilValue;
}
The main work is done by findVar, but to use it we need to install name as a name
in the symbol table. As we wanted the value for internal use, we return NULL.
Similar functions with syntax
void defineVar(SEXP symbol, SEXP value, SEXP rho)
void setVar(SEXP symbol, SEXP value, SEXP rho)
can be used to assign values to R variables. defineVar creates a new binding or
changes the value of an existing binding in the specified environment frame; it is
the analogue of assign(symbol, value, envir = rho, inherits = FALSE), but
unlike assign, defineVar does not make a copy of the
object value.154 setVar searches for an existing binding for symbol in rho or its
enclosing environments. If a binding is found, its value is changed to value.
Otherwise, a new binding with the specified value is created in the global
environment. This corresponds to assign(symbol, value, envir = rho, inherits
= TRUE).
Next: Named objects and copying, Previous: Finding and setting variables,
Up: Handling R objects in C [Contents][Index]
5.9.9 Some convenience functions
Some operations are done so frequently that there are convenience functions to
handle them. (All these are provided via the header file Rinternals.h.)
Suppose we wanted to pass a single logical argument ignore_quotes: we could use
int ign = asLogical(ignore_quotes);
if(ign == NA_LOGICAL) error("'ignore_quotes' must be TRUE or FALSE");
which will do any coercion needed (at least from a vector argument), and
return NA_LOGICAL if the value passed was NA or coercion failed. There are
also asInteger, asReal and asComplex. The function asChar returns a CHARSXP. All
of these functions ignore any elements of an input vector after the first.
To return a length-one real vector we can use
double x;
...
return ScalarReal(x);
and there are versions of this for all the atomic vector types (those for a length-one
character vector being ScalarString with argument a CHARSXP and mkString with
argument const char *).
SEXP ScalarReal(double);
SEXP ScalarInteger(int);
SEXP ScalarLogical(int)
SEXP ScalarRaw(Rbyte);
SEXP ScalarComplex(Rcomplex);
SEXP ScalarString(SEXP);
SEXP mkString(const char *);
Some of the isXXXX functions differ from their apparent R-level counterparts: for
example isVector is true for any atomic vector type (isVectorAtomic) and for lists
and expressions (isVectorList) (with no check on attributes). isMatrix is a test of
a length-2 "dim" attribute.
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);
There are a series of small macros/functions to help construct pairlists and
language objects (whose internal structures just differ by SEXPTYPE).
Function CONS(u, v) is the basic building block: it constructs a pairlist
from u followed by v (which is a pairlist or R_NilValue). LCONS is a variant that
constructs a language object. Functions list1 to list6 construct a pairlist from one
to six items, and lang1 to lang6 do the same for a language object (a function to
call plus zero to five arguments). Functions elt and lastElt find the ith element
and the last element of a pairlist, and nthcdr returns a pointer to the nth position in
the pairlist (whose CAR is the nth item).
Functions str2type and type2str map R length-one character strings to and
from SEXPTYPE numbers, and type2char maps numbers to C character strings.
Semi-internal convenience functions
Previous: Some convenience functions, Up: Some convenience functions
[Contents][Index]
[Link] Semi-internal convenience functions
There is quite a collection of functions that may be used in your C code if you are
willing to adapt to rare “API” changes. These typically contain “workhorses” of
their R counterparts.
Functions any_duplicated and any_duplicated3 are fast versions of
R’s any(duplicated(.)).
Function R_compute_identical corresponds to R’s identical function.
Let us convert our finite convolution example to use .Call. The calling function in
R is
conv <- function(a, b) .Call("convolve2", a, b)
which could hardly be simpler, but as we shall see all the type coercion is
transferred to the C code, which is
#include <R.h>
#include <Rinternals.h>
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 < nab; i++) xab[i] = 0.0;
for(int i = 0; i < na; i++)
for(int j = 0; j < nb; j++) xab[i + j] += xa[i] * xb[j];
UNPROTECT(3);
return ab;
}
Next: Missing and special values, Previous: Calling .Call, Up: Interface
functions .Call and .External [Contents][Index]
We can use the same example to illustrate .External. The R code changes only by
replacing .Call by .External
conv <- function(a, b) .External("convolveE", a, b)
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.
#include <R.h>
#include <Rinternals.h>
a = PROTECT(coerceVector(CADR(args), REALSXP));
b = PROTECT(coerceVector(CADDR(args), REALSXP));
...
}
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
first = CADR(args);
second = CADDR(args);
third = CADDDR(args);
fourth = CAD4R(args);
fifth = CAD5R(args);
provide convenient ways to access the first four arguments. More generally we can
use the CDR and CAR macros as in
args = CDR(args); a = CAR(args);
args = CDR(args); b = CAR(args);
which clearly allows us to extract an unlimited number of arguments
(whereas .Call has a limit, albeit at 65 not a small one).
More usefully, the .External interface provides an easy way to handle calls with a
variable number of arguments, as length(args) will give the number of arguments
supplied (of which the first is ignored). We may need to know the names (‘tags’)
given to the actual arguments, which we can by using the TAG macro and using
something like the following example, that prints the names and the first value of
its arguments if they are vector types.
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)) ? "" : CHAR(PRINTNAME(TAG(args)));
SEXP el = CAR(args);
if (length(el) == 0) {
Rprintf("[%d] ‘%s’ R type, length 0\n", i+1, name);
continue;
}
switch(TYPEOF(el)) {
case REALSXP:
Rprintf("[%d] ‘%s’ %f\n", i+1, name, REAL(el)[0]);
break;
case LGLSXP:
case INTSXP:
Rprintf("[%d] ‘%s’ %d\n", i+1, name, INTEGER(el)[0]);
break;
case CPLXSXP:
{
Rcomplex cpl = COMPLEX(el)[0];
Rprintf("[%d] ‘%s’ %f + %fi\n", i+1, name, cpl.r, cpl.i);
}
break;
case STRSXP:
Rprintf("[%d] ‘%s’ %s\n", i+1, name,
CHAR(STRING_ELT(el, 0)));
break;
default:
Rprintf("[%d] ‘%s’ R type\n", i+1, name);
}
}
return R_NilValue;
}
This can be called by the wrapper function
showArgs <- function(...) invisible(.External("showArgs", ...))
Note that this style of programming is convenient but not necessary, as an
alternative style is
showArgs1 <- function(...) invisible(.Call("showArgs1", list(...)))
The (very similar) C code is in the scripts.
Additional functions for accessing pairlist components are CAAR, CDAR, CDDR,
and CDDDR. These components can be modified
with SETCAR, SETCDR, SETCADR, SETCADDR, SETCADDDR, and SETCAD4R.
One piece of error-checking the .C call does (unless NAOK is true) is to check for
missing (NA) and IEEE special values (Inf, -Inf and NaN) and give an error if any
are found. With the .Call interface these will be passed to our code. In this
example the special values are no problem, as IEC60559 arithmetic will handle
them correctly. In the current implementation this is also true of NA as it is a type
of NaN, but it is unwise to rely on such details. Thus we will re-write the code to
handle NAs using macros defined in R_ext/Arith.h included by R.h.
The code changes are the same in any of the versions of convolve2 or convolveE:
...
for(int i = 0; i < na; i++)
for(int j = 0; j < 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];
...
Note that the ISNA macro, and the similar macros ISNAN (which checks
for NaN or NA) and R_FINITE (which is false for NA and all the special values), only
apply to numeric values of type double. Missingness of integers, logicals and
character strings can be tested by equality to the
constants NA_INTEGER, NA_LOGICAL and NA_STRING. These and NA_REAL can be used to
set elements of R vectors to NA.
The constants R_NaN, R_PosInf and R_NegInf can be used to set doubles to the
special values.
Next: Parsing R code from C, Previous: Interface functions .Call and .External,
Up: System and foreign language interfaces [Contents][Index]
In this section we re-work the example of Becker, Chambers & Wilks (1988,
pp.~205–10) on finding a zero of a univariate function. The R code and an example
are
zero <- function(f, guesses, tol = 1e-7) {
[Link] <- function(x) {
x <- f(x)
if() stop("Need a numeric result")
[Link](x)
}
.Call("zero", body([Link]), [Link](guesses), [Link](tol),
[Link]())
}
We will use a longer example (by Saikat DebRoy) to illustrate the use of
evaluation and .External. 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.
An interpreted R version and an example are
[Link] <- function(expr, theta, rho=[Link]([Link]()))
{
eps <- sqrt(.Machine$[Link])
ans <- eval(substitute(expr), rho)
grad <- matrix(, length(ans), length(theta),
dimnames=list(NULL, theta))
for (i in seq_along(theta)) {
old <- get(theta[i], envir=rho)
delta <- eps * max(1, abs(old))
assign(theta[i], old+delta, envir=rho)
ans1 <- eval(substitute(expr), rho)
assign(theta[i], old, envir=rho)
grad[, i] <- (ans1 - ans)/delta
}
attr(ans, "gradient") <- grad
ans
}
omega <- 1:5; x <- 1; y <- 2
[Link](sin(omega*x*y), c("x", "y"))
where expr is an expression, theta a character vector of variable names and rho the
environment to be used.
For the compiled version the call from R will be
.External("numeric_deriv", expr, theta, rho)
with example usage
.External("numeric_deriv", quote(sin(omega*x*y)),
c("x", "y"), .GlobalEnv)
Note the need to quote the expression to stop it being evaluated in the caller.
Here is the complete C code which we will explain section by section.
#include <R.h>
#include <Rinternals.h>
#include <float.h> /* for DBL_EPSILON */
expr = CADR(args);
if(!isString(theta = CADDR(args)))
error("theta should be of type character");
if(!isEnvironment(rho = CADDDR(args)))
error("rho should be an environment");
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, &status, R_NilValue));
if (status != PARSE_OK) {
UNPROTECT(2);
error("invalid call %s", cmd);
}
/* Loop is needed here as EXPSEXP will be of length > 1 */
for(int i = 0; i < length(cmdexpr); i++)
ans = eval(VECTOR_ELT(cmdexpr, i), R_GlobalEnv);
UNPROTECT(2);
}
return ans;
}
Note that a single line of text may give rise to more than one R expression.
R_ParseVector is essentially the code used to implement parse(text=) at R level.
The first argument is a character vector (corresponding to text) and the second the
maximal number of expressions to parse (corresponding to n). The third argument
is a pointer to a variable of an enumeration type, and it is normal (as parse does) to
regard all values other than PARSE_OK as an error. Other values which might be
returned are PARSE_INCOMPLETE (an incomplete expression was found)
and PARSE_ERROR (a syntax error), in both cases the value returned
being R_NilValue. The fourth argument is a length one character vector to be used
as a filename in error messages, a srcfile object or the R NULL object (as in the
example above). If a srcfile object was used, a srcref attribute would be attached
to the result, containing a list of srcref objects of the same length as the
expression, to allow it to be echoed with its original formatting.
Accessing source references
Next: Vector accessor functions, Previous: Parsing R code from C, Up: System and
foreign language interfaces [Contents][Index]
Previous: External pointers and weak references, Up: External pointers and weak
references [Contents][Index]
5.13.1 An example
Next: Character encoding issues, Previous: External pointers and weak references,
Up: System and foreign language interfaces [Contents][Index]
Previous: Vector accessor functions, Up: System and foreign language interfaces
[Contents][Index]
Next: Generic functions and methods, Previous: System and foreign language
interfaces, Up: Writing R Extensions [Contents][Index]
Next: Error signaling, Previous: The R API: entry points for C code, Up: The
R API: entry points for C code [Contents][Index]
Here R will reclaim the memory at the end of the call to .C, .Call or .External.
Use
char *R_alloc(size_t n, int size)
which allocates n units of size bytes each. A typical usage (from package stats) is
x = (int *) R_alloc(nrows(merge)+2, sizeof(int));
(size_t is defined in stddef.h which the header defining R_alloc includes.)
There is a similar call, S_alloc (named for compatibility with older versions of S)
which zeroes the memory allocated,
char *S_alloc(long n, int size)
and
char *S_realloc(char *p, long new, long old, int size)
which (for new > old) changes the allocation size from old to new units, and zeroes
the additional units. NB: these calls are best avoided as long is insufficient for
large memory allocations on 64-bit Windows (where it is limited to 2^31-1 bytes).
This memory is taken from the heap, and released at the end of
the .C, .Call or .External call. Users can also manage it, by noting the current
position with a call to vmaxget and subsequently clearing memory allocated by a
call to vmaxset. An example might be
void *vmax = vmaxget()
// a loop involving the use of R_alloc at each iteration
vmaxset(vmax)
This is only recommended for experts.
Note that this memory will be freed on error or user interrupt (if allowed:
see Allowing interrupts).
The memory returned is only guaranteed to be aligned as required
for double pointers: take precautions if casting to a pointer which needs more.
There is also
long double *R_allocLD(size_t n)
which is guaranteed to have the 16-byte alignment needed for long double pointers
on some platforms.
These functions should only be used in code called by .C etc, never from front-
ends. They are not thread-safe.
Next: Random number generation, Previous: Memory allocation, Up: The R API:
entry points for C code [Contents][Index]
There are two interface function provided to call error and warning from Fortran
code, in each case with a simple character string argument. They are defined as
subroutine rexit(message)
subroutine rwarn(message)
Messages of more than 255 characters are truncated, with a warning.
Next: Missing and IEEE special values, Previous: Error signaling, Up: The R API:
entry points for C code [Contents][Index]
Next: Printing, Previous: Random number generation, Up: The R API: entry points
for C code [Contents][Index]
Next: Calling C from Fortran and vice versa, Previous: Missing and IEEE special
values, Up: The R API: entry points for C code [Contents][Index]
6.5 Printing
The most useful function for printing from a C routine compiled into R is Rprintf.
This is used in exactly the same way as printf, but is guaranteed to write to R’s
output (which might be a GUI console rather than a file, and can be re-directed
by sink). It is wise to write complete lines (including the "\n") before returning to
R. It is defined in R_ext/Print.h.
The function REprintf is similar but writes on the error stream (stderr) which may
or may not be different from the standard output stream.
Functions Rvprintf and REvprintf are analogues using the vprintf interface.
Because that is a C99159 interface, they are only defined by R_ext/Print.h in
C++ code if the macro R_USE_C99_IN_CXX is defined before it is included or (as
from R 4.0.0) a C++11 compiler is used.
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.
Printing from Fortran
On many systems Fortran write and print statements can be used, but the output
may not interleave well with that of C, and may be invisible on GUI interfaces.
They are not portable and best avoided.
Some subroutines are provided to ease the output of information from Fortran
code.
subroutine dblepr(label, nchar, data, ndata)
subroutine realpr(label, nchar, data, ndata)
subroutine intpr (label, nchar, data, ndata)
and from R 4.0.0,
subroutine labelpr(label, nchar)
subroutine dblepr1(label, nchar, var)
subroutine realpr1(label, nchar, var)
subroutine intpr1 (label, nchar, var)
Here label is a character label of up to 255 characters, nchar is its length (which
can be -1 if the whole label is to be used), data is an array of length at
least ndata of the appropriate type (double
precision, real and integer respectively) and var is a (scalar) variable. These
routines print the label on one line and then print data or var as if it were an R
vector on subsequent line(s). Note that some compilers will give an error or
warning unless data is an array: others will accept a scalar when ndata has value
one or zero. NB: There is no check on the type of data or var, so
using real (including a real constant) instead of double precision will give
incorrect answers.
intpr works with zero ndata so can be used to print a label in earlier versions of R.
Next: Numerical analysis subroutines, Previous: Printing, Up: The R API: entry
points for C code [Contents][Index]
Next: Fortran LOGICAL, Previous: Calling C from Fortran and vice versa,
Up: Calling C from Fortran and vice versa [Contents][Index]
6.6.1 Fortran character strings
Passing character strings from C to Fortran or vice versa is not portable, but can be
done with care. The internal representations are different: a character array in C (or
C++) is nul-terminated so its length can be computed by strlen. Fortran character
arrays are typically stored as an array of bytes and a length. This matters when
passing strings from C to Fortran or vice versa: in many cases one has been able to
get away with passing the string but not the length. However, in 2019 this changed
for gfortran, starting with version 9 but backported to versions 7 and 8. Several
months later, gfortran 9.2 introduced an option
-ftail-call-workaround
and made it the current default but said it might be withdrawn in future.
Suppose we want a function to report a message from Fortran to R’s console (one
could use labelpr, or intpr with dummy data, but this might be the basis of a
custom reporting function). Suppose the equivalent in Fortran would be
subroutine rmsg(msg)
character*(*) msg
print *.msg
end
in file rmsg.f. Using gfortran 9.2 and later we can extract the C view by
gfortran -c -fc-prototypes-external rmsg.f
which gives
void rmsg_ (char *msg, size_t msg_len);
(where size_t applies to version 8 and later). We could re-write that portably in C
as
#ifndef USE_FC_LEN_T
# define USE_FC_LEN_T
#endif
#include <Rconfig.h> // included by R.h, so define USE_FC_LEN_T early
#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
(USE_FC_LEN_T is the default as from R 4.3.0.)
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
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
where the C side is simply
void cmsg(const char *msg)
{
// do something with nul-terminated string ‘msg’
}
If you use bind to a C function as here, the only way to check that the bound
definition is correct is to compile the package with LTO (which requires
compatible C and Fortran compilers, usually gcc and gfortran).
Passing a variable-length string from C to Fortran is trickier,
but [Link]
guide-reference/2023-0/[Link] 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
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
which is then called from C with declaration
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);
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
// before any R headers, or define in PKG_CPPFLAGS
#ifndef USE_FC_LEN_T
# define USE_FC_LEN_T
#endif
#include <Rconfig.h>
#include <R_ext/BLAS.h>
#ifndef FCONE
# define FCONE
#endif
...
F77_CALL(dgemm)("N", "T", &nrx, &ncy, &ncx, &one, x,
&nrx, y, &nry, &zero, z, &nrx FCONE FCONE);
(Note there is no comma before or between the FCONE 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.
Next: Passing functions, Previous: Fortran character strings, Up: Calling C from
Fortran and vice versa [Contents][Index]
6.6.2 Fortran LOGICAL
Previous: Fortran LOGICAL, Up: Calling C from Fortran and vice versa
[Contents][Index]
6.6.3 Passing functions
F77_CALL(lmdif)(&fcn_lmdif, ...
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 f2c.
Next: Optimization, Previous: Calling C from Fortran and vice versa, Up: The
R API: entry points for C code [Contents][Index]
Entries marked with an asterisk only have ‘p’ and ‘q’ functions available, and
none of the non-central distributions have ‘r’ functions.
(If remapping is suppressed, the Normal distribution names
are Rf_dnorm4, Rf_pnorm5 and Rf_qnorm5.)
Additionally, a multivariate RNG for the multinomial distribution is
void rmultinom(int n, double* prob, int K, int* rN)
where K = length(prob), sum(prob[.]) == 1 and rN must point to a length-K integer
vector n1 n2 .. nK where each entry nj=rN[j] is “filled” by a random binomial
from Bin(n; prob[j]), constrained to sum(rN[.]) == n.
After calls to dwilcox, pwilcox or qwilcox the function wilcox_free() should be
called, and similarly signrank_free() for the signed rank
functions. Since wilcox_free() and signrank_free() were only added
to Rmath.h in R 4.2.0, their use requires something like
#include "Rmath.h"
#include "Rversion.h"
Function: void dpsifn (double x, int n, int kode, int m, double* ans,
int* nz, int* ierr)
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 lgammafn. In other words, digamma(x) is the same
as psigamma(x,0), trigamma(x) == psigamma(x,1), etc. The underlying
workhorse, dpsifn(), is useful, e.g., when several derivatives of log
Gamma=lgammafn are desired. It computes and returns in ans[] the length-
m 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., psigamma(x,k). For more details,
see the comments in src/nmath/polygamma.c.
Next: Integration, Previous: Numerical analysis subroutines, Up: The R API: entry
points for C code [Contents][Index]
6.8 Optimization
The C code underlying optim can be accessed directly. The user needs to supply a
function to compute the function to be minimized, of the type
typedef double optimfn(int n, double *par, void *ex);
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.
Some of the methods also require a gradient function
typedef void optimgr(int n, double *par, double *gr, void *ex);
which passes back the gradient in the gr argument. No function is provided for
finite-differencing, nor for approximating the Hessian at the result.
The interfaces (defined in header R_ext/Applic.h) are
Nelder Mead:
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);
BFGS:
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);
Conjugate gradients:
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);
Limited-memory BFGS with bounds:
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);
Simulated annealing:
void samin(int n, double *x, double *Fmin, optimfn fn, int
maxit,
int tmax, double temp, int trace, void *ex);
Many of the arguments are common to the various methods. n is the number of
parameters, x or xin is the starting parameters on entry and x the final parameters
on exit, with final value returned in Fmin. Most of the other parameters can be
found from the help page for optim: see the source
code src/appl/lbfgsb.c for the values of nbd, which specifies which bounds
are to be used.
Next: Utility functions, Previous: Optimization, Up: The R API: entry points for C
code [Contents][Index]
6.9 Integration
The C code underlying integrate can be accessed directly. The user needs to
supply a vectorizing C function to compute the function to be integrated, of the
type
typedef void integr_fn(double *x, int n, void *ex);
where x[] is both input and output and has length n, i.e., a C function, say fn, of
type integr_fn must basically do for(i in 1:n) x[i] := f(x[i], ex). The
vectorization requirement can be used to speed up the integrand instead of calling
it n times. Note that in the current implementation built on QUADPACK, n will be
either 15 or 21. The ex argument is a pointer passed down from the calling routine,
normally used to carry auxiliary information.
There are interfaces (defined in header R_ext/Applic.h) for integrals over
finite and infinite intervals (or “ranges” or “integration boundaries”).
Finite:
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);
Infinite:
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);
Only the 3rd and 4th argument differ for the two integrators; for the finite range
integral using Rdqags, a and b are the integration interval bounds, whereas for an
infinite range integral using Rdqagi, bound is the finite bound of the integration (if
the integral is not doubly-infinite) and inf is a code indicating the kind of
integration range,
inf = 1
corresponds to (bound, +Inf),
inf = -1
corresponds to (-Inf, bound),
inf = 2
corresponds to (-Inf, +Inf),
f and ex define the integrand function, see above; epsabs and epsrel specify the
absolute and relative accuracy requested, result, abserr and last are the output
components value, [Link] and subdivisions of the R function integrate,
where neval gives the number of integrand function evaluations, and the error
code ier is translated to R’s integrate() $ message, look at that function
definition. limit corresponds to integrate(..., subdivisions = *). It seems you
should always define the two work arrays and the length of the second one as
lenw = 4 * limit;
iwork = (int *) R_alloc(limit, sizeof(int));
work = (double *) R_alloc(lenw, sizeof(double));
The comments in the source code in src/appl/integrate.c give more
details, particularly about reasons for failure (ier >= 1).
Next: Re-encoding, Previous: Integration, Up: The R API: entry points for C code
[Contents][Index]
Function: void R_max_col (double* matrix, int* nr, int* nc, int* maxes,
int* ties_meth)
Given the nr by nc matrix matrix in column-major (“Fortran”)
order, R_max_col() returns in maxes[i-1] the column number of the maximal
element in the i-th row (the same as R’s [Link]() function). In the case of
ties (multiple maxima), *ties_meth is an integer code in 1:3 determining the
method: 1 = “random”, 2 = “first” and 3 = “last”. See R’s help page ?
[Link].
Next: Condition handling and cleanup code, Previous: Utility functions, Up: The
R API: entry points for C code [Contents][Index]
6.11 Re-encoding
R has its own C-level interface to the encoding conversion capabilities provided
by iconv because there are incompatibilities between the declarations in different
implementations of iconv.
These are declared in header file R_ext/Riconv.h.
Next: Allowing interrupts, Previous: Re-encoding, Up: The R API: entry points for
C code [Contents][Index]
Next: Platform and version information, Previous: Condition handling and cleanup
code, Up: The R API: entry points for C code [Contents][Index]
void R_CheckUserInterrupt(void);
and from Fortran
subroutine rchkusr()
These check if the user has requested an interrupt, and if so branch to R’s error
signaling functions.
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.
Next: Inlining C functions, Previous: Allowing interrupts, Up: The R API: entry
points for C code [Contents][Index]
Next: Controlling visibility, Previous: Platform and version information, Up: The
R API: entry points for C code [Contents][Index]
6.15 Inlining C functions
The C99 keyword inline 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 R_INLINE (defined in file Rconfig.h included by R.h),
as for example from package cluster
#include <R.h>
Next: Using these functions in your own C code, Previous: Inlining C functions,
Up: The R API: entry points for C code [Contents][Index]
Previous: Using these functions in your own C code, Up: The R API: entry points
for C code [Contents][Index]
Next: Linking GUIs and other front-ends to R, Previous: The R API: entry points
for C code, Up: Writing R Extensions [Contents][Index]
Previous: Generic functions and methods, Up: Generic functions and methods
[Contents][Index]
Next: Embedding R under Windows, Previous: Linking GUIs and other front-ends
to R, Up: Linking GUIs and other front-ends to R [Contents][Index]
R_ReplDLLinit();
while(R_ReplDLLdo1() > 0) {
/* add user actions here if desired */
}
*/
Rf_endEmbeddedR(0);
/* final tidying up after R is shutdown */
return 0;
}
If you do not want to pass R arguments, you can fake an argv array, for example by
char *argv[]= {"REmbeddedPostgres", "--silent"};
Rf_initEmbeddedR(sizeof(argv)/sizeof(argv[0]), argv);
However, to make a GUI we usually do want to run run_Rmainloop 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.
One issue to watch is that on some
platforms Rf_initEmbeddedR and Rf_endEmbeddedR change the settings of the FPU
(e.g. to allow errors to be trapped and to make use of extended precision registers).
The standard code sets up a session temporary directory in the usual
way, unless R_TempDir is set to a non-NULL value before Rf_initEmbeddedR 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.
Rf_initEmbeddedR sets R to be in interactive mode: you can
set R_Interactive (defined in Rinterface.h) subsequently to change this.
Note that R expects to be run with the locale category ‘LC_NUMERIC’ set to its
default value of C, and so should not be embedded into an application which
changes that.
It is the user’s responsibility to attempt to initialize only once. To protect the R
interpreter, Rf_initialize_R will exit the process if re-initialization is attempted.
Compiling against the R library
Setting R callbacks
Registering symbols
Meshing event loops
Threading issues
Suitable flags to compile and link against the R (shared or static) library can be
found by
R CMD config --cppflags
R CMD config --ldflags
(These apply only to an uninstalled copy or a standard install.)
If R is installed, pkg-config is available and neither sub-architectures nor a macOS
framework have been used, alternatives for a shared R library are
pkg-config --cflags libR
pkg-config --libs libR
and for a static R library
pkg-config --cflags libR
pkg-config --static --libs libR
(This may work for an installed OS framework if pkg-config is taught where to
look for [Link]: it is installed inside the framework.)
However, a more comprehensive way is to set up a Makefile to compile the
front-end. Suppose file myfe.c is to be compiled to myfe. A
suitable Makefile might be
## WARNING: does not work when ${R_HOME} contains spaces
include ${R_HOME}/etc${R_ARCH}/Makeconf
all: myfe
R_RunExitFinalizers();
/* clean up after the editor e.g. CleanEd() */
R_CleanTempDir();
exit(status);
}
These callbacks should never be changed in a running R session (and hence cannot
be called from an extension package).
Function: SEXP R_dataentry (SEXP, SEXP, SEXP, SEXP);
Next: Meshing event loops, Previous: Setting R callbacks, Up: Embedding R under
Unix-alikes [Contents][Index]
8.1.3 Registering symbols
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 Rinterface.h (if CSTACK_DEFNS is defined) as
extern uintptr_t R_CStackLimit; /* C stack limit */
extern uintptr_t R_CStackStart; /* Initial stack address */
Note that uintptr_t is an optional C99 type for which a substitute is defined in R,
so your code needs to define HAVE_UINTPTR_T appropriately. To do so, test if the
type is defined in C header stdint.h or C++ header cstdint and if so include
the header and define HAVE_UINTPTR_T before including Rinterface.h. (For C
code one can simply include Rconfig.h, possibly via R.h, and for C++11
code Rinterface.h will include the header cstdint.)
These will be set169 when Rf_initialize_R is called, to values appropriate to the
main thread. Stack-checking can be disabled by setting R_CStackLimit =
(uintptr_t)-1 immediately after Rf_initialize_R 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.)
You may also want to consider how signals are handled: R sets signal handlers for
several signals, including SIGINT, SIGSEGV, SIGPIPE, SIGUSR1 and SIGUSR2, but these
can all be suppressed by setting the variable R_SignalHandlers (declared
in Rinterface.h) to 0.
Note that these variables must not be changed by an R package: a package should
not call R internals which makes use of the stack-checking mechanism on a
secondary thread.
Previous: Embedding R under Unix-alikes, Up: Linking GUIs and other front-ends
to R [Contents][Index]
The R DLL is mainly written in C and has _cdecl entry points. Calling it directly
will be tricky except from C code (or C++ with a little care).
There is a version of the Unix-alike interface calling
int Rf_initEmbeddedR(int ac, char **av);
void Rf_endEmbeddedR(int fatal);
which is an entry point in [Link]. Examples of its use (and a
suitable [Link]) can be found in the tests/Embedding directory of
the sources. You may need to ensure that R_HOME/bin is in your PATH so the R
DLLs are found.
Examples of calling [Link] directly are provided in the
directory src/gnuwin32/front-ends, including a simple command-line
front end rtest.c whose code is
#define Win32
#include <windows.h>
#include <stdio.h>
#include <Rversion.h>
#define LibExtern __declspec(dllimport) extern
#include <Rembedded.h>
#include <R_ext/RStartup.h>
/* for askok and askyesnocancel */
#include <graphapp.h>
/* 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 myCallBack(void)
{
/* called during i/o, eval, graphics in ProcessEvents */
}
R_setStartTime();
R_DefParamsEx(Rp, RSTART_VERSION);
if((RHome = get_R_HOME()) == NULL) {
fprintf(stderr, "R_HOME must be set in the environment or Registry\
n");
exit(1);
}
Rp->rhome = RHome;
RUser = getRUser();
Rp->home = RUser;
Rp->CharacterMode = LinkDLL;
Rp->EmitEmbeddedUTF8 = FALSE;
Rp->ReadConsole = myReadConsole;
Rp->WriteConsole = myWriteConsole;
Rp->CallBack = myCallBack;
Rp->ShowMessage = askok;
Rp->YesNoCancel = askyesnocancel;
Rp->Busy = myBusy;
Rp->R_Quiet = TRUE; /* Default is FALSE */
Rp->R_Interactive = FALSE; /* Default is TRUE */
Rp->RestoreAction = SA_RESTORE;
Rp->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() > 0) {
/* add user actions here if desired */
}
/* only get here on EOF (not q()) */
#endif
Rf_endEmbeddedR(0);
return 0;
}
The ideas are
Check that the front-end and the linked [Link] match – other front-ends
may allow a looser match.
Find and set the R home directory and the user’s home directory. The
former may be available from the Windows Registry: it will be
in HKEY_LOCAL_MACHINE\Software\R-core\R\InstallPath from an
administrative install and HKEY_CURRENT_USER\Software\R-core\R\
InstallPath otherwise, if selected during installation (as it is by default).
Define startup conditions and
callbacks via the Rstart structure. R_DefParams sets the defaults,
and R_SetParams sets updated values. R_DefParamsEx takes an extra
argument, the version number of the Rstart structure provided
(RSTART_VERSION refers to the current version) and returns a non-zero status
when that version is not supported by R.
Record the command-line arguments used
by R_set_command_line_arguments for use by the R function commandArgs().
Set up the signal handler and the basic user interface.
Run the main R loop, possibly with our actions intermeshed.
Arrange to clean up.
An underlying theme is the need to keep the GUI ‘alive’, and this has not been
done in this example. The R callback R_ProcessEvents 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 – two ways are provided to allow this:
R_ProcessEvents calls the callback registered by Rp->callback. A version of
this is used to run package Tcl/Tk for tcltk under Windows, for the code is
void R_ProcessEvents(void)
{
while (peekevent()) doevent(); /* Windows events for
GraphApp */
if (UserBreak) { UserBreak = FALSE; onintr(); }
R_CallBackHook();
if(R_tcldo) R_tcldo();
}
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 #ifdef SIMPLE_CASE.
It may be that no R GraphApp windows need to be considered, although these
include pagers, the windows() graphics device, the R data and script editors and
various popups such as [Link]() and [Link](). It would be possible to
replace all of these, but it seems easier to allow GraphApp to handle most of them.
It is possible to run R in a GUI in a single thread (as [Link] shows) but it will
normally be easier170 to use multiple threads.
Note that R’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.
Applications embedding R 4.2.0 and newer should use UCRT 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.
Both applications which embed R and those which use a system call to invoke R
(as [Link], [Link] or [Link]) need to be able to find the R bin directory.
The simplest way to do so is the ask the user to set an environment
variable R_HOME and use that, but naive users may be flummoxed as to how to do so
or what value to use.
The R for Windows installers have for a long time allowed the value of R_HOME to
be recorded in the Windows Registry: this is optional but selected by
default. Where 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.
The basic Registry location is Software\R-core\R. For an administrative install this
is under HKEY_LOCAL_MACHINE and on a 64-bit OS HKEY_LOCAL_MACHINE\Software\R-
core\R 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 HKEY_CURRENT_USER\Software\R-core\R which is seen by both 32-bit and 64-
bit applications and so records the last install of either architecture. To circumvent
this, there are locations Software\R-core\R32 and Software\R-core\R64 which
always refer to one architecture.
When R is installed and recording is not disabled then two string values are written
at that location for keys InstallPath and Current Version, 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 3.0.0 or 3.0.0
patched or 3.1.0 Pre-release with a value for InstallPath.
.
.C: Interface functions .C and .Fortran
.Call: Handling R objects in C
.Call: Calling .Call
.External: Handling R objects in C
.External: Calling .External
.Fortran: Interface functions .C and .Fortran
.[Link]: Load hooks
.onAttach: Load hooks
.onDetach: Load hooks
.onLoad: Load hooks
.onUnload: Load hooks
.[Link]: Random numbers
\
\acronym: Marking text
\alias: Documenting functions
\arguments: Documenting functions
\author: Documenting functions
\bold: Marking text
\cite: Marking text
\code: Marking text
\command: Marking text
\concept: Indices
\cr: Sectioning
\CRANpkg{pkg}: User-defined macros
\deqn: Mathematics
\describe: Lists and tables
\description: Documenting functions
\details: Documenting functions
\dfn: Marking text
\doi{numbers}: User-defined macros
\dontrun: Documenting functions
\dontshow: Documenting functions
\dots: Insertions
\dQuote: Marking text
\email: Marking text
\emph: Marking text
\enc: Insertions
\enumerate: Lists and tables
\env: Marking text
\eqn: Mathematics
\examples: Documenting functions
\figure: Figures
\file: Marking text
\format: Documenting data sets
\href: Marking text
\if: Conditional text
\ifelse: Conditional text
\itemize: Lists and tables
\kbd: Marking text
\keyword: Documenting functions
\ldots: Insertions
\link: Cross-references
\method: Documenting functions
\name: Documenting functions
\newcommand: User-defined macros
\note: Documenting functions
\option: Marking text
\out: Conditional text
\packageAuthor: User-defined macros
\packageDescription: User-defined macros
\packageDESCRIPTION: User-defined macros
\packageIndices: User-defined macros
\packageMaintainer: User-defined macros
\packageTitle: User-defined macros
\pkg: Marking text
\preformatted: Marking text
\R: Insertions
\RdOpts: Dynamic pages
\references: Documenting functions
\renewcommand: User-defined macros
\S3method: Documenting functions
\samp: Marking text
\section: Sectioning
\seealso: Documenting functions
\Sexpr: Dynamic pages
\source: Documenting data sets
\sQuote: Marking text
\sspace: User-defined macros
\strong: Marking text
\tabular: Lists and tables
\title: Documenting functions
\url: Marking text
\usage: Documenting functions
\value: Documenting functions
\var: Marking text
\verb: Marking text
A
allocList: Evaluating R expressions from C
allocMatrix: Calculating numerical derivatives
allocVector: Allocating storage
any_duplicated: Semi-internal convenience functions
any_duplicated3: Semi-internal convenience functions
asChar: Some convenience functions
asComplex: Some convenience functions
asInteger: Some convenience functions
asLogical: Some convenience functions
asReal: Some convenience functions
AUTHORS: Package subdirectories
B
bessel_i: Mathematical functions
bessel_j: Mathematical functions
bessel_k: Mathematical functions
bessel_y: Mathematical functions
beta: Mathematical functions
BLAS_LIBS: Using Makevars
browser: Browsing
C
CAAR: Calling .External
CAD4R: Calling .External
CAD5R: Calling .External
CADDDR: Calling .External
CADDR: Calling .External
CADR: Calling .External
Calloc: User-controlled memory
CallocCharBuf: User-controlled memory
CAR: Calling .External
CDAR: Calling .External
CDDDR: Calling .External
CDDR: Calling .External
CDR: Calling .External
cgmin: Optimization
choose: Mathematical functions
CITATION: Package subdirectories
CITATION: Preparing translations
classgets: Classes
CleanEd: Setting R callbacks
coerceVector: Details of R types
COMPLEX: Vector accessor functions
CONS: Some convenience functions
cons: Some convenience functions
COPYRIGHTS: The DESCRIPTION file
COPYRIGHTS: Package subdirectories
cospi: Numerical Utilities
cPsort: Utility functions
D
dblepr: Printing from Fortran
dblepr1: Printing from Fortran
debug: Debugging R code
debugger: Debugging R code
defineVar: Finding and setting variables
digamma: Mathematical functions
dimgets: Attributes
dimnamesgets: Attributes
dpsifn: Mathematical functions
[Link]: Debugging R code
duplicate: Named objects and copying
[Link]: [Link] and [Link]
[Link]: [Link] and [Link]
E
elt: Some convenience functions
error: Error signaling
errorcall: Error signaling
eval: Evaluating R expressions from C
expm1: Numerical Utilities
export: Specifying imports and exports
exportClasses: Namespaces with S4 classes and methods
exportClassPattern: Namespaces with S4 classes and methods
exportMethods: Namespaces with S4 classes and methods
exportPattern: Specifying imports and exports
exportPattern: Namespaces with S4 classes and methods
exp_rand: Random numbers
F
FALSE: Mathematical constants
findFun: Evaluating R expressions from C
findInterval: Utility functions
findInterval2(double*: Utility functions
findVar: Finding and setting variables
FLIBS: Using Makevars
fmax2: Numerical Utilities
fmin2: Numerical Utilities
fprec: Numerical Utilities
fpu_setup: Setting R callbacks
Free: User-controlled memory
fround: Numerical Utilities
fsign: Numerical Utilities
ftrunc: Numerical Utilities
G
gammafn: Mathematical functions
gctorture: Using gctorture
GetArrayDimnames: Attributes
getAttrib: Attributes
getCharCE: Character encoding issues
GetColNames: Attributes
GetMatrixDimnames: Attributes
GetRNGstate: Random numbers
GetRowNames: Attributes
I
imax2: Numerical Utilities
imin2: Numerical Utilities
import: Specifying imports and exports
importClassesFrom: Namespaces with S4 classes and methods
importFrom: Specifying imports and exports
importMethodsFrom: Namespaces with S4 classes and methods
install: Attributes
installChar: Finding and setting variables
INTEGER: Vector accessor functions
integr_fn: Integration
intpr: Printing from Fortran
intpr1: Printing from Fortran
iPsort: Utility functions
isArray: Some convenience functions
isComplex: Details of R types
isEnvironment: Details of R types
isExpression: Details of R types
isFactor: Some convenience functions
isFunction: Some convenience functions
isInteger: Details of R types
isLanguage: Some convenience functions
isList: Some convenience functions
isLogical: Details of R types
isMatrix: Some convenience functions
ISNA: Missing and special values
ISNA: Missing and IEEE values
ISNAN: Missing and special values
ISNAN: Missing and IEEE values
isNewList: Some convenience functions
isNull: Details of R types
isNumeric: Some convenience functions
isObject: Some convenience functions
isOrdered: Some convenience functions
isPairList: Some convenience functions
isPrimitive: Some convenience functions
isReal: Details of R types
isString: Details of R types
isSymbol: Details of R types
isTs: Some convenience functions
isUnordered: Some convenience functions
isVector: Some convenience functions
isVectorAtomic: Some convenience functions
isVectorList: Some convenience functions
L
labelpr: Printing from Fortran
lang1: Some convenience functions
lang2: Some convenience functions
lang3: Some convenience functions
lang4: Some convenience functions
lang5: Some convenience functions
lang6: Some convenience functions
LAPACK_LIBS: Using Makevars
lastElt: Some convenience functions
lbeta: Mathematical functions
lbfgsb: Optimization
lchoose: Mathematical functions
LCONS: Some convenience functions
lcons: Some convenience functions
lgamma1p: Numerical Utilities
lgammafn: Mathematical functions
[Link]: Package subdirectories
[Link]: [Link] and [Link]
list1: Some convenience functions
list2: Some convenience functions
list3: Some convenience functions
list4: Some convenience functions
list5: Some convenience functions
list6: Some convenience functions
log1mexp: Numerical Utilities
log1p: Numerical Utilities
log1pexp: Numerical Utilities
log1pmx: Numerical Utilities
LOGICAL: Vector accessor functions
logspace_add: Numerical Utilities
logspace_sub: Numerical Utilities
logspace_sum: Numerical Utilities
M
MARK_NOT_MUTABLE: Named objects and copying
MAYBE_REFERENCED: Named objects and copying
MAYBE_SHARED: Named objects and copying
Memcpy: User-controlled memory
Memzero: User-controlled memory
mkChar: Handling character data
mkCharCE: Character encoding issues
mkCharLen: Handling character data
mkCharLenCE: Character encoding issues
mkString: Some convenience functions
M_E: Mathematical constants
M_PI: Mathematical constants
N
namesgets: Attributes
NA_REAL: Missing and IEEE values
[Link]: Package subdirectories
nmmin: Optimization
norm_rand: Random numbers
nrows: Transient storage allocation
nthcdr: Some convenience functions
O
OBJECTS: Using Makevars
OBJECTS: Creating shared objects
onintr: Calling [Link] directly
optimfn: Optimization
optimgr: Optimization
P
pentagamma: Mathematical functions
PKG_CFLAGS: Creating shared objects
PKG_CPPFLAGS: Creating shared objects
PKG_CXXFLAGS: Creating shared objects
PKG_FCFLAGS: Using F9x code
PKG_FFLAGS: Creating shared objects
PKG_LIBS: Creating shared objects
PKG_OBJCFLAGS: Creating shared objects
PKG_OBJCXXFLAGS: Creating shared objects
PRINTNAME: Calling .External
PrintValue: Inspecting R objects
prompt: Rd format
PROTECT: Garbage Collection
protect: Garbage Collection
PROTECT_WITH_INDEX: Garbage Collection
psigamma: Mathematical functions
PutRNGstate: Random numbers
Q
qsort3: Utility functions
qsort4: Utility functions
R
R CMD build: Building package tarballs
R CMD check: Checking packages
R CMD config: Configure and cleanup
R CMD Rd2pdf: Processing documentation files
R CMD Rdconv: Processing documentation files
R CMD SHLIB: Creating shared objects
R CMD Stangle: Processing documentation files
R CMD Sweave: Processing documentation files
RAW: Vector accessor functions
rchkusr: Allowing interrupts
Rdqagi: Integration
Rdqags: Integration
REAL: Vector accessor functions
Realloc: User-controlled memory
realpr: Printing from Fortran
realpr1: Printing from Fortran
recover: Debugging R code
reEnc: Character encoding issues
REprintf: Printing
REPROTECT: Garbage Collection
REvprintf: Printing
revsort: Utility functions
Rf_endEmbeddedR: Embedding R under Unix-alikes
Rf_initEmbeddedR: Embedding R under Unix-alikes
Rf_initialize_R: Embedding R under Unix-alikes
Rf_KillAllDevices: Setting R callbacks
Rf_mainloop: Embedding R under Unix-alikes
Riconv: Re-encoding
Riconv_close: Re-encoding
Riconv_open: Re-encoding
Rprintf: Printing
Rprof: Profiling R code for speed
Rprof: Memory statistics from Rprof
Rprofmem: Tracking memory allocations
rPsort: Utility functions
rsort_with_index: Utility functions
Rtanpi: Numerical Utilities
run_Rmainloop: Embedding R under Unix-alikes
Rvprintf: Printing
R_addhistory: Setting R callbacks
R_alloc: Transient storage allocation
R_allocLD: Transient storage allocation
R_Busy: Setting R callbacks
R_Calloc: User-controlled memory
R_CheckUserInterrupt: Allowing interrupts
R_ChooseFile: Setting R callbacks
R_CleanTempDir: Setting R callbacks
R_CleanUp: Setting R callbacks
R_ClearerrConsole: Setting R callbacks
R_ClearExternalPtr: External pointers and weak references
R_compute_identical: Semi-internal convenience functions
R_ContinueUnwind: Condition handling and cleanup code
R_csort: Utility functions
R_dataentry: Setting R callbacks
R_dataviewer: Setting R callbacks
R_DefParams: Calling [Link] directly
R_DefParamsEx: Calling [Link] directly
R_dot_Last: Setting R callbacks
R_EditFile: Setting R callbacks
R_EditFiles: Setting R callbacks
R_ExpandFileName: Utility functions
R_ExternalPtrAddr: External pointers and weak references
R_ExternalPtrAddrFn: External pointers and weak references
R_ExternalPtrProtected: External pointers and weak references
R_ExternalPtrTag: External pointers and weak references
R_FINITE: Missing and IEEE values
R_FlushConsole: Setting R callbacks
R_forceSymbols: Registering native routines
R_Free: User-controlled memory
R_free_tmpnam: Utility functions
R_GetCCallable: Linking to native routines in other packages
R_GetCurrentEnv: Evaluating R expressions from C
R_GetCurrentSrcref: Accessing source references
R_getEmbeddingDllInfo: Registering symbols
R_GetSrcFilename: Accessing source references
R_INLINE: Inlining C functions
R_IsNaN: Missing and IEEE values
R_isort: Utility functions
R_LIBRARY_DIR: Configure and cleanup
R_loadhistory: Setting R callbacks
R_MakeExternalPtr: External pointers and weak references
R_MakeExternalPtrFn: External pointers and weak references
R_MakeUnwindCont: Condition handling and cleanup code
R_MakeWeakRef: External pointers and weak references
R_MakeWeakRefC: External pointers and weak references
R_max_col: Utility functions
R_NegInf: Missing and IEEE values
R_NewEnv: Finding and setting variables
R_NewPreciousMSet: Garbage Collection
R_orderVector: Utility functions
R_orderVector1: Utility functions
R_PACKAGE_DIR: Configure and cleanup
R_PACKAGE_DIR: Configure and cleanup
R_PACKAGE_NAME: Configure and cleanup
R_PACKAGE_NAME: Configure and cleanup
R_ParseVector: Parsing R code from C
R_PolledEvents: Meshing event loops
R_PosInf: Missing and IEEE values
R_pow: Numerical Utilities
R_pow_di: Numerical Utilities
R_PreserveInMSet: Garbage Collection
R_PreserveObject: Garbage Collection
R_ProcessEvents: Calling [Link] directly
R_ProtectWithIndex: Garbage Collection
R_PV: Inspecting R objects
R_qsort: Utility functions
R_qsort_I: Utility functions
R_qsort_int: Utility functions
R_qsort_int_I: Utility functions
R_ReadConsole: Setting R callbacks
R_Realloc: User-controlled memory
R_RegisterCCallable: Linking to native routines in other packages
R_RegisterCFinalizer: External pointers and weak references
R_RegisterCFinalizerEx: External pointers and weak references
R_RegisterFinalizer: External pointers and weak references
R_RegisterFinalizerEx: External pointers and weak references
R_registerRoutines: Registering native routines
R_ReleaseFromMSet: Garbage Collection
R_ReleaseObject: Garbage Collection
R_ReplDLLdo1: Embedding R under Unix-alikes
R_ReplDLLinit: Embedding R under Unix-alikes
R_Reprotect: Garbage Collection
R_ResetConsole: Setting R callbacks
R_rsort: Utility functions
R_RunExitFinalizers: Setting R callbacks
R_RunWeakRefFinalizer: External pointers and weak references
R_SaveGlobalEnv: Setting R callbacks
R_savehistory: Setting R callbacks
R_selectlist: Setting R callbacks
R_SetExternalPtrAddr: External pointers and weak references
R_SetExternalPtrProtected: External pointers and weak references
R_SetExternalPtrTag: External pointers and weak references
R_SetParams: Calling [Link] directly
R_setStartTime: Calling [Link] directly
R_set_command_line_arguments: Calling [Link] directly
R_ShowFiles: Setting R callbacks
R_ShowMessage: Setting R callbacks
R_Srcref: Accessing source references
R_Suicide: Setting R callbacks
R_tmpnam: Utility functions
R_tmpnam2: Utility functions
R_tryCatch: Condition handling and cleanup code
R_tryCatchError: Condition handling and cleanup code
R_unif_index: Random numbers
R_UnwindProtect: Condition handling and cleanup code
R_useDynamicSymbols: Registering native routines
R_Version: Platform and version information
R_wait_usec: Meshing event loops
R_WeakRefKey: External pointers and weak references
R_WeakRefValue: External pointers and weak references
R_withCallingErrorHandler: Condition handling and cleanup code
R_WriteConsole: Setting R callbacks
R_WriteConsoleEx: Setting R callbacks
S
S3method: Registering S3 methods
SAFE_FFLAGS: Using Makevars
samin: Optimization
ScalarComplex: Some convenience functions
ScalarInteger: Some convenience functions
ScalarLogical: Some convenience functions
ScalarRaw: Some convenience functions
ScalarReal: Some convenience functions
ScalarString: Some convenience functions
setAttrib: Attributes
SETCAD4R: Calling .External
SETCADDDR: Calling .External
SETCADDR: Calling .External
SETCADR: Calling .External
SETCAR: Calling .External
SETCDR: Calling .External
setup_Rmainloop: Calling [Link] directly
setVar: Finding and setting variables
SET_STRING_ELT: Handling character data
SET_TAG: Evaluating R expressions from C
SET_VECTOR_ELT: Vector accessor functions
sign: Numerical Utilities
signrank_free: Distribution functions
sinpi: Numerical Utilities
str2type: Some convenience functions
STRING_ELT: Handling character data
summaryRprof: Memory statistics from Rprof
system: Operating system access
[Link]: Operating system access
system2: Operating system access
S_alloc: Transient storage allocation
S_realloc: Transient storage allocation
T
TAG: Calling .External
tanpi: Numerical Utilities
tetragamma: Mathematical functions
trace: Debugging R code
traceback: Debugging R code
tracemem: Tracing copies of an object
translateChar: Character encoding issues
translateCharUTF8: Character encoding issues
trigamma: Mathematical functions
TRUE: Mathematical constants
type2char: Some convenience functions
type2str: Some convenience functions
TYPEOF: Calling .External
U
undebug: Debugging R code
unif_rand: Random numbers
UNPROTECT: Garbage Collection
unprotect: Garbage Collection
UNPROTECT_PTR: Garbage Collection
unprotect_ptr: Garbage Collection
untracemem: Tracing copies of an object
useDynLib: useDynLib
V
VECTOR_ELT: Vector accessor functions
vmaxget: Transient storage allocation
vmaxset: Transient storage allocation
vmmin: Optimization
W
warning: Error signaling
warningcall: Error signaling
warningcall_immediate: Error signaling
wilcox_free: Distribution functions
. \
Jump to:
A B C D E F G I L M N O P Q R S T U V W
Concept index
. \
Jump to:
A B C D E F G H I L M N O P R S T U V W Z
Index Entry Section
.
.install_extras file: Writing package vignettes
.Rbuildignore file: Building package tarballs
.Rinstignore file: Package subdirectories
\
\linkS4class: Cross-references
A
Allocating storage: Allocating storage
Attributes: Attributes
B
Bessel functions: Mathematical functions
Beta function: Mathematical functions
Building binary packages: Building binary packages
Building source packages: Building package tarballs
C
C++ code, interfacing: Interfacing C++ code
Calling C from Fortran and vice versa: Calling C from Fortran and vice versa
Checking packages: Checking packages
citation: Package subdirectories
citation: Preparing translations
Classes: Classes
Cleanup code: Condition handling and cleanup code
cleanup file: Package structure
Condition handling: Condition handling and cleanup code
conditionals: Conditional text
configure file: Package structure
Copying objects: Named objects and copying
CRAN: Creating R packages
Creating packages: Creating R packages
Creating shared objects: Creating shared objects
Cross-references in documentation: Cross-references
cumulative hazard: Distribution functions
D
Debugging: Debugging compiled code
DESCRIPTION file: The DESCRIPTION file
Details of R types: Details of R types
Distribution functions from C: Distribution functions
Documentation, writing: Writing R documentation files
Dynamic loading: [Link] and [Link]
dynamic pages: Dynamic pages
E
Editing Rd files: Editing Rd files
encoding: Encoding
Error handling: Condition handling and cleanup code
Error signaling from C: Error signaling
Error signaling from Fortran: Error signaling from Fortran
Evaluating R expressions from C: Evaluating R expressions from C
external pointer: External pointers and weak references
F
Figures in documentation: Figures
finalizer: External pointers and weak references
Finding variables: Finding and setting variables
G
Gamma function: Mathematical functions
Garbage collection: Garbage Collection
Generic functions: Generic functions and methods
H
handling character data: Handling character data
Handling lists: Handling lists
Handling R objects in C: Handling R objects in C
I
IEEE special values: Missing and special values
IEEE special values: Missing and IEEE values
INDEX file: The INDEX file
Indices: Indices
Inspecting R objects when debugging: Inspecting R objects
integration: Integration
Interfaces to compiled code: Interface functions .C and .Fortran
Interfaces to compiled code: Interface functions .Call and .External
Interfacing C++ code: Interfacing C++ code
Interrupts: Allowing interrupts
L
LICENCE file: Licensing
LICENSE file: Licensing
Lists and tables in documentation: Lists and tables
M
Marking text in documentation: Marking text
Mathematics in documentation: Mathematics
Memory allocation from C: Memory allocation
Memory use: Profiling R code for memory use
Method functions: Generic functions and methods
Missing values: Missing and special values
Missing values: Missing and IEEE values
N
namespaces: Package namespaces
news: Package subdirectories
Numerical analysis subroutines from C: Numerical analysis subroutines
Numerical derivatives: Calculating numerical derivatives
O
OpenMP: OpenMP support
OpenMP: Platform and version information
Operating system access: Operating system access
optimization: Optimization
P
Package builder: Building package tarballs
Package structure: Package structure
Package subdirectories: Package subdirectories
Packages: Creating R packages
Parsing R code from C: Parsing R code from C
Platform-specific documentation: Platform-specific sections
Polygamma functions: Mathematical functions
Printing from C: Printing
Printing from Fortran: Printing from Fortran
Processing Rd format: Processing documentation files
Profiling: Profiling R code for speed
Profiling: Profiling R code for memory use
Profiling: Profiling compiled code
R
Random numbers in C: Random numbers
Random numbers in C: Distribution functions
Random numbers in Fortran: Calling C from Fortran and vice versa
Registering native routines: Registering native routines
S
Setting variables: Finding and setting variables
Sort functions from C: Utility functions
Sweave: Writing package vignettes
T
tarballs: Building package tarballs
Tidying R code: Tidying R code
U
user-defined macros: User-defined macros
V
Version information from C: Platform and version information
vignettes: Writing package vignettes
Visibility: Controlling visibility
W
weak reference: External pointers and weak references
Z
Zero-finding: Zero-finding
. \
Jump to:
A B C D E F G H I L M N O P R S T U V W Z
Footnotes
(1)
This seems to be commonly used for a file in ‘markdown’ 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 CRAN package web pages render such files in HTML: the
converter used expects the file to be encoded in UTF-8.
(3)
(4)
false positives are possible, but only a handful have been seen so far.
(5)
(7)
(9)
[Link] will try to extract an email address from a Contact field if there is
no BugReports field.
(11)
(12)
This includes all packages directly called by library and require calls, as well as
data obtained via data(theirdata, package = "somepkg") calls: R CMD check 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 ‘Suggests’ list for package A. Nor will undeclared uses in included files be
reported, nor unconditional uses of packages listed under ‘Enhances’. R CMD
check --as-cran will detect more of the subtler uses.
(14)
Extensions .S and .s arise from code originally written for S(-PLUS), but are
commonly used for assembler code. Extension .q was used for S, which at one
time was tentatively called QPE.
(15)
(16)
This is true for OSes which implement the ‘C’ locale: Windows’ idea of the ‘C’
locale uses the WinAnsi charset.
(17)
More precisely, they can contain the English alphanumeric characters and the
symbols ‘$ - _ . + ! ' ( ) , ; = &’.
(18)
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 SDK have
removed much of the support for Objective C v1.0 and Objective C++.
(19)
(20)
(21)
The best way to generate such a file is to copy the .Rout from a successful run
of R CMD check. If you want to generate it separately, do run R with options --
vanilla --no-echo and with environment variable LANGUAGE=en set to get
messages in English. Be careful not to use output with the option --
timings (and note that --as-cran sets it).
(23)
e.g. [Link]
(24)
People who have trouble with case are advised to use .rda as a common error is
to refer to [Link] as [Link]!
(25)
For all the CRAN packages tested, either gz or bzip2 provided a very substantial
reduction in installed size.
(26)
but it is available on the machines used to produce the CRAN binary packages:
however as Apple does not ship .pc files for its system libraries such
as expat, libcurl, libxml2, sqlite3 and ‘zlib’, it may well not find information
on these. Some substitutes are available
from [Link] and
are installed on the CRAN package builders.
(30)
but not all projects get this right when only a static library is installed, so it is often
necessary to try in turn pkg-config --libs and pkg-config --static --libs.
(32)
a decade ago Autoconf used [Link]: this is still accepted but should be
renamed and autoreconf as used by R CMD check --as-cran will report as such.
(33)
For those using autoconf 2.70 or later there is also AC_CONFIG_MACRO_DIRS which
allows multiple directories to be specified.
(34)
Default builds of LLVM clang 3.8.0 and later have support for OpenMP, but
the libomp run-time library may not be installed.
(39)
In most implementations the _OPENMP macro has value a date which can be mapped
to an OpenMP version: for example, value 201307 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.
(40)
Which it was at the time of writing with GCC, Intel and Clang compilers. The
count may include the thread running the main process.
(42)
Be careful not to declare nthreads as const int: the Oracle compiler required it to
be ‘an lvalue’.
(43)
(44)
A few OSes (AIX, Windows) do not need special flags for such code, but most do
—although compilers will often generate PIC code when not asked to do so.
(45)
Values 201103L, 201402L, 201703L and 202002L are most commonly used for C++11,
C++14, C++17 and C++20 respectively, but some compilers set 1L. For C++23 all
that can currently be assumed is a value greater than that for C++20: for
example g++ 12 uses 202100L and clang++ (LLVM 15, Apple 14) uses 202101L.
(48)
See [Link]
recommendations or [Link]
It seems a reasonable assumption that any compiler promising some C++14
conformance will provide these—e.g. g++ 4.9.x did but 4.8.5 did not.
(50)
(51)
(53)
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.
(54)
for the most comprehensive checking this should be 5.8.0 or later: any for
which tidy --version does not report a version number will be too old – this
includes the 2006 version shipped with macOS.
(56)
(57)
called CVS or .svn or .arch-ids or .bzr or .git (but not files called .git)
or .hg.
(58)
called .metadata.
(59)
(60)
(63)
provided the conditions of the package’s license are met: many, including CRAN,
see the omission of source components as incompatible with an Open Source
license.
(64)
(65)
Note that lazy-loaded datasets are not in the package’s namespace so need to be
accessed via ::, e.g. survival::[Link].
(66)
NB: this will only be read in all versions of R if the package contains R code in
a R directory.
(68)
Note that this is the basename of the shared object, and the appropriate extension
(.so or .dll) will be added.
(69)
Solaris make did not accept CRLF-terminated Makefiles; Solaris warned about and
some other makes ignore incomplete final lines.
(73)
GNU make, BSD make and other variants of pmake in FreeBSD, NetBSD and
formerly in macOS, and formerly AT&T make as implemented on Solaris and
‘Distributed Make’ (dmake), part of Oracle Developer Studio and available in other
versions including from Apache OpenOffice.
(75)
For example, test options -a and -e are not portable, and not supported in the
AT&T Bourne shell used on Solaris 10/11, even though they are in the POSIX
standard. Nor did Solaris support ‘$(cmd)’.
(76)
it was not in the Bourne shell, and was not supported by Solaris 10.
(78)
These are optional because the corresponding types are, but must be provided if the
types are.
(80)
in libselinux.
(84)
Whereas the GNU linker reorders so -L options are processed first, the Solaris one
did not.
(87)
If a Java interpreter is required directly (not via rJava) this must be declared and
its presence tested like any other external command.
(89)
(90)
These are not needed for the default compiler settings on ‘x86_64’ but are likely
to be needed on ‘ix86’.
(92)
Select ‘Save as’, and select ‘Reduce file size’ from the ‘Quartz filter’ menu’: this
can be accessed in other ways, for example by Automator.
(93)
except perhaps some special characters such as backslash and hash which may be
taken over for currency symbols.
(94)
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.
(97)
This is seen on Linux, Solaris and FreeBSD, although each has other ways to turn
on all extensions, e.g. defining _GNU_SOURCE, __EXTENSIONS__ or _BSD_SOURCE: the
GCC compilers by default define _GNU_SOURCE unless a strict standard such as -
std=c99 is used. On macOS extensions are declared unless one of these macros
is given too small a value.
(98)
at the time of writing ‘arm64’ macOS both warned and did not supply a prototype
in math.h which resulted in a compilation error.
(100)
which often is the same as the header included by the C compiler, but some
compilers have wrappers for some of the C headers.
(103)
Although this is expected to be part of C23, full support of that is years away.
(104)
[Link]
(105)
when using the macOS 13 SDK with a deployment target of macOS 13.
(107)
see [Link]
(108)
See [Link]
[Link]#modified-compiler-flags.
(109)
In principle this could depend on the OS, but has been checked on Linux and
macOS.
(110)
There can be exceptions: for example Rd files are not allowed to start with a dot,
and have to be uniquely named on a case-insensitive file system.
(112)
in the current locale, and with special treatment for LaTeX special characters and
with any ‘pkgname-package’ topic moved to the top of the list.
(113)
Text between or after list items is discouraged.
(114)
(116)
There is only a fine distinction between \dots and \ldots. It is technically incorrect
to use \ldots in code blocks and tools::checkRd will warn about this—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.
(117)
(118)
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 _R_CYRILLIC_TEX_ may need to be set to a non-empty value to enable this.
(119)
For Unix-alikes these are intervals of CPU time, and for Windows of elapsed time.
(121)
With the exceptions of the commands listed below: an object of such a name can
be printed via an explicit call to print.
(122)
including using the data sections of R vectors after they are freed.
(125)
currently on ‘x86_64’/‘ix86’ 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 ‘aarch64’ only.) On some platforms the runtime library, libasan,
needs to be installed separately, and for checking C++ you may also
need libubsan.
(127)
see [Link]
%202014%20--%20container%[Link].
(128)
part of the LLVM project and distributed in llvm RPMs and .debs on Linux. It is
not currently shipped by Apple.
(129)
(132)
for example, X11/GL libraries on Linux, seen when checking package rgl and
some others using it—a workaround is to set environment
variable RGL_USE_NULL=true.
(133)
but works better if inlining and frame pointer optimizations are disabled.
(135)
(136)
See [Link]
‘@executable_path’ could be used rather than absolute paths.
(137)
Note that this is then not checked for over-runs by option CBoundsCheck = TRUE.
(140)
Strictly this is OS-specific, but no exceptions have been seen for many years.
(141)
For calls from within a namespace the search is confined to the DLL loaded for
that package.
(142)
For unregistered entry points the OS’s dlsym 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 .Call entry points.
(143)
(145)
(146)
Even including C system headers in such a block has caused compilation errors.
(147)
[Link]
(148)
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.
(151)
see The R API: entry points for C code: note that these are not all part of the API.
(152)
If no coercion was required, coerceVector would have passed the old object
through unchanged.
(154)
(155)
see Character encoding issues for why this might not be what is required.
(156)
Known problems have been defining LENGTH, error, length, vector and warning:
whether these matter depends on the OS and toolchain, with many problem reports
involving clang++. As from LLVM clang 13.0.0, the remapping of match breaks
the subsequent inclusion of omp.h.
(158)
(161)
[Link]
(163)
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 AIX nor Solaris compilers.
(164)
This applies to the compiler for the default C++ dialect (currently C++11) and not
necessarily to other dialects.
(165)
In some cases Fortran compilers accept the flag but do not actually hide their
symbols.
(166)
In the parlance of macOS this is a dynamic library, and is the normal way to build
R on that platform.
(167)
but these are not part of the automated test procedures and so little tested.
(168)
at least on platforms where the values are available, that is having getrlimit and
on Linux or having sysctl supporting KERN_USRSTACK, including FreeBSD and
macOS.
(170)
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.