Extern method in classes

One powerful feature of System Verilog OOP approach is the use of extern methods in classes. The extern keyword allows you to define class methods outside the class body, improving code modularity and readability.

In System Verilog, extern methods are function or task declarations in a class whose definitions are provided outside the class body. This separation of declaration and definition enhances the organization of code, especially in large projects.

Syntax of extern Methods

  1. Declaration within the class:
    The method is declared inside the class using the extern keyword.
  2. Definition outside the class:
    The method’s definition is written outside the class, prefixed with the class name.

General Syntax:

class ClassName;
    extern MethodName(arguments);
endclass

// Method definition
ReturnType ClassName::MethodName(arguments) {
    // Method body
}

Key Points to Remember

  1. Access Scope:
    Extern methods have access to class members (variables and other methods) as if they were defined inside the class.
  2. Definition Order:
    The extern method definitions must appear after the class declaration to ensure they are properly associated.
  3. Extern methods should have same number of argument lists, data types and argument name.
  4. If any return type is used in extern method, it should be same as in class declaration.

Example 1: A Simple Counter Class

// Class declaration with extern methods
class Counter;
    int count;

    // Extern method declarations
    extern function void reset();
    extern function void increment();
    extern function int get_value();
endclass

// Definitions of the extern methods
function void Counter::reset();
    count = 0;
endfunction

function void Counter::increment();
    count++;
endfunction

function int Counter::get_value();
    return count;
endfunction

// Testbench to use the Counter class
module tb;
    Counter c;

    initial begin
        c = new();
        c.reset();
        $display("Initial value: %0d", c.get_value());
        
        c.increment();
        c.increment();
        $display("Value after incrementing twice: %0d", c.get_value());
    end
endmodule

Output:

Initial value: 0
Value after incrementing twice: 2

Explanation of the Example

  1. Class Declaration:
    • The Counter class declares the reset, increment, and get_value methods as extern.
    • The count variable is a class member.
  2. Method Definitions:
    • The methods are defined outside the class using the syntax ClassName::MethodName.
    • Each method operates on the count variable.
  3. Testbench:
    • A testbench creates an instance of the Counter class, calls its methods, and prints the results.