Problem with #include

Dear Collegues,

I am trying to split a macro into multiple files. This turned out to be rather complex…

e.g:

// in main.C

void main(){

// The follwing part I would lke to move to the file “prologue.cpp”

TFile *file = new TFile("data.root");
TTree *tree = (TTree*) file->Get("eventbranch");
UInt_t 	x;
UInt_t	y;
tree->SetBranchAddress("x",&x);
tree->SetBranchAddress("y",&y);

// Until here.

tree->GetEntry(23);

    cout << x*y << endl;

}

Then I would like to do this:

// in main2.C

void main2(){
#include “prologue.cpp”;
// or gROOT->LoadMacro(“prologue.cpp”);

tree->GetEntry(23);
    cout << x*y << endl;

}

// in prologue.cpp

TFile *file = new TFile("data.root");
TTree *tree = (TTree*) file->Get("eventbranch");
UInt_t 	x;
UInt_t	y;
tree->SetBranchAddress("x",&x);
tree->SetBranchAddress("y",&y);

However, it does not work.
Thank you very much for your help! [-o<

Maybe I should add that I do not plan to compile the script.
I run it like:

root -l main2.C

Hi,

Here is a possible solution:
main2.cpp:

[code]#include “prologue.cpp”

void main2()
{
UInt_t x = 0, y = 0;
TTree tree = prologue(&x, &y);
if (tree) tree->GetEntry(23);
cout << x
y << endl;
}
[/code]
And prologue.cpp:

TTree *prologue(UInt_t *x, UInt_t *y) { TTree *tree = 0; TFile *file = TFile::Open("data.root"); if (file) tree = (TTree*) file->Get("eventbranch"); if (tree) { tree->SetBranchAddress("x", x); tree->SetBranchAddress("y", y); } return tree; }
Cheers, Bertrand.

Dear Bertrand,

thank you very much for your reply! As far as I understand, you define a function (prologue) which will return the tree. For this particular situation this should work fine! However, I am also searching for a more general sollution. I would like to be able to “out source” any line from the main script to a seperate file without the need to define a function. I was told by several collegues that #include should do this, however, they do not know ROOT but only use C++.
Do you have an idea how I could do this?

Thank you very much!
Cheers

Sébastien

Hi Sébastien,

Yes, you can use global variables (which is an ugly solution…):
main2.cpp:

[code]#include “prologue.cpp”

void main2()
{
prologue();
if (tree) tree->GetEntry(23);
cout << x*y << endl;
}[/code]
And prologue.cpp:

[code]TTree *tree = 0;
UInt_t x = 0, y = 0;

void prologue()
{
TFile file = TFile::Open(“data.root”);
if (file) tree = (TTree
) file->Get(“eventbranch”);
if (tree) {
tree->SetBranchAddress(“x”, &x);
tree->SetBranchAddress(“y”, &y);
}
}[/code]
Cheers, Bertrand.

Hi Bertrand,

thank you again for your replay! I will need some more time to digest your suggestion. :blush:

Hi Bertrand,

I had some time to look at your suggestion and it works well! The global variables, even thought this aproach is uglly, seam to do the job.

Thank you again for your help!

Cheers,

Sébastien