Verilog function 函数

语法
function [automatic] [return_type]name([port_list]);
    [statements]
endfunction

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

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

函数的定义

支持以下两种定义方式:

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

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

函数的调用
reg [7:0] result;
reg [7:0] a, b;

initial begin
    a = 4;
    b = 5;
    #10 result = sum (a, b);
end
递归调用

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

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

仿真结果:

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文件,内容如下

module fun_lib();
	//function1;	
	//function2;
	//function3;
endmodule

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

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

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

whik1194

如果对你有帮助,欢迎打赏。谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值