我是靠谱客的博主 负责盼望,这篇文章主要介绍Verilog function 函数,现在分享给大家,希望可以做个参考。

文章目录

        • 语法
        • 函数的定义
        • 函数的调用
        • 递归调用
      • 多文件调用

语法

复制代码
1
2
3
4
function [automatic] [return_type]name([port_list]); [statements] endfunction

Verilog中的Function函数和C中的函数非常类似,它可以根据你的输入,返回计算的结果,函数的实现只能是组合逻辑,不能包括时间控制,例如#100,可以指定返回值的类型,应该包含至少1个输入,输入只能是input类型,不能是inout或output,只能返回一个值。

当task/function定义为automatic,其变量也是隐式automatic的。 因此,在多次调用task/function时,变量每次都会分配内存并不会覆盖。

函数的定义

支持以下两种定义方式:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
function [7:0] sum; input [7:0] a, b; begin sum = a + b; end endfunction function [7:0] sum (input [7:0] a, b); begin sum = a + b; end endfunction

可以看出,指定函数名称的同时,也生成了一个同名的返回变量。

函数的调用

复制代码
1
2
3
4
5
6
7
8
reg [7:0] result; reg [7:0] a, b; initial begin a = 4; b = 5; #10 result = sum (a, b); end

递归调用

Function可以被自己调用,实现递归操作。下面这个示例是计算阶乘的实现方法:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module tb; initial begin integer result = factorial(4); $display("factorial(4) = %0d", result); end function automatic integer factorial(integer i); integer result = i; // This function is called within the body of this // function with a different argument if (i) begin result = i * factorial(i-1); $display("i=%0d result=%0d", i, result); end else result = 1; return result; endfunction endmodule

仿真结果:

复制代码
1
2
3
4
5
6
7
8
xcelium> run i=1 result=1 i=2 result=2 i=3 result=6 i=4 result=24 factorial(4) = 24 xmsim: *W,RNQUIE: Simulation is complete

多文件调用

声明fun_lib.v文件,内容如下

复制代码
1
2
3
4
5
6
module fun_lib(); //function1; //function2; //function3; endmodule

在另一个top.v文件引用:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
module top( //port declare ); //instance module fun_lib fun_lib_ut0(); always @ () begin // out1 <= fun_lib_ut0.function1(/* param */ ); out2 <= fun_lib_ut0.function2(/* param */); end endmodule

FROM:verilog-functions

最后

以上就是负责盼望最近收集整理的关于Verilog function 函数的全部内容,更多相关Verilog内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部