Include ROOT in cpp code

Dears rooters,
Usually i create a macro and I run it in root. But now I have a more complex cpp code, composed by a header and class files, so I would like to include root in this program. How can I do it? I have seen on the web many examples with different methos to compile, but were not very clear… so can someone explain me step by step how can I do it please?

thanks a lot :slight_smile:

Here is a simple program and a Makefile for it. I hope this is enough for you to modify for your purposes.

#include <iostream>

#include "TFile.h"
#include "TKey.h"

void indent(int depth)
    for (int i = 0; i < depth; ++i)
        printf(" ");

void list(TKey*, int);
void list(TObject*, int);
void list(TDirectory*, int);

void list(TKey *key, int depth)
    printf("TKey: %s:%s;%d\n", key->GetClassName(), key->GetName(), (int)key->GetCycle());

    if (TObject* obj = key->ReadObj()) {
       if (strncmp("TDirectory", key->GetClassName(), 10) == 0) {
            if (TDirectory *dir = dynamic_cast<TDirectory*>(obj))
                list(dir, depth+1);
       } else {

void list(TObject *obj, int depth)
    printf("%s: %s\n", obj->ClassName(), obj->GetName());

    if (TDirectory *dir = dynamic_cast<TDirectory*>(obj))
        list(dir, depth+1);

void list(TDirectory *dir, int depth)
    for (TObject* obj : *(dir->GetList()))
        list(obj, depth+1);

    for (TObject* obj : *(dir->GetListOfKeys()))
        if (TKey *key = dynamic_cast<TKey*>(obj))
            list(key, depth+1);

int main(int argc, char **argv)
    for (int i = 1; i < argc; ++i) {
        TFile f(argv[i], "read");

        if (f.IsZombie()) {
            fprintf(stderr, "%s: error opening file: %s\n", basename(argv[0]), argv[i]);

        printf("TFile: %s\n", f.GetName());

        for (TObject* obj : *(f.GetListOfKeys()))
            if (TKey *key = dynamic_cast<TKey*>(obj))
                list(key, 1);


    return 0;



CXXFLAGS=-Wall -O2 -march=native -std=c++11

ROOTFLAGS=$(shell root-config --cflags)
ROOTLIBS=$(shell root-config --libs)

all: root-ls

debug: all
debug: CXXFLAGS += -DDEBUG -g


	$(RM) -rf root-ls

thanks a lot amadio!! this works!! :slight_smile:

now my problem is that I have more than 1 cpp file, since I have an header and a class file to compile with the main… how can I do?
sorry for the probably stupid question but I’m a very beginner programmer…

thanks a lot :slight_smile:


g++ -o myExe myFile_0.cpp myFile_1.cpp ... myFile_N.cpp -I ./ `root-config --cflags --libs`


thanks a lot, it works!!! :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.