Getting started with ROOT
Learning objectives
After completing this chapter, you should be able to:
- Install and configure ROOT.
- Start and navigate the ROOT interactive environment.
- Execute C++ statements within ROOT.
- Create and execute ROOT macros.
- Understand the difference between interpreted and compiled code.
- Compile standalone C++ programs using ROOT libraries.
- Access the official ROOT documentation.
Installing ROOT
ROOT is available for Linux, macOS and Windows. Several installation methods are supported, including precompiled binary distributions, package managers and compilation from source.
The recommended installation method depends on your operating system and development environment.
For detailed installation instructions, visit the official ROOT installation page.
ROOT can be installed using a compatible precompiled binary distribution or a supported package manager.
After extracting a binary distribution, configure the environment by executing:
source /path/to/root/bin/thisroot.sh
Replace /path/to/root with the actual installation
directory.
ROOT can be installed natively on Windows.
Alternatively, Windows Subsystem for Linux (WSL) provides a Linux environment in which ROOT and other scientific computing tools can be used.
When using WSL, follow the Linux installation instructions.
ROOT can be installed using Homebrew:
brew install root
Alternatively, a compatible precompiled distribution can be downloaded from the official ROOT website.
ROOT version
This guide is based on ROOT 6.
Some functionality may differ between ROOT versions. Always ensure that your installation is compatible with the requirements of your assignment.
Verifying the installation
Open a terminal and execute:
root --version
If ROOT has been installed and configured correctly, the installed version should be displayed.
On Linux and macOS, you can also execute:
which root
This command displays the location of the ROOT executable.
Command not found
If the terminal cannot locate the root command,
ROOT may not be installed correctly, or its executable
directory may not be included in the PATH
environment variable.
For a manually installed binary distribution,
try sourcing thisroot.sh again.
The ROOT interactive environment
ROOT provides an interactive command-line environment in which C++ statements can be executed directly.
This environment is based on Cling, an interactive C++ interpreter.
Starting ROOT
To start ROOT, execute the following command in a terminal:
root
Alternatively, use:
root -l
The -l option suppresses the introductory ROOT banner.
After starting ROOT, an interactive prompt appears:
root [0]
You can now enter C++ statements directly.
Executing C++ statements
Try declaring a variable:
double x = 5.0;
Perform a mathematical operation:
double y = x * x;
Display the result:
std::cout << y << std::endl;
The expected output is:
25
Unlike a conventional compiled C++ program, the interactive ROOT environment allows individual statements to be entered and executed without manually compiling an entire source file.
Cling
Cling is an interactive C++ interpreter based on LLVM and Clang.
It supports interactive execution through just-in-time compilation, allowing users to experiment with C++ code without following the traditional manual compilation workflow.
Using ROOT classes interactively
ROOT classes can also be accessed directly from the interactive environment.
For example, create a histogram:
TH1D* h = new TH1D("h", "Example", 10, 0, 10);
Add several observations:
h->Fill(2.5);
h->Fill(4.2);
h->Fill(4.5);
h->Fill(7.1);
Display the histogram:
h->Draw();
A graphical window containing the histogram should appear if a graphical environment is available.
The histogram class and its methods will be discussed in detail in a later chapter.
Interactive ROOT commands
In addition to C++ statements, ROOT provides special interpreter commands.
These commands begin with a dot and are not part of the C++ programming language.
| Command | Description |
|---|---|
.q |
Exit the ROOT environment |
.help |
Display available interpreter commands |
.ls |
List objects in the current ROOT directory |
.pwd |
Display the current ROOT directory |
.x macro.C |
Execute a ROOT macro |
.L macro.C |
Load a ROOT macro |
.x macro.C+ |
Compile and execute a macro using ACLiC |
.L macro.C+ |
Compile and load a macro using ACLiC |
Interpreter commands and C++ statements
Interpreter commands are entered directly into the ROOT interactive environment.
They are not ordinary C++ statements and should not be inserted directly into C++ source files.
Exiting ROOT
To terminate the interactive session, execute:
.q
ROOT macros
Entering individual statements into the interactive environment is useful for experimentation.
However, scientific data analysis usually involves multiple operations that must be executed repeatedly.
A ROOT macro allows these operations to be stored in a source file and executed together.
ROOT macros commonly use the .C file extension.
What is a macro?
In ROOT, a macro is a C++ source file that can be executed or loaded through the ROOT environment.
It should not be confused with a C++ preprocessor
macro defined using #define.
Creating your first macro
Create a file named hello_root.C:
#include <iostream>
void hello_root()
{
std::cout << "Hello, ROOT!" << std::endl;
}
The macro contains two main components:
| Component | Purpose |
|---|---|
#include <iostream> |
Provides standard input and output functionality |
void hello_root() |
Defines the function executed by the macro |
std::cout |
Writes information to the standard output |
std::endl |
Inserts a newline and flushes the output stream |
Naming convention
For a named macro, use the same name for the source file and the function that serves as its entry point.
For example:
- File name:
hello_root.C - Function name:
hello_root()
This allows ROOT to identify the function to execute automatically.
Executing a macro
There are several ways to execute a ROOT macro.
root -l hello_root.C
ROOT starts and executes the macro.
First, start ROOT:
root -l
Then execute:
.x hello_root.C
root -l -b -q hello_root.C
ROOT executes the macro without opening graphical windows and terminates afterwards.
The expected output is:
Hello, ROOT!
Understanding command-line options
| Option | Description |
|---|---|
-l |
Suppress the introductory banner |
-b |
Enable batch mode |
-q |
Exit ROOT after processing the supplied macros |
-n |
Do not execute ROOT logon and logoff macros |
Batch mode is particularly useful when processing large datasets or executing analyses on remote servers.
Macros with arguments
A ROOT macro can accept arguments in the same way as an ordinary C++ function.
Create a file named calculate.C:
#include <iostream>
void calculate(double x, double y)
{
double result = x + y;
std::cout << "Result: "
<< result << std::endl;
}
Execute the macro from the ROOT environment:
.x calculate.C(3.0, 5.0)
Alternatively, execute it from the terminal:
root -l -q 'calculate.C(3.0, 5.0)'
The expected output is:
Result: 8
Default arguments
Arguments can also have default values:
#include <iostream>
void calculate(double x = 1.0, double y = 2.0)
{
std::cout << x + y << std::endl;
}
The macro can now be executed without explicitly providing arguments:
.x calculate.C
Or with custom arguments:
.x calculate.C(10.0, 20.0)
Configurable analyses
Macro arguments are useful for defining analysis parameters, such as:
- Input file names
- Number of events to process
- Histogram binning
- Particle selection thresholds
- Output directories
This makes an analysis more flexible and reproducible.
Loading macros
Executing a macro and loading a macro are two different operations.
The .x command executes a macro.
The .L command loads its definitions into the
current ROOT session without automatically executing
the named entry function.
Consider the following macro:
#include <iostream>
double square(double x)
{
return x * x;
}
Save it as square.C.
Load the macro:
.L square.C
The function can now be called interactively:
square(5.0);
The returned value is:
25
The function can be called repeatedly without reloading the source file.
What is the difference between .x and .L?
.x loads and executes the macro.
.L loads the definitions, allowing functions
and classes to be accessed later.
Loading a macro is useful when it contains reusable functions or class definitions.
Interpreted and compiled execution
ROOT supports multiple approaches to executing C++ code.
Interactive execution
C++ statements can be entered directly into the ROOT environment.
double x = 10.0;
std::cout << x << std::endl;
This approach is useful for:
- Testing individual statements.
- Inspecting ROOT objects.
- Experimenting with class methods.
- Performing small calculations.
Macro execution
C++ code can be stored in a macro and executed through the ROOT interpreter.
.x analysis.C
This approach is useful for developing and testing scientific analyses.
Compiling macros with ACLiC
ROOT provides a mechanism called ACLiC (Automatic Compiler of Libraries for CINT).
Despite its historical name, ACLiC is also available in modern ROOT versions using Cling.
A macro can be compiled and executed by adding a plus sign to its file name:
.x analysis.C+
Alternatively, it can be compiled and loaded:
.L analysis.C+
ROOT invokes the system compiler and creates a shared library that can be loaded into the current ROOT session.
To force recompilation, use two plus signs:
.x analysis.C++
Compilation requirements
Compiling a macro requires a compatible C++ compiler and a correctly configured ROOT development environment.
Explicitly including the required header files is recommended.
Comparison of execution methods
| Method | Command | Typical use |
|---|---|---|
| Interactive | root -l |
Experimentation |
| Macro execution | .x analysis.C |
Analysis development |
| Macro loading | .L analysis.C |
Reusable functions |
| Compiled macro | .x analysis.C+ |
Compiled analysis code |
| Standalone executable | ./analysis |
Independent applications |
Interpreted does not mean uncompiled
Cling uses just-in-time compilation internally.
Therefore, the distinction between interpreted and compiled ROOT macros concerns the execution and compilation workflow, rather than whether machine code is generated at all.
Standalone C++ programs
ROOT can also be used as a collection of C++ libraries without starting the ROOT interactive environment.
In this case, a conventional C++ program is created
with a main() function.
Create a file named analysis.cpp:
#include <TH1D.h>
#include <TCanvas.h>
int main()
{
TH1D hist(
"h",
"Example histogram;x;Counts",
10, 0.0, 10.0
);
hist.Fill(2.5);
hist.Fill(4.2);
hist.Fill(4.5);
TCanvas canvas("c1", "Example", 800, 600);
hist.Draw();
canvas.SaveAs("histogram.pdf");
return 0;
}
Compiling the program
On Linux, a standalone program can be compiled
using a compatible C++ compiler and root-config.
g++ analysis.cpp -o analysis $(root-config --cflags --libs)
The root-config utility provides information
about the installed ROOT environment.
| Command | Description |
|---|---|
root-config --version |
Display the ROOT version |
root-config --cflags |
Display compiler flags |
root-config --libs |
Display linker flags |
root-config --incdir |
Display the header directory |
root-config --libdir |
Display the library directory |
The resulting executable can be started using:
./analysis
The program generates a file named histogram.pdf.
Macros and standalone programs
A ROOT macro is executed or loaded through ROOT.
A standalone C++ program is compiled and linked against ROOT libraries, producing an independent executable.
Both approaches provide access to ROOT classes and functionality.
Working with header files
ROOT functionality is organised into C++ classes.
When using a class in a source file, its corresponding header should generally be included explicitly.
#include <TFile.h>
#include <TTree.h>
#include <TH1D.h>
#include <TCanvas.h>
Standard C++ headers can be included alongside ROOT headers:
#include <iostream>
#include <vector>
#include <cmath>
#include <TFile.h>
#include <TTree.h>
#include <TH1D.h>
| Header | Functionality |
|---|---|
<iostream> |
Standard input and output |
<vector> |
Dynamically sized arrays |
<cmath> |
Standard mathematical functions |
<TFile.h> |
ROOT file operations |
<TTree.h> |
Tree-based data structures |
<TH1D.h> |
One-dimensional histograms |
<TCanvas.h> |
Graphical output |
Explicit includes
The interactive ROOT environment can automatically make many ROOT declarations available.
Nevertheless, explicitly including the required headers makes source files easier to understand, maintain and compile independently.
Pointers to ROOT objects
ROOT frequently uses pointers to access, manipulate and manage objects.
However, not every ROOT object needs to be accessed through a pointer.
The choice between using an object directly and using a pointer depends on how the object is created, accessed and managed throughout the program.
Objects and pointers
Consider the following histogram declaration:
TH1D h("h", "Distribution", 100, 0, 10);
This statement creates a histogram object directly.
Its methods can be accessed using the dot operator:
h.Fill(2.5);
h.Draw();
Alternatively, a pointer to a histogram can be declared:
TH1D* h_ptr = &h;
The pointer stores the memory address of the existing histogram.
Its methods can be accessed using the arrow operator:
h_ptr->Fill(2.5);
h_ptr->Draw();
The following expressions are equivalent:
h.Fill(2.5);
h_ptr->Fill(2.5);
(*h_ptr).Fill(2.5);
All three expressions operate on the same histogram.
A pointer is not an object
Declaring a pointer does not necessarily create a new ROOT object.
TH1D* h_ptr = nullptr;
This statement creates a pointer that does not currently refer to any histogram.
Attempting to access an object through a null pointer results in undefined behaviour.
When should we use objects directly?
Direct object creation is generally appropriate when:
- The object is created locally.
- Its lifetime is limited to the current scope.
- Its type is known at compile time.
- Dynamic allocation is unnecessary.
- The object does not need to survive the function in which it was created.
For example:
void analyse()
{
TH1D h("h", "Distribution", 100, 0, 10);
h.SetDirectory(nullptr);
h.Fill(2.5);
h.Fill(3.1);
h.Print();
}
The histogram is created when the corresponding declaration is executed.
It is automatically destroyed when the function terminates.
This approach simplifies memory management because the programmer does not need to explicitly destroy the object.
Prefer automatic lifetime when possible
If an object is only required within a particular function or scope, creating it directly is often the simplest and safest approach.
When should we use pointers?
Pointers are particularly useful when:
- Accessing existing objects stored in ROOT files.
- Accessing objects returned by ROOT methods.
- Referring to objects without copying them.
- Representing an optional object.
- Working with dynamically allocated objects.
- Using polymorphism through a common base class.
Retrieving objects from ROOT files
Consider a ROOT file containing a histogram named
h_pt.
TFile file("events.root", "READ");
TH1D* h = file.Get<TH1D>("h_pt");
The Get() method returns a pointer to the
retrieved object.
It does not return the histogram by value.
The pointer provides access to the histogram without requiring a separate copy.
Before accessing the object, verify that it was successfully retrieved:
if (h != nullptr)
{
h->Draw();
}
If the requested object does not exist or has an incompatible type, the typed retrieval returns a null pointer.
Object lifetime
A histogram retrieved from a ROOT file is normally associated with that file.
Closing the file may destroy the histogram.
The pointer does not automatically become a null pointer when the object is destroyed.
Accessing it afterwards may result in undefined behaviour.
Accessing trees
Trees are commonly accessed through pointers because they are retrieved from existing ROOT files.
TFile file("events.root", "READ");
TTree* tree = file.Get<TTree>("collisionTree");
if (tree != nullptr)
{
tree->Print();
}
The pointer provides access to the tree associated with the file.
Accessing objects returned by ROOT methods
Many ROOT methods return pointers to objects.
For example:
TH1D h("h", "Distribution", 100, 0, 10);
TAxis* axis = h.GetXaxis();
axis->SetTitle("Transverse momentum");
The GetXaxis() method returns a pointer
to the existing axis object belonging to
the histogram.
No new axis needs to be created.
The same operation can be written more compactly as:
h.GetXaxis()->SetTitle("Transverse momentum");
The axis is owned by the histogram and must not be deleted independently.
Dynamic allocation
ROOT objects can also be created dynamically
using the new operator.
TH1D* h = new TH1D(
"h",
"Distribution",
100,
0,
10
);
h->SetDirectory(nullptr);
Unlike a local object with automatic storage duration, a dynamically allocated object is not automatically destroyed when its pointer goes out of scope.
The programmer must ensure that the object is eventually destroyed.
delete h;
h = nullptr;
Dynamic allocation can be useful when the required lifetime of an object extends beyond the scope in which it was created.
For example, a function may create and return a histogram:
TH1D* createHistogram()
{
TH1D* h = new TH1D(
"h",
"Distribution",
100,
0,
10
);
h->SetDirectory(nullptr);
h->Fill(2.5);
return h;
}
The caller receives a pointer to the histogram and is responsible for deleting it.
TH1D* h = createHistogram();
h->Print();
delete h;
Returning pointers to local objects
The following implementation is incorrect:
TH1D* createHistogram()
{
TH1D h("h", "Distribution", 100, 0, 10);
h.SetDirectory(nullptr);
return &h;
}
The histogram is destroyed when the function terminates.
The returned pointer refers to an object that no longer exists.
Such a pointer is called a dangling pointer.
Pointers versus references
A pointer is not the only mechanism for accessing an existing object without copying it.
C++ also provides references.
void fillHistogram(TH1D& h)
{
h.Fill(2.5);
}
The histogram can be passed directly:
TH1D h("h", "Distribution", 100, 0, 10);
fillHistogram(h);
Alternatively, the function could accept a pointer:
void fillHistogram(TH1D* h)
{
if (h != nullptr)
{
h->Fill(2.5);
}
}
In this case, the address of the histogram must be passed:
fillHistogram(&h);
Both implementations modify the original histogram without creating a copy.
References are generally preferable when the object is required to exist.
Pointers are useful when the absence of an object is a valid possibility.
Polymorphism
Many ROOT classes inherit from common base classes.
For example, TH1D and TH1F both inherit
from TH1. (For further details, see chapter on ROOT histogram classes)
flowchart TD
A["TH1"] --> B["TH1D"]
A --> C["TH1F"]
A --> D["TH1I"]
A pointer to the base class can therefore refer to objects of different derived classes.
TH1D h_double("hd", "Double", 100, 0, 10);
TH1F h_float("hf", "Float", 100, 0, 10);
TH1* h = &h_double;
h->Fill(2.5);
h = &h_float;
h->Fill(3.5);
This allows functions to operate on different histogram classes through a common interface.
void printStatistics(const TH1* h)
{
if (h != nullptr)
{
std::cout << h->GetMean() << '\n';
std::cout << h->GetStdDev() << '\n';
}
}
The function can accept pointers to different histogram types.
Polymorphism is also possible through references to the base class.
Smart pointers
Modern C++ provides smart pointers that automatically manage dynamically allocated objects.
For example, std::unique_ptr represents
exclusive ownership of an object.
#include <memory>
#include <TH1D.h>
auto h = std::make_unique<TH1D>(
"h",
"Distribution",
100,
0,
10
);
h->SetDirectory(nullptr);
h->Fill(2.5);
The histogram is automatically destroyed when the smart pointer goes out of scope.
An explicit call to delete is unnecessary.
ROOT ownership and smart pointers
ROOT may automatically associate certain objects with a directory or file.
When using a smart pointer to own a histogram, ensure that ROOT does not independently manage its lifetime.
For histograms, this can be achieved using:
h->SetDirectory(nullptr);
Do not place an object owned by a ROOT file or another ROOT object into an owning smart pointer without first resolving its ownership.
Otherwise, multiple owners may attempt to destroy the same object.
Object access and ownership
Using a pointer does not necessarily mean that the programmer owns the object.
Consider the following examples:
| Expression | Object owner or lifetime manager |
|---|---|
TH1D h(...) |
Automatic lifetime, provided it is not managed by a ROOT directory |
TH1D* p = &h |
Unchanged; the pointer only refers to h |
new TH1D(...) |
Depends on directory association and ownership |
file.Get<TH1D>("h") |
Normally the ROOT directory or file |
h.GetXaxis() |
The histogram |
std::make_unique<TH1D>(...) |
Smart pointer, provided ROOT ownership is disabled |
The distinction between accessing and owning an object is fundamental.
A pointer may simply provide access to an object managed elsewhere.
Do not delete every pointer
A pointer does not indicate whether the referenced object should be deleted by the programmer.
Only destroy objects whose lifetime you are responsible for managing.
Which approach should I use?
flowchart TD
A["Do you need a ROOT object?"] --> B{"Does the object already exist?"}
B -->|Yes| C{"Does the ROOT method return a pointer?"}
C -->|Yes| D["Use the returned pointer"]
C -->|No| E["Consider a reference"]
B -->|No| F{"Is automatic lifetime sufficient?"}
F -->|Yes| G["Create the object directly"]
F -->|No| H["Consider a smart pointer or returning by value"]
D --> I["Check object ownership"]
H --> I
General recommendation
Prefer direct objects when automatic lifetime is sufficient.
Use references when passing required existing objects to functions.
Use raw pointers when ROOT returns them or when optional, non-owning access is required.
Prefer smart pointers for dynamic allocation when compatible with ROOT's ownership model.
Always distinguish object access from object ownership.
Common problems
ROOT command not found
Check whether ROOT is installed and whether
its executable directory is included in PATH.
For a manually installed distribution:
source /path/to/root/bin/thisroot.sh
Macro file not found
Verify the file name and the current working directory.
Linux file names are case-sensitive.
For example, analysis.C and analysis.c
are different file names.
Unknown type name or undeclared identifier
Check whether the appropriate header file has been included.
Also verify the spelling of class names, variable names and function names.
A graphical window does not appear
Check whether ROOT is running in batch mode.
When working on a remote server or in WSL, a graphical environment may need to be configured.
Alternatively, save the graphical output
directly to a file using SaveAs().
The macro cannot be compiled
Check the compiler error messages.
Common causes include missing headers, syntax errors, incompatible data types and an incorrectly configured compiler environment.
Exercises
Exercise 1 — Interactive environment
Start ROOT and declare two floating-point variables.
Calculate their sum, product and ratio, and display the results.
Exercise 2 — Your first macro
Create a macro that prints the integers from 1 to 10 and their squares.
Execute the macro from both the terminal and the ROOT interactive environment.
Exercise 3 — Macro arguments
Modify the previous macro so that the upper limit is provided as a function argument.
Test the macro using different input values.
Exercise 4 — Loading functions
Create a macro containing a function that calculates the magnitude of a two-dimensional vector:
Load the macro using .L and evaluate the
function for several input values.
Exercise 5 — Execution methods
Explain the differences between:
.x analysis.C
.L analysis.C
.x analysis.C+
Identify a situation in which each execution method would be useful.