Hidden Gems of SystemVerilog – 1. Compilation unit scope

This is a new series of technical blogs that focus on SystemVerilog itself. This is not a SystemVerilog tutorial, but rather I would like to dig into the SystemVerilog language and show you the features that not many people may know about. The first article is about compilation unit. Since Halloween is just around the corner, let’s start with getting some candies.

1
2
3
4
5
6
7
8
9
10
11
string candy = "Snickers";
 
module trick_or_treat;
  string candy = "Skittles"; 
  task treat;
    $display( { "I've got ", candy, "!" } ); // Skittles  endtask
 
  initial treat;
endmodule

When this module is executed, you get Skittles1 because the candy (line 4) is declared within the name space of the trick_or_treat module and the candy (line 1), which has the same variable name declared outside of the module, is hidden. But how to get the Snickers2 then? You need to disambiguate the candy by specifying the compilation-unit scope. The compilation unit is each file, or all files on a given compilation command line. $unit is the name used to access the identifiers in the compilation-unit scope (line 7).

1
2
3
4
5
6
7
8
9
10
11
string candy = "Snickers"; 
module trick_or_treat;
  string candy = "Skittles";
 
  task treat;
    $display( { "I've got ", $unit::candy, "!" } ); // Snickers  endtask
 
  initial treat;
endmodule

Now you can get Snickers. Happy Halloween!

EDA Playground

You can view and run the code on EDA Playground.

1) Skittles is a registered trademark of Wm. Wrigley Jr. Company.
2) Snickers is a registered trademark of Mars, Incorporated.

2 thoughts on “Hidden Gems of SystemVerilog – 1. Compilation unit scope”

  1. Hi Kisuke,
    I have a file defines.svh where i declare a enum type (typedef enum ……. ) . I need to use this enum in the my design as well as test bench. I put the test bench files all in a package and many of the test bench file refer to the enum declared in defines.svh. I do `include defines.svh in the design.v file as well as any test bench file that uses the enum. I have guard defines in the defines.svh so it won’t complain about multiple declaration. The issue I face is when it try to compile the package (with test bench files) it says “SV package not allowed to access items declared in Compilation unit scope” when it hits the line which declares a variable of the type defined in defines.svh. My question is do I need to create a separate file exclusively for test bench file to use? This has to be copy of the defines.svh.
    Regards,
    Gautam

    1. Make sure you include the defines.svh in the package:

      package p;
        `include "defines.svh"
        // include other test-bench files
      endpackage: p

Leave a Reply to Gautam Cancel reply

Your email address will not be published. Required fields are marked *