Standalone C program runs without error but doesn't display histogram

Hi! I have a very simple C++ program that runs fine in the interpreter, but when I convert it to standalone code, fails to draw the only histogram.

// header imports
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
#include <string>
#include <TROOT.h>
#include <TChain.h>
#include <TFile.h>
#include "TSystem.h"
#include "TMath.h"
#include "TH1.h"
#include "TRandom3.h"
#include "TCanvas.h"

int main()
{	
	// Define a new canvas
	TCanvas *canvas = new TCanvas("c1", "testing");
	//change canvas height
	canvas->SetWindowSize(900, 600);

	int bin_length = 100;
	int i;
	TH1 *hist1 = new TH1F("hist1", "this should be a normal histogram", bin_length, 0,4);

	canvas->cd(1);

	TRandom3 *ran = new TRandom3();

	for(i=0;i<30000;i++)
	{
		hist1->Fill(ran->Gaus(1,1), ran->Gaus(1,1));
	}

	std::cout << ran->Gaus(1,1) << std::endl;
	hist1->Draw();
	return 0;
}

The program runs without any errors, compiles with no errors or warnings, and successfully displays a random number. However, it doesn’t display the histogram. Any ideas what might be causing this?

Thanks in advance!

1 Like

The program closes right after the Draw call, you have to let it keep running. Just add #include "TApplication.h", instantiate TApplication app("app", nullptr, nullptr); at the beginning of your main and call app.Run(); right before the return 0;.

1 Like

@eguiraud
This works perfectly! Thank you so much!!

1 Like

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