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

回眸只為那壹抹淺笑 提交于 2019-12-04 06:32:34

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.

You can use a simple PLI application to read an environment variable. Here's a sample, without any error checks:

#include <stdlib.h>
#include <string.h>

#include "vpi_user.h"

PLI_INT32 pli_getenv (PLI_BYTE8 * arg) {

    vpiHandle tf_obj = vpi_handle (vpiSysTfCall, NULL);
    vpiHandle arg_iter = vpi_iterate (vpiArgument, tf_obj);

    vpiHandle arg1, arg2;
    arg1 = vpi_scan (arg_iter);
    arg2 = vpi_scan (arg_iter);

    s_vpi_value vi, vo;
    vi.format = vpiStringVal;
    vpi_get_value (arg2, &vi);

    vo.format = vpiStringVal;
    vo.value.str = strdup (getenv (vi.value.str));
    vpi_put_value (arg1, &vo, NULL, vpiNoDelay);

    return 0;
}

The VCS documentation should explain how to link this into the simulator.

It is often simpler to use the Verilog preprocessor

File = $fopen(`PATH_FILENAME, "r");

Then invoke the simulator from your Makefile/shell script the specifying value to be substituted

$(SIM) -DPATH_FILENAME=\"$PATH/FileName\" blah.v ...

I use this with Icarus' iverilog often, vsim and friends probably support similar.

Quotes are escaped so that they are included in the substituted value, since the preprocessor will not substitute inside a literal value. For instance this combination does not work:

File = $fopen("`PATH_FILENAME", "r");

...

`$(SIM) -DPATH_FILENAME=$PATH/FileName blah.v ...`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!