Search code examples
c++headerredefineopencascade

Can I redefine a c++ static const defined in a OpenCascade/OCCT header at runtime?


Maybe this is simple but I would like to dynamically redefine a constant set in a library header, so that I don't have to recompile it every time it should be changed. In OpenCascade's Precision.hxx the constant "Precision::Confusion" is defined as:

class Precision 
{
public:
...
  static Standard_Real Confusion() { return 1.e-7; }
...
}

Is it be possible to redefine it in a (c++) function at runtime?


Solution

  • If you want to play with this constant affecting everything in your code and in OCCT itself without re-compilation of every piece of code using it, you may move definition of constant to .cxx file.

    // Precision.hxx
    class Precision
    {
    public:
    ...
      Standard_EXPORT static Standard_Real Confusion();
    ...
    }
    
    // Precision.cxx
    Standard_Real Precision::Confusion() { return 1.e-7; }
    
    // FILES
    Precision.hxx
    Precision.cxx
    

    In that case, you will need to re-build TKMath.dll dynamic library after modification of constant.

    Moving such constant into exported function may affect negativelly performance of OCCT algorithms, as extra function call will be required and no compiler optimization will be possible.

    Another issue is that some OCCT algorithm might actually become broken / unstable / slower after changing Precision::Confusion() value due to combination with other numerical constants in them.

    If you found Precision::Confusion() too rough for your calculations - consider working with your model in another length units rather than changing global constants (e.g. switch from meters to millimeters or from millimeters to micrometers). Data Exchange components in OCCT support length unit conversion on export/import steps.

    Beware also that Precision::Confusion() defines only a lower/default precision value in 3D space. When working with topology, tolerance values on shape level will be used to enlarge algorithm tolerance, so that changing Precision::Confusion() will not affect such algorithms at all, in case if your model is somehow broken (encodes too large tolerance values to cover geometrical error definition).