How do I get an object from a file?

Hello,
I am totally new to ROOT, pretty much new to coding altogether and I need help. I need to get a histogram out of a TFile, here is what I have: (I know this program itself does not do much, but it fits into a bigger program.)

void minihstack(){
  TFile file("histograms.root"); // Let's open the TFile
  TH1F * h_muon0_pt;  // Get the Histogram out 
  file.GetObject("h_muon0_pt",h_muon0_pt);
  h_muon0_pt->Draw();
}

I always get “warning: null passed to a callee that requires a non-null argument”. Obviously the line with GetObject is wrong, but I cannot find a way to correct it. I am positive the histogram h_muon0_pt is in the histograms.root file.
Thank you very much for any ideas on how to fix this!

file.ls();

For info your code is working with an file I have:

{
  TFile file("hsimple.root"); // Let's open the TFile
  TH1F * hpx;  // Get the Histogram out
  file.GetObject("hpx",hpx);
  hpx->Draw();
}

as Wile suggest it would be good to see the content of your file.

1 Like

Also you better do:

{
  auto file = new TFile("histograms.root"); // Let's open the TFile
  TH1F * h_muon0_pt;  // Get the Histogram out
  file->GetObject("h_muon0_pt",h_muon0_pt);
  h_muon0_pt->Draw();
}

Otherwise you will get an empty plot.

1 Like

Actually, in the original macro, you simply need h_muon0_pt->DrawCopy(); :wink:

Yes that’s an other way …

Thank you so much, it works! There was a semicolon behind the name of the histogram for some odd reason and I missed that.
And now the plot is not empty, either :smiley: