SystemVerilog Classes with Static Properties
One of the advantages of creating your testbenches with Object Oriented Programming, as opposed to traditional procedural programming, is that your data and code are contained in a class, reducing the need for global variables. Those are useful, but you need to use them carefully to restrict how they are accessed, to avoid data corruption. Also, you need to create unique names for global variables to avoid conflicts. Is there an OOP way to make a variable that can be accessed across multiple classes, and solves the naming problem?
When you debug code with multiple objects, it is handy to have a unique name or ID for each one, so you can easily follow them through system. How can you set the ID automatically? You could have a global variable that counts the number of objects of this type, but you are trying to avoid globals. The OOP solution is a static variable, where the storage is associated with the class declaration, not the multiple objects that are constructed dynamically.
class Thing; int id; // Dynamic, unique to each object static int count; // Static, associated with the class function new(); id = count++; // Initialize ID, update count endfunction // The rest of the class endclass
Every time you construct a new object, its id gets the current count, and then count is incremented. The count property holds the number of objects created. Since this property is static, it exists even when no objects have been created. The colon-colon syntax shown below is known as the scope resolution operator, and it says to look for the name count in the namespace Thing.
Thing t0, t1, t2; initial begin // Print the count, before any objects constructed $display("count=%0d. before", Thing::count); t0 = new(); // Print count after the first object constructed $display("count=%0d. after", Thing::count); t1 = new(); t2 = new(); end
Here is a picture of what was just created. The static count property is associated with the class, and only one copy exists. The handles t0, t1, and t2 point to separate objects, each with separate storage and their unique id value.
Aha – you have just created a “global” variable, count, that holds the number of Thing objects created so far, but it is “local” to the Thing class. In OOP terms, you would say that the property is in the Thing class name space.
Every class has its own name space, so a property called “count” in the Thing class does not conflict with one in another class. Every class could have its own count variable, without all the confusion if this was done with global variables.
Enjoy your verification journey!
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