File operations

I have many variables with the following naming conventions.

int mem_0_0 = 5;
int mem_0_1 = 10;

and so on…

this is just an example, you might suggest me to use arrays instead of declaring these variables. but my problem is something else…

I want to write the values of mem_0_0 and mem_0_1 variables inside a file. I have written a sample code below. but I am not getting the values 5 and 10, instead decimal value of strings mem_0_0 and mem_0_1 is getting written inside file.

module test;
int mem_0_0 = 5;
int mem_0_1 = 10;
int fd;
initial begin
fd = $fopen("file.txt", "w");

for(int i=0; i<2; i++)begin
$fwrite(in, "%0d\n", $sformatf("mem_0_%0d", i));

How can I write the values of variables inside file?

In reply to Abuzar Gaffari:

You can’t reference variables by creating strings with the variable name. You can only reference variables by their actual instance.

You can use an array, or write code with each instance name.

In reply to Abuzar Gaffari:

It would help to have more details about your problem. As previously mentioned, SystemVerilog provides no way to reference identifiers via strings. Compiled languages like C/C++/Java cannot interpret strings as code at run-time.

That said, SystemVerilog does provide a C to simulator interface (VPI) that can provide access to identifiers via a string lookup if the tool knows at compilation time that you plan to use that. It has to create a database of identifier strings and preserve signal values that you plan to access so they are not optimized away.

But depending on what you need to do, you might be able to take advantage of tool specific debug and waveform dumping features to access signal names without having to write any C code.

In reply to cgales:

It would help to explain in more detail what you need to achieve.

As mentioned, you cannot reference identifier names via strings. SystemVerilog is a compiled language like C/C++/Java and will not interpret strings as code once run-time execution begins.

That said, SystemVerilog does provide a C programming interface to the simulator tool (VPI) that enables access to identifiers via strings. The compiler needs to know this as compilation time so it can build a database of identifier names and preserve signal values so they are not optimized away.

Depending on what want to accomplish, you might not have to write any C code. Most tools already provide debug and waveform capture features that allow access “constructed” names.