SystemVerilog static variables 与 static functions

static 成员属于类本身,所有对象共享一份。它适合计数器、配置表、全局注册表等需要跨对象共享的数据。

1. 静态变量

1
2
3
4
5
6
7
8
9
class packet;
static int count = 0;
int id;

function new();
count++;
id = count;
endfunction
endclass

每创建一个对象,count 加一;所有对象共享同一个 count。

2. 静态方法

1
2
3
4
5
function static int get_count();
return count;
endfunction

$display("%0d", packet::get_count());

静态方法通过 class::method() 调用,不能访问非静态成员,也没有 this。

3. 初始化时机

静态变量在仿真开始时初始化一次,早于任何对象创建。依赖其他静态变量的初始化顺序不应假设。

4. 常见误区

  1. 在静态方法中访问 this:非法。
  2. 期望静态变量每个对象一份:它是共享的。
  3. 静态变量未初始化:默认值依类型而定,应显式赋值。

小结

static 表达“属于类而非对象”。需要跨对象共享计数、缓存或配置时使用,但要注意初始化与线程安全。

参考文献:ChipVerify SystemVerilog Tutorial — SystemVerilog Static Variables & Functions 章节(https://chipverify.com/systemverilog/systemverilog-static-variables-functions)。本文为原创中文讲解。