return false;
 }
 
-/* Register a kind of selftest that calls the test function once for each
-   gdbarch known to GDB.  */
+/* Generate a selftest for each gdbarch known to GDB.  */
 
-void
-register_test_foreach_arch (const std::string &name,
-                           self_test_foreach_arch_function *function)
+static std::vector<selftest>
+foreach_arch_test_generator (const std::string &name,
+                            self_test_foreach_arch_function *function)
 {
+  std::vector<selftest> tests;
   std::vector<const char *> arches = gdbarch_printable_names ();
+  tests.reserve (arches.size ());
   for (const char *arch : arches)
     {
       if (skip_arch (arch))
             reset ();
           });
 
-      std::string test_name
-       = name + std::string ("::") + std::string (arch);
-      register_test (test_name, test_fn);
+      tests.emplace_back (string_printf ("%s::%s", name.c_str (), arch),
+                         test_fn);
     }
+  return tests;
+}
+
+/* See selftest-arch.h.  */
+
+void
+register_test_foreach_arch (const std::string &name,
+                           self_test_foreach_arch_function *function)
+{
+  add_lazy_generator ([=] ()
+                     {
+                       return foreach_arch_test_generator (name, function);
+                     });
 }
 
 void
 
        }
        -re "Selftests have been disabled for this build.\r\n$gdb_prompt $" {
            unsupported $test
+           set num_ran 0
            set enabled 0
        }
     }
 
-    return $enabled
+    return [list $enabled $num_ran]
 }
 
 # Test completion of command "maintenance selftest".
 }
 
 with_test_prefix "no executable loaded" {
-    set self_tests_enabled [run_selftests ""]
+    set res [run_selftests ""]
+    set self_tests_enabled [lindex $res 0]
+    set num_ran [lindex $res 1]
+}
+
+if { $self_tests_enabled && ![is_remote host] } {
+    # Check that we have the same amount of selftests whatever the
+    # initialization order of GDB.
+    with_test_prefix "reversed initialization" {
+       save_vars { env(GDB_REVERSE_INIT_FUNCTIONS) } {
+           if [info exists env(GDB_REVERSE_INIT_FUNCTIONS)] {
+               unset env(GDB_REVERSE_INIT_FUNCTIONS)
+           } else {
+               set env(GDB_REVERSE_INIT_FUNCTIONS) 1
+           }
+
+           set res [run_selftests ""]
+           gdb_assert "$num_ran == [lindex $res 1]" \
+               "selftest not dependent on initialization order"
+       }
+    }
 }
 
 with_test_prefix "executable loaded" {