How do I read an environment variable in Verilog/System Verilog?

Jean picture Jean · Feb 22, 2013 · Viewed 18.4k times · Source

How do I read an environment variable in Verilog ? (Running on a VCS simulator)

I am trying to accomplish

File=$fopen("$PATH/FileName","r");

$PATH is an environment variable.

Answer

jclin picture jclin · Feb 27, 2013

You can simply use SystemVerilog DPI for getting environment. And because getenv is a standard C library for every POSIX platform, so you do not need to implement your own getenv() equivalent function for the function definition again.

Example code in SV.

import "DPI-C" function string getenv(input string env_name);

module top;

  initial begin
    $write("env = %s\n", {getenv("HOME"), "/FileName"});
  end
endmodule

Running

ncverilog -sv dpi.v

or

vcs -sverilog dpi.v

It will show

env = /home/user/FileName

And one more issue in your original question, PATH is a environment for executable search path and concatenate with ":" character. I think it should be an example here, not really "PATH" environment. Otherwise, your fopen file name could be "/bin:/usr/bin:/usr/local/bin/FileName", which is wrong.