Thought Leadership

SystemVerilog Static Methods

By Chris Spear

Introduction

In my last post, you learned how to create a class with a static property. This variable acts like a global variable in that only one copy exists, no matter how many objects you create. This post shows how you can create methods that access those static properties.

Methods

Any class method can read and write these static properties, just like dynamic properties. However, if you declare the method as static, you can call the method without needing to construct an object. Here is the Thing class with a static method to print the count of Thing objects. You can call Thing::print_count(), even if no Thing objects were constructed.

class Thing;
  int id;           // Dynamic, unique to each object
  static int count; // Static, associated with the class      

  static function void print_count();
    $display(“Thing::count = %0d.”, count);
  endfunction
  // The rest of the class
endclass

Static methods can only access static properties. Remember, a static property acts like a global variable in that it is always around. Dynamic properties are stored in objects. The id property only exists in individual objects, so print_count() could not see it.

Here is a simple error handler class that keeps track of how many error messages have printed and exits when you reach the maximum. Notice that there are no ErrorH handles or objects created. Copy this code and try on your simulator.

class ErrorH;
  static int count=0, max_count=10;

  static function void print(input string s);
    $error(s);
    if (++count >= max_count) begin
      $display("*** Error max %0d exceeded", max_count);
      $finish(0);
    end
  endfunction

  static function void set_max_count(input int m);
    max_count = m;
  endfunction
endclass

initial begin
  ErrorH::set_max_count(2); // Limit the number of errors
  ErrorH::print("one");
  ErrorH::print("two - should end sim");
  ErrorH::print("three - should not print");
end

More tips

The uvm_config_db class is built on static methods, which is why you need to call with the following syntax.

uvm_config_db::set(...)
uvm_config_db::get(...)

Without static methods, you would have to construct a DB object, and pass its handle around to every corner of the testbench. That defeats the whole goal of simplifying sharing of configuration information.

The specialization is not shown. Look for more details in an upcoming blog post.

Enjoy your verification journey!
Chris Spear

Keep learning at mentor.com/training
Questions or ideas? verificationacademy.com/ask-chris-spear
View my recent webinar on UVM Coding Guidelines and the Questions and Answers

Leave a Reply

This article first appeared on the Siemens Digital Industries Software blog at https://blogs.sw.siemens.com/verificationhorizons/2020/04/29/systemverilog-static-methods/