Archive for 2008
C, class, design, global, instance, object, pattern, singleton, SystemVerilog
In Cpp, SystemVerilog on October 3, 2008 at 5:43 am
Purpose of a singleton:
To have a class which has only one instance(object)
All the objects of this class refer to same global object
that is created only once
This design pattern provides a mechanism for providing
namespaces to global variables
Download here. singleton-design-pattern
C++ example for singleton design pattern: click here
System Verilog example for singleton design pattern
// Filename : singleton.sv
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com
module tb;
class Singleton;
// object that is created only once
extern static Singleton single;
// constructor that is called only once
extern function new;
// method to get object
extern function Singleton get_instance;
// data to check the functionality
int data;
endclass
initial Singleton::single = null;
function Singleton::new;
data = 14;
endfunction
function Singleton Singleton::get_instance;
// call the constructor for the first time
// if the object has been created already
// return reference to the object already created
if(single==null) single = new;
// return the reference to the object
return single;
endfunction
Singleton s, t;
initial begin
// don’t use s= new;
// since it will create new instances
// instead use the get_instance method
s = s.get_instance();
t = t.get_instance();
$display(“initial value of s.data = “,s.data);
s.data = 25;
$display(“modified value of s.data = “,s.data);
$display(“value of t.data = “,t.data);
end
endmodule
Result:
initial value of s->data = 14
modified value of s->data = 25
value of t->data = 25
Download here. singleton-design-pattern
C, class, design, global, instance, object, pattern, singleton
In Cpp on October 3, 2008 at 5:40 am
Download here. singleton-design-pattern
Purpose of a singleton:
To have a class which has only one instance(object)
All the objects of this class refer to same global object
that is created only once
This design pattern provides a mechanism for providing
namespaces to global variables
C++ example for singleton design pattern
// Filename : singleton.cpp
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com
#include <iostream>
using namespace std;
class Singleton {
// constructor that is called only once
Singleton();
// object that is created only once
static Singleton *single;
public:
// method to get object
Singleton* get_instance();
// data to check the functionality
int data;
};
Singleton* Singleton::single = NULL;
Singleton* Singleton::get_instance() {
// call the constructor for the first time
// if the object has been created already
// return reference to the object already created
if(single==NULL) single = new Singleton();
return single;
}
Singleton::Singleton() {
data = 14;
}
int main() {
Singleton *s, *t ;
s = s->get_instance();
cout<<”initial value of s->data = “<<s->data<<endl;
s->data = 25;
cout<<”modified value of s->data = “<<s->data<<endl;
t = t->get_instance();
cout<<”value of t->data = “<<t->data<<endl;
}
// end of file singleton.cpp
Result:
initial value of s->data = 14
modified value of s->data = 25
value of t->data = 25
Download here. singleton-design-pattern
class, interface, Modelsim, ncverilog, questasim, SystemVerilog, virtual
In SystemVerilog on September 24, 2008 at 6:53 am
Download here. system_verilog_virtual_interface
// Filename : virtual_interface.sv
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com
interface bus(input wire clk);
int address;
int data;
modport virtual_interface(input clk);
endinterface
module virtual_interface;
bit clk;
bus BUS(clk);
class monitor;
virtual bus VBUS;
task disp;
$display(VBUS.address);
$display(VBUS.data);
endtask
endclass
monitor m;
initial begin
m = new;
m.VBUS = BUS;
BUS.address = 100;
BUS.data = 1234;
m.disp;
end
endmodule
// Running simulation in ncverilog
// ncverilog +sv virtual_interface.sv
// Running simulation in modelsim/questasim
// vlib work
// vlog -sv virtual_interface.sv
// vsim -c virtual_interface
// run
Download here. system_verilog_virtual_interface
class, consumer, inheritance, method, producer, SystemVerilog, tlm, transaction, virutal
In SystemVerilog on September 24, 2008 at 6:17 am
Download here. transactionlevelmodeling_systemverilog
// Filename : tlm.sv
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com
module producer_consumer;
virtual class put_if;
// Abstract Class whose methods are not yet implemented
virtual task put(int val);
endtask
endclass
class producer;
put_if put_port;
task run;
int i;
for(i=0;i<10;i++) put_port.put(i);
endtask
endclass
class consumer extends put_if;
// methods of put_if class are over-ridden
// and defined here
task put(int val);
$display(“Consumer receiving “,val);
endtask
endclass
producer p;
consumer c;
initial begin
p = new;
c = new;
p.put_port = c;
p.run;
end
endmodule
// Running simulation in ncverilog
ncverilog +sv tlm.sv
// Running simulation in modelsim/questasim
vlib work
vlog -sv tlm.sv
vsim -c producer_consumer
run
Download here. transactionlevelmodeling_systemverilog
hello, irun, ius, ncverilog, ovm, SystemVerilog, Verilog
In SystemVerilog, Verilog on September 19, 2008 at 10:00 am
Here is hello world program in
System Verilog Open Verification Methodology
Download here. hello_ovm
// Filename : hello_ovm.sv
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com
module hello_ovm;
`include “ovm.svh”
class Random extends ovm_transaction;
rand int num;
constraint c { num >= 0 && num < 50; }
function new(string name);
super.new(name);
endfunction
endclass
Random r;
initial begin
r = new(“Hello OVM”);
r.print();
ovm_report_message(“APPLIED ELECTRONICS JOURNAL”,
$psprintf(“Hello World”));
end
endmodule
// End of file hello_ovm.sv
One liner to run this in IUS
When OVM library is not installed by default:
1) Set OVMHOME to the root directory where OVM library is installed
setenv OVMHOME /netstar/ag.raja/sv/OVM/ovm-1.1
2.a) IUS 6.2-s003 and IUS 6.2-s004
irun -sv -nowarn PMBDVX -ovmhome $OVMHOME $OVMHOME/src/ovm_pkg.sv hello_ovm.sv
2.b) IUS 6.2-s005
irun -sv -ovmhome $OVMHOME $OVMHOME/src/ovm_pkg.sv hello_ovm.sv
When OVM is already installed to $CDS_INST_DIR/tools/ovm
a) IUS 6.2-s003 and IUS 6.2-s004
irun -sv -ovm -nowarn PMBDVX hello_ovm.sv
b) IUS 6.2-s005
irun -sv -ovm hello_ovm.sv
Using Options File
irun –f options_file
// options_file begins here
-sv
-ovm
hello_ovm.sv
// options_file ends here
Download here. hello_ovm
highlight, Linux, startup, sv, svh, svhpp, svpp, syntax, SystemVerilog, Verilog, vim, vimrc, vpp
In Shell, SystemVerilog, Verilog on September 19, 2008 at 5:02 am
Enable syntax highlight for sytemm verilog, verilog preprocessor files with extensions v, sv, vpp, svh, svhpp
Create a file named “.vimrc” in your home directory [*nix]
Put the following lines in that file
“File Begins here
“Note: Comments in vim script begin with double quote
“Filename : .vimrc
“Author : A.G.Raja
“Website : http://agraja.wordpress.com
“Show line numbers
set nu
“Source the syntax file
so $VIMRUNTIME/syntax/verilog.vim
“Add file extensions to be highlighted
au Syntax sv runtime! syntax/verilog.vim
au Syntax svh runtime! syntax/verilog.vim
au Syntax vpp runtime! syntax/verilog.vim
au Syntax svpp runtime! syntax/verilog.vim
au Syntax svhpp runtime! syntax/verilog.vim
“End of file
C, char, conversion, string, wide, wstring
In Cpp on September 8, 2008 at 6:15 am
Download here. string-wstring-conversion-functions
// Filename : string_wstring.cpp
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com
#include <iostream>
using namespace std;
string wstring2string(wstring wstr) {
string str(wstr.length(),’ ‘);
copy(wstr.begin(),wstr.end(),str.begin());
return str;
}
wstring string2wstring(string str) {
wstring wstr(str.length(),L’ ‘);
copy(str.begin(),str.end(),wstr.begin());
return wstr;
}
int main() {
wstring wstr = string2wstring(“raja”);
string str = wstring2string(wstr);
cout<<str<<endl;
}
Download here. string-wstring-conversion-functions
code, format, indent, Perl, program, script, source, text, Verilog
In SystemVerilog, Verilog on August 29, 2008 at 7:04 am
Here’s a perl script to indent verilog files.
Download here. vindent.pdf
Add your own list of keywords to indent any source code
For example, this script could be used to indent C/C++/Java source codes.
This script uses two spaces for each indent. This could be changed as required.
#!/usr/bin/perl
# Filename : vindent.pl
# Author : A.G.Raja
# Website : http://agraja.wordpress.com
#
# Usage : ./vindent.pl verilogfile.v
# : ./vindent.pl *.*v*
# Help : ./vindent.pl
# Verilog File indenter
# Space for each indent
my $Space = “ “;
# Block begin. For indenting C/C++/Java program use “{“
my $Open = “begin”;
# Block end. For indenting C/C++/Java program use “}”
my $Close = “end”;
# Block statements.
# Note: Each Open keyword must have corresponding Close keyword
my @Openkeywords = qw{ module program package interface class task function };
my @Closekeywords = qw{ endmodule endprogram endpackage endinterface endclass endtask endfunction };
sub indent {
my $indent = 0;
my($infile) = @_;
open(FILE, “$infile”) or die “Couldn’t open file \”$infile\”\n”;
open(TFILE, “>temp”) or die “Couldn’t create temp file\n”;
while($line = <FILE>) {
chomp $line;
$line =~ s/^\s*//;
print TFILE “$line \n”;
}
close TFILE;
close FILE;
open(TFILE, “<temp”);
open(FILE, “>$infile”);
while($line = <TFILE>) {
foreach $Closekey (@Closekeywords) {
if($line =~ /^$Closekey\s/) { $indent–; }
}
if (($line =~ /.*\s+$Close\s/ ) || ($line =~ /^$Close\s/))
{ $indent–; }
for($i=0;$i<$indent;$i++) { print FILE $Space; }
print FILE $line;
foreach $Openkey (@Openkeywords) {
if($line =~ /^$Openkey\s/) { $indent++; }
}
if (($line =~ /.*\s+$Open\s/ )|| ($line =~ /^$Open\s/))
{ $indent++; }
}
close FILE; close TFILE;
print “Indented File \”$infile\”\n”;
}
my $argnum;
if($ARGV[0] eq “”) {
print “Usage : vindent.pl verilogfile.v\n”;
print “ vindent.pl *.v\n”;
print “ vindent.pl *.*v*\n”;
print “Help :\n”;
print “ vindent.pl\n”;
}
foreach $argnum (0 .. $#ARGV) {
my $ifile = $ARGV[$argnum];
&indent($ifile);
}
unlink “temp”;
Download here. vindent.pdf
C, class, getline, parse, string
In C on August 18, 2008 at 11:14 am
Download here. getline
Features of the below string getline class
1) Can be used like getline function for streams
2) Can have multiple delimiters as opposed to the getline function for streams
3) Delimiter need not be single char. It can be a string
4) Pointer to current position in the string is automatically incremented
similar to that in stringstream
5) It is possible to rewind the pointer position to zero using the rewind() method.
6) It is also possible to get single char at the current position of pointer from the string
7) It is possible to get single char at current pointer position if it is one of the
characters of the list. This is an optional argument to the get method
stream getline feature can be realized by calling the getline method of this
class without passing any arguments. No arguments to getline method defaults to
newline char as delimiter
// File : Getline.hh
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com
#include <iostream>
using namespace std;
class Getline {
string text, buffer;
int pos,p;
public:
int str(string txt) {
pos = 0;
this->text = txt;
}
string getline(string delim = “\n”, int delim_type = 1);
char get(string delim = “”);
int unget(int decr = 1) {
pos -= decr;
}
int end() {
if(pos>=text.size()) return 1;
else return 0;
}
int rewind() {
pos = 0;
}
};
string Getline::getline(string delim, int delim_type) {
p = delim_type ? text.find(delim,pos)
: text.find_first_of(delim,pos);
if(p!=-1) {
buffer = text.substr(pos,p-pos);
pos = delim_type ? p+delim.length() : p +1;
} else {
buffer = text.substr(pos);
pos += buffer.length();
} return buffer;
}
char Getline::get(string delim) {
if(delim.empty() and pos<text.size()) return text[pos++];
if(delim.find(text[pos])!=-1) {
pos++;
return text[pos-1];
}
return 0; // must
}
// End of File Getline.hh
// File : test_Getline.cpp
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com
#include <iostream>
#include “Getline.hh”
using namespace std;
int main() {
Getline g;
g.str(“Hi, my name is Raja\nI’m an Engineer”);
// Get the substring terminated by “y na”
cout<<g.getline(“y na”)<<endl;
// Result: “Hi, m”
// Get substring terminated by first of “sji”
cout<<g.getline(“sji”,0)<<endl;
// Get line terminated by ‘\n’
cout<<g.getline()<<endl;
// Result: “s Raja”
// Get single char at current position of pointer
cout<<g.get()<<endl;
// Result: “I”
// Get a char at current position of pointer
// if it is in the list “_$%’#”
cout<<g.get(“_$%’#”)<<endl;
// Result: “‘”
// Unget single char, unget 4 chars
g.unget(); g.unget(4);
}
Download here. getline
C, char, find, function, program, replace, spaces, string, trim
In Bookmarks on March 19, 2008 at 1:35 pm
Download here. string_replace.pdf
// Filename : string_replace.c
// Author : A.G.Raja
// Website : agraja.wordpress.com
// License : GPL
#include <stdio.h>
char* string_replace(unsigned char *from, char *find, char *replace)
{
const char *p;
char *q, *to;
int i,d, match;
to=malloc(sizeof(char)*strlen(from)*strlen(replace)/strlen(find));
for(p = from, q = to; *p != ”; p++)
{
// find logic
for(d=0;d<strlen(find);d++)
{
if (*(p+d) == *(find+d)) match=1;
else match =0;
}
// replace logic
if (match)
{
for(i=0;i<strlen(replace);i++)
{
*(q+i)=*(replace+i);
}
q=q+i; p=p+d-1;
}
else // copy unchanged chars
{ *q=*p; q++; }
} *q = ”;
return to;
}
// Test code
int main()
{
unsigned char *str = “this is original text” ;
char f[]=”original”;
char r[]=”new”;
unsigned char *str2;
printf(“before:%s\n”,str);
str2=string_replace(str,f,r);
printf(“after:%s\n”,str2);
return 0;
}
Download here. string_replace.pdf
Tips:
See the following pages for char replace, trim spaces
char replace
trim spaces
C, char, find, function, program, replace, trim
In Bookmarks on March 12, 2008 at 5:42 am
Download here. find_replace.pdf
// Filename : find_replace.c
// Author : A.G.Raja
// Website : agraja.wordpress.com
// License : GPL
#include <stdio.h>
void find_replace(char *to, unsigned char *from, char find, char replace)
{
const char *p; char *q;
for(p = from, q = to; *p != ”; p++)
{
if ( *p != find)
{ *q=*p; q++; }
else
{ *q=replace; q++; }
} *q = ”;
}
int main()
{
unsigned char *str = “this is original text” ;
unsigned char str2[strlen(str)];
printf(“before:%s\n”,str);
find_replace(str2,str,’s’,'x’);
printf(“after:%s\n”,str2);
return 0;
}
// This program can be used for single char only.
// string with more than one char is not supported
Download here. find_replace.pdf
Tips:
This function can be used to trim white spaces in file.
See this page for an example: Trim
See this page for string replace: string replace
build, clean, gcc, make, Makefile, Perl, script
In Bookmarks on February 28, 2008 at 6:51 am
Download here. createmakefile.pdf
#!/usr/bin/perl
# File name: writemake.pl
# Author: A.G.Raja
# Website: agraja.wordpress.com
# License: GPL
use strict;
use warnings;
open(FH,">Makefile") or die "Cannot create Makefile";
print FH ("all: buildnn");
print FH ("build: " . $ARGV[0] .".onn");
print FH ("shared: " . $ARGV[0] . ".sonn");
print FH ("clean: n");
print FH ("trm ".$ARGV[0].".*o nn");
print FH ($ARGV[0].".o: ".$ARGV[0].".cn");
print FH ("tgcc -o ".$ARGV[0].".o ".$ARGV[0].".cnn");
print FH ($ARGV[0].".so: ".$ARGV[0].".cn");
print FH ("tgcc -fPIC -shared -o ".$ARGV[0].".so ".$ARGV[0].".cn");
close FH;
# Usage:
# chmod +x writemake.pl
# writenake.pl hello
Below is the Makefile generated:
all: build
build: hello.o
shared: hello.so
clean:
rm hello.*o
hello.o: hello.c
gcc -o hello.o hello.c
hello.so: hello.c
gcc -fPIC -shared -o hello.so hello.c
Download here. createmakefile.pdf
C, Cpp, download, dpi, Modelsim, system, TCL, Verilog
In Bookmarks on February 20, 2008 at 4:47 am
Refer to the previous post for introduction.
The above example gives a demo with NCVerilog.
Here is the run script for running the same example with Modelsim under windows.
Download here. system-verilog-dpi-modelsim.pdf
#File name run.tcl
# Author: A.G.Raja
# Website: agraja.wordpress.com
# License: GPL
#Type at Transcript terminal: source run.tcl
vlib work
vlog -sv -dpiheader dpiheader.h dpi_top.v
exec gcc -c -g -IE:/modelsim/include dpi_main.c -o dpi_main.obj
exec gcc -shared -o dpi_main.dll dpi_main.obj -LE:/modelsim/win32
vsim -novopt top -sv_lib dpi_main
run
# EOF run.tcl
Replace “E:/modelsim” with “modelsim installation path”
1) Don’t create a new project while starting Modelsim
2) Open and proceed directly to Modelsim.
3) At the transcript terminal change to the working directory
4) No need to create a folder named work.
5) The run script given above does it.
Download here. system-verilog-dpi-modelsim.pdf
Download NCVerilog demo here.
systemverilogdpi.pdf
assert, C, macro
In Bookmarks on February 4, 2008 at 10:29 am
// assert.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
// Licence: GPL
#include <iostream>
using namespace std;
#define my_assert(x) \
if(!x) cout<<__FILE__<<”:assertion on line “; \
cout<<__LINE__<<” failed”<<endl;
int main()
{
int a,b;
a=0;
my_assert(a) // User defined assertion
assert(a); // Predefined assertion
}
// g++ assert.cpp
Download here.
assert.doc
C, close, eof, file, fstream, ifstream, ofstream, open, operations, read, write
In Bookmarks on February 4, 2008 at 9:50 am
// file_write.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile (“example.txt”);
if (myfile.is_open())
{
myfile << “This is a line.\n”;
myfile << “This is another line.\n”;
myfile.close();
}
else cout << “Unable to open file”;
return 0;
}
// g++ file_write.cpp
// file_read.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile (“example.txt”);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << “Unable to open file”<<endl;
return 0;
}
//g++ file_read.cpp
Download here.
cpp_file_operations.doc
C, class, constructor, destructor
In Bookmarks on February 4, 2008 at 6:14 am
// constructor_destructor.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
// Licence: GPL
#include <iostream>
using namespace std;
class Employee{
char *name;
int age;
double salary;
public: Employee(); //Constructor
void print();
void setval(char *name, int age, double salary);
char* getname() { return name; }
int getage() { return age; }
double getsalary() { return salary; }
~Employee(); //Destructor
};
Employee::Employee()
{
cout<<”Object Created”<<endl;
name=”fresher”;
age=23;
salary=17500;
}
void Employee::print()
{
cout<< name<<”\t”<<age<<”\t”<<salary <<endl;
}
void Employee::setval(char *n, int a, double s)
{
name=n;
age=a;
salary=s;
}
Employee::~Employee()
{
cout<<”Object Destroyed”<<endl;
}
int main()
{
char *NAME;
int AGE;
double SALARY;
//Employee E257 = {“raja”,25,23519.78};
Employee E257;
cout<<”Print Default Values”<<endl;
E257.print(); // Default Values
E257.setval(“raja”,25,23768);
cout<<”Print New Values”<<endl;
E257.print(); // New values
NAME=E257.getname();
AGE=E257.getage();
SALARY=E257.getsalary();
cout<<NAME<<”\t”<<AGE<<”\t”<<SALARY<<endl;
}
// g++ constructor_destructor.cpp
Download here.
constructor.doc
C, class, download, member, object, private, public, struct
In Bookmarks on February 2, 2008 at 6:26 am
This is an example to show the similarity between a struct and a class
#include <iostream>using namespace std;
int main()
{
struct employee
{char *name;
int age;
double salary;
};
employee e257 = {”raja“,25,23519.78};
cout<< e257.name<<”\t”<<e257.age
<<”\t”<<e257.salary <<endl;
class Employee { public: char *name;
int age;double salary; };
Employee E257 = {”raja”,25,23519.78};
cout<< E257.name<<”\t”<<E257.age
<<”\t”<<E257.salary <<endl;
}
Note:
1) All members of a struct are public by default
2) All members of a class are private by default
3) For a class member to be public, it has be
declared public with the keyword "public".
Advantage of using classes
1) Member variables are private and protected.
2) Constructors functions(declared public) can be
used to initialize and modify values of that private variables.
See this page for Constructors: Constructors & Destructors </pre
Download here.struct.doc
In Bookmarks on January 5, 2008 at 12:34 am
In Bookmarks on January 4, 2008 at 12:41 am
C, comments, documentation, help, Perl, program, script
Perl script to display comments
In Bookmarks on March 19, 2008 at 1:57 pmDownload here. c_help.pdf
#!/usr/bin/perl
# Filename: chelp.pl
# Author : A. G. Raja
# Website : agraja.wordpress.com
# License : GPL
# pass c file as argument to this script
# this script displays all the comments
use strict;
use warnings;
open(FILE,$ARGV[0]) or die “File not Found”;
my $line;
my $start=0;
while ( $line = <FILE> ) {
if($line =~ /\/\//)
{
$line=~ s/(.*)\/\/(.*)/$2/;
print $line;
}
if($line =~ /\/\*/)
{
$start=1;
$line=~ s/(.*)\/\*(.*)/$2/;
}
if($line =~ /\*\//)
{
$line=~ s/(.*)\*\//$1/;
print $line;
$start=0;
}
if($start) { print $line; }
}
close FILE;
Tips:
Use a shell script to redirect the output
of the above script to another program.
Example
#!/bin/bash
# Filename: help.sh
# Author : A.G.Raja
# Website : agraja.wordpress.com
# License : GPL
# rename chelp.pl to chelp
# Install chelp and add to path
chelp $1 | less
Demo:
Below is a C file
// Filename : demo.c
// Author : cfile.pl
// License : GPL
#include <stdio.h>
#define print(x) printf(“str=%s\n”,x);
int main(int argc, char **argv)
{
/* this is a multi-
line comment */
char *str=”File name:”;// this will print file name
print(argv[0])
return 0;
}
Type at the terminal:
[raja@agraja ]$ chelp demo.c
The following will be printed to stdout
Filename : demo.c
Author : cfile.pl
License : GPL
this is a multi-
line comment
this will print file name
Download here. c_help.pdf