SystemVerilog中的package提供了保存和共享数据、参数和方法的机制,可以在多个module、class、program和interface中重用。
package中声明的内容都属于这个package作用域(scope)。在使用这些内容时,需要先import这个package,然后通过package引用。
SystemVerilog中的package通过package和endpackage声明
package my_pkg; typedefenumbit [1:0] { RED,YELLOW, GREEN, RSVD } e_signal; typedefstruct { bit [3:0]signal_id; bit active; bit [1:0] timeout; } e_sig_param; function common (); $display ("Calledfrom somewhere"); endfunctionendpackage
然后通过import :: 指定需要导入的内容。如果需要导入所有内容,就需要输入
import my_pkg::* ;
// Import the package defined above to use e_signal package my_pkg; typedef enum bit [1:0] { RED,YELLOW, GREEN, RSVD } e_signal; typedef struct { bit [3:0]signal_id; bit active; bit [1:0]timeout; } e_sig_param; function common (); $display ("Called fromsomewhere"); endfunctionendpackage program test_case; import my_pkg::* ; class myClass; e_signal my_sig; endclass myClass cls; initial begin cls = new (); cls.my_sig = GREEN; $display ("my_sig =%s", cls.my_sig.name()); common (); end endprogram
使用Questasim仿真
run# my_sig = GREEN# Called from somewhere# 1# Simulation stop requested.
因为我们输入了import my_pkg::* ;所以仿真器才认识e_signal
我们将import my_pkg::*删掉再仿真,仿真器会报出编译错误
** Error: **.sv(23): Invalid type'e_signal'. Please check the type of the variable 'my_sig'.** Error: **.sv(30): (vlog-2730) Undefinedvariable: 'GREEN'.
package变量作用域
假设在顶层和package中具有同名的变量READ
package my_pkg; typedef enum bit { READ, WRITE }e_rd_wr;endpackage program test_case; import my_pkg::* ; typedef enum bit { WRITE, READ } e_wr_rd; initial begin automatic e_wr_rd opc1 = READ; automatic e_rd_wr opc2 = READ; $display ("READ1 = %0dREAD2 = %0d ", opc1, opc2); end endprogram
此时会发生编译错误:
** Error: (vlog-8386) **.sv(13): An enumvariable 'opc2' of type 'e_rd_wr' may only be assigned the same enum typedvariable or one of its values. Variable 'READ' of type 'e_wr_rd' is not valid.
这时候需要使用赋值方式
opc2 = my_pkg::READ;
仿真器输出log:
run# READ1 = 1 READ2 = 0# 1# Simulation stop requested.
那么import和include有什么区别呢?
`include将文件中所有文本原样插入包含的文件中。这是一个预处理语句,`include在import之前执行。
import不会复制文本内容。但是import可package中内容引入import语句所在的作用域。
总结下就是
include is equivalent to copy/paste or insertion of whatever is present in that file to wherever you include.
import is used to make all/select variables from a package visible.
往期精彩