36.9. Common Geant4 Errors and Solutions
Table of Contents
Introduction
When you start with Geant4 it is very common to run into compilation errors, crashes, and confusing runtime messages. This chapter collects some of the most frequent issues beginners see and suggests concrete checks and fixes. It does not aim to be exhaustive, but to give you a first checklist whenever something goes wrong.
Throughout this chapter, pay special attention to messages in the terminal. Geant4 usually tells you what failed, but the useful part can be easy to miss among all the output.
When you see an error, always read the first clear error line carefully before changing code. The first message is usually the most important clue.
CMake and Build Errors
Most Geant4 applications are built with CMake. Problems usually fall into a few categories: Geant4 cannot be found, libraries are not linked, or you try to compile without re-running CMake after changing configuration.
Typical CMake error messages and likely causes are shown in the table.
| Symptom / Message fragment | Likely cause |
|---|---|
Could NOT find Geant4 | Geant4 installation not found or env not set |
geant4-config.cmake not found | Wrong or missing Geant4_DIR |
| Undefined references to Geant4 symbols at link time | Missing target_link_libraries(... Geant4::G4...) |
Includes not found, G4RunManager.hh missing | Wrong or missing include directories |
If CMake cannot find Geant4, check whether you have sourced the Geant4 environment script, for example source /path/to/geant4.sh, or set Geant4_DIR to the Geant4 installation's CMake directory before running CMake. Then delete your build directory or at least the CMakeCache.txt file and re-run CMake.
If you see link errors like undefined reference to G4RunManager::G4RunManager(), make sure your CMakeLists.txt uses find_package(Geant4 REQUIRED) and links against the Geant4 libraries that CMake exports. For a basic application, this usually means linking with Geant4::G4run, Geant4::G4event, Geant4::G4geometry, and others, or using the standard Geant4 example template that links a catch-all Geant4 target.
Whenever you change the Geant4 installation, or enable multithreading or visualization, reconfigure the project by removing CMakeCache.txt and running CMake again. Otherwise CMake can keep stale options that no longer match your system.
Geometry Construction Problems
Many crashes happen during geometry construction, inside the Construct() method of your detector construction class. Common issues include null pointers from G4NistManager, missing world volumes, and uninitialized materials.
If the program terminates with an exception mentioning your detector construction, read the message for hints like "World volume not defined" or "Solid overlaps detected".
A very typical beginner error is to forget to return the world physical volume from Construct(). Geant4 expects a G4VPhysicalVolume* that represents the world. If you accidentally return a logical volume, or a local variable that has gone out of scope, the program will fail quickly.
Another frequent problem is constructing a volume with a null material. This can happen if G4NistManager::FindOrBuildMaterial("G4_AIR") fails because of a typo in the material name. In that case, the returned pointer is null and using it in a G4LogicalVolume constructor leads to a runtime error.
Always check that material pointers obtained from G4NistManager are not null before using them to build logical volumes.
If your program prints warnings about geometry overlaps, the problem is usually that inner volumes are larger than the mother volume, or that two volumes overlap each other. Use Geant4's built-in overlap checking, such as the /geometry/test macro commands, and visual inspection to find and fix these overlaps. Reducing dimensions by a small margin is often enough to avoid subtle overlaps.
Missing or Incorrect Materials
Material definition issues can cause both crashes and physically wrong results. Common errors include using incorrect density units, defining elements but never using them, or mistyping NIST material names.
A typical mistake is to specify density with the wrong units, such as 1.0 * g/m3 when you meant grams per cubic centimeter. This leads to extremely low or high densities and unrealistic particle interactions.
Another problem is to confuse elements and materials. Defining an element like silicon is not enough; you still need to define a material that uses that element, or request a ready-made material from the NIST database.
Geant4 will print informative messages when you ask G4NistManager for an unknown material. Look for output like "Material G4_AIRR not found" which indicates a typo.
Always use Geant4 units explicitly in material definitions and verify the density scale with a quick calculation, for example by estimating mass of a simple volume.
If you suspect material issues, print material information at runtime. Geant4 provides methods to print compositions, densities, and state of materials for debugging purposes. This helps to check that you are really simulating what you think you are simulating.
Physics List and Process Errors
If you see messages about missing particles or processes, the error is usually related to the physics list. Typical symptoms include tracks that stop immediately, warnings that a particle is not defined, or messages about no physics processes assigned.
If you implement your own physics list and forget to register electromagnetic physics, particles will propagate without interacting, or with only a subset of processes. For most applications it is safer to start with a reference physics list such as FTFP_BERT and only later customize.
You may also run into warnings about cut values if you use default cuts that are too large for a small detector, or too small leading to long run times. These are not fatal errors, but they can affect your results.
Another common situation is using a particle type in the primary generator that is not available in the current physics list. Geant4 usually prints a message that the particle is unknown, and sometimes replaces it or aborts. Carefully check the particle name strings you use and make sure that the physics list includes that particle.
If tracks do not interact as expected, first suspect the physics list and verify that it is appropriate and correctly registered with the run manager.
Sensitive Detector and Hits Issues
Sensitive detector problems rarely produce clear compiler errors, but they can cause missing output, empty hit collections, or segmentation faults. The main sources of trouble are incorrect pointer management in hit classes, forgetting to assign the sensitive detector to a logical volume, or mishandling hit collections.
If your output files contain no hits and your analysis shows all zeros, the first check is whether the logical volumes that should act as detectors actually have a sensitive detector assigned. Sensitive detectors are attached to logical volumes, not physical volumes, so attaching to the wrong object will silently fail to produce hits in the desired place.
Another frequent error is failing to register the hits collection in the event, so that you cannot retrieve it later in the event or run actions. Geant4 requires a consistent use of collection IDs and names. If you create multiple hit collections, verify that their names match between sensitive detector, event action, and analysis code.
When you implement a custom hit class, be careful with memory allocation and ownership. Geant4 collections of hits are often responsible for deleting the contained hits at the end of an event. If you try to manage the same memory yourself, or keep raw pointers beyond the event scope, you can easily trigger crashes.
If you see segmentation faults inside ProcessHits, print diagnostic messages for each call to check which steps reach your sensitive detector, and verify that you do not dereference null pointers from G4Step, G4StepPoint, or associated volumes.
Primary Generator and Source Problems
Particle source issues often manifest as no events being simulated, particles starting outside the intended geometry, or unexpected direction and energy distributions. Common mistakes include creating the primary generator action but not registering it, misusing the particle gun, or misconfiguring the General Particle Source in macros.
If your simulation runs but no tracks appear in the visualization, confirm that the run manager knows about your primary generator action. In multithreaded applications you usually register it in your action initialization class, not directly in main.
When using the particle gun, remember that its default position and direction may not match your geometry. If you forget to set the position, particles can start at the origin, possibly outside or in the middle of materials you did not intend. Incorrect units in energy settings, such as using 1.0 instead of 1.0 * MeV, also lead to unrealistic sources.
For the General Particle Source, the configuration is usually driven by macro commands. If you mistype commands or specify incompatible options, Geant4 prints GPS warnings at initialization. Always review the macro output at startup and confirm that your particle type, position distribution, angular distribution, and energy distribution are accepted.
Whenever particles do not appear where or how you expect, log the primary particle properties in your PrimaryGeneratorAction for the first few events.
Analysis and Output Issues
Problems in analysis code usually show up as empty histograms, missing files, or output files that are smaller than expected. Typical causes include not opening or closing the analysis manager correctly, forgetting to fill histograms and ntuples, or writing output only from the master thread in a multithreaded run.
If your program finishes but the expected output file does not exist, verify that you called the analysis manager's OpenFile() before running and Write() and CloseFile() at the end of the run. The order and placement of these calls matters. If they occur in user actions that are not registered or not called, the analysis system may never create the file.
Empty histograms can result from filling them with incorrect IDs, such as off-by-one errors or using a histogram ID that was never created. Always store and reuse the IDs returned by the analysis manager when you create histograms or ntuples.
In multithreaded runs, it is easy to misunderstand how data from different threads is combined. If you see only partial data, check that you use the thread-safe analysis manager approach recommended for your Geant4 version, and that you do not manually write files from worker threads unless you know precisely how you will merge them.
If output is empty, first check that you fill histograms or ntuples in the same run where you open and later close the analysis file.
Segmentation Faults and Crashes
Segmentation faults are often the most intimidating errors for beginners. In Geant4 applications, they typically come from dereferencing null or invalid pointers, using objects after they have been deleted, or constructing geometry with invalid parameters.
Common triggers include using geometric dimensions that are negative or zero, accessing G4Step or G4Track objects outside the scope of the stepping or tracking actions, or keeping references to volumes that are redefined or deleted. Whenever you implement user actions, be careful not to store raw pointers to Geant4 objects beyond the function in which they are delivered, unless the documentation explicitly allows it.
If the crash occurs soon after starting the run, it is often related to geometry or physics initialization. Look for diagnostic messages right before the crash. To narrow down the source, try running only one or two events, or disable some parts of your user actions to see whether the crash persists.
Using a debugger such as gdb can be very helpful. Running your program under a debugger and inspecting the backtrace at the moment of the crash reveals which function and line caused the fault. This information, combined with Geant4's verbose mode for geometry or tracking, usually makes it possible to locate the bug.
Never assume that a segmentation fault is "random". It almost always comes from undefined behavior in your code, such as invalid pointers or invalid geometry parameters.
Using Geant4 Verbose Output for Debugging
Geant4 provides many verbose levels and categories that can help you understand what happens during a run. These are controlled through macro commands and sometimes through code. For beginners, increasing verbosity is one of the simplest ways to debug without changing C++.
Geometry verbose modes can list all volumes, check for overlaps, and print navigation steps. Tracking verbose modes can display each step of a track, including positions, energies, and processes. Physics processes can also be made more verbose to show how they contribute to energy loss and scattering.
A practical strategy is to start with normal verbosity and gradually increase it in specific areas where you see problems, for example only for a particular particle type or region. This prevents the output from becoming overwhelming.
Use high verbose levels only for a few events, otherwise the output becomes huge and performance can drop drastically.
By combining verbose output with careful reading of error messages and a debugger when needed, you can usually track down even subtle issues in your Geant4 applications.
Views: 9
KAHIBARO