diff --git a/core/dictgen/res/rootcling_impl.h b/core/dictgen/res/rootcling_impl.h
index f86e971ba7f93cda91555f50754215f36c88924e..cbd1133cf927d70eca063e88d7ccf863d8ec0fcf 100644
--- a/core/dictgen/res/rootcling_impl.h
+++ b/core/dictgen/res/rootcling_impl.h
@@ -20,6 +20,7 @@ namespace RootCling {
    struct DriverConfig {
       bool fBuildingROOTStage1 = false;
       std::string fLLVMResourceDir;
+      const char** fPRootDir = nullptr;
 
       // Function that might (rootcling) or might not (rootcling_stage1) be there.
       const char ** * (*fTROOT__GetExtraInterpreterArgs)() = nullptr;
diff --git a/core/dictgen/src/rootcling_impl.cxx b/core/dictgen/src/rootcling_impl.cxx
index 304cbbb5bb4879a2f048a6a0fdfb688e0e6ac2fb..f775ac382c49ad1e5fc25b8707eff3b0d158a80d 100644
--- a/core/dictgen/src/rootcling_impl.cxx
+++ b/core/dictgen/src/rootcling_impl.cxx
@@ -716,11 +716,22 @@ void SetRootSys()
          // There was no slashes at all let now change ROOTSYS
          return;
       }
-      int ncha = strlen(ep) + 10;
-      char *env = new char[ncha];
-      snprintf(env, ncha, "ROOTSYS=%s", ep);
-      putenv(env);
-      delete [] ep;
+      if (gDriverConfig) {
+         const char** pRootDir = gDriverConfig->fPRootDir;
+         if (gBuildingROOT && pRootDir && !strcmp(*pRootDir, ep)) {
+            *pRootDir = ep; // leaks...
+         } else {
+            delete [] ep;
+         }
+      } else {
+         // stage 1.
+         int ncha = strlen(ep) + 10;
+         char *env = new char[ncha];
+         snprintf(env, ncha, "ROOTSYS=%s", ep);
+         putenv(env);
+         delete [] ep;
+      }
+
    }
 }
 
diff --git a/main/src/rootcling.cxx b/main/src/rootcling.cxx
index 1e2e6c93c2af20921b2312154ec973cbc1ea9ada..833176e7209f88c1f13d27deab9e59b80957eff0 100644
--- a/main/src/rootcling.cxx
+++ b/main/src/rootcling.cxx
@@ -33,6 +33,7 @@ int main(int argc, char **argv)
 #endif
 
    config.fBuildingROOTStage1 = false;
+   config.fPRootDir = &gRootDir;
    config.fTROOT__GetExtraInterpreterArgs = &TROOT__GetExtraInterpreterArgs;
    config.fTCling__GetInterpreter = &TCling__GetInterpreter;
    config.fInitializeStreamerInfoROOTFile = &InitializeStreamerInfoROOTFile;