Filling a ROOT ntuple from a C program

Hi,

Does anyone have sample code to do simple things in ROOT called from a C main function? For example I want to fill an ntuple and write it to disk using C code.

I wrote a bit of test code and it seems to work. I thought it would be more complicated or there would be issues with linkage of c vs. c++ libs. If someone has suggestions to improve this please feel free to comment.

nt.c (290 Bytes)
ntFill.h (287 Bytes)
ntFill.cxx (249 Bytes)

Here’s the Makefile:

ROOT_CFLAGS=`root-config --cflags`
ROOT_LIBS=`root-config --libs`
CINC=-I.

.PHONY: all clean

.DELETE_ON_ERROR:

all: nt

libntFill.so: ntFill.cxx ntFill.h
        $(CXX) -shared $(ROOT_CFLAGS) ntFill.cxx -o $@ $(ROOT_LIBS)

nt: nt.c libntFill.so
        $(CC) -o $@ $< ./libntFill.so

clean:
        rm -f libntFill.so nt

Hi,

Why are you using C and not C++? It will be (may?) possible to “mix” them, but you are going to have all sorts of issues if you do. Sticking with just C++ works much better if possible.

cheers,
  Charles

[quote=“cplager”]Hi,

Why are you using C and not C++? It will be (may?) possible to “mix” them, but you are going to have all sorts of issues if you do. Sticking with just C++ works much better if possible.

[/quote]

Someone has existing C code and they want to add functionality for histograms and trees. I think they previously used cfortran and PAW but they’re exporting it to system where the admins only have ROOT and don’t want to install the other stuff.

[quote=“whanlon”][quote=“cplager”]Hi,

Why are you using C and not C++? It will be (may?) possible to “mix” them, but you are going to have all sorts of issues if you do. Sticking with just C++ works much better if possible.

[/quote]

Someone has existing C code and they want to add functionality for histograms and trees. I think they previously used cfortran and PAW but they’re exporting it to system where the admins only have ROOT and don’t want to install the other stuff.[/quote]

A couple of points:

  • Most C code compiles as is as C++ code.

  • Most modern systems that have C have the C++ compiler.

  • You can mix C/C++, but the piece of code that calls ROOT needs to be in C++. You could possibly get away with small C++ interfaces (depending on what you are doing), but the more complicated you want your program to be, the harder this will be.

Good luck. :smiley:

Cheers,
Charles