Erlang进程调用跨模块代码时触发undef错误求助
Erlang进程调用模块函数报错问题解决
错误原因
你遇到的{undef,[{processes,area,[],[]}]}错误,核心原因是**spawn/3调用指定了错误的模块名**:在processes.erl的execute/0函数里,你写了PID = spawn(processes, area, []),但processes模块并没有定义或导出area/0函数——你要启动的是calc模块里的area/0进程,所以模块名应该写calc而不是processes。
修正后的代码
calc.erl(无需修改,保持原代码即可)
-module(calc). -export([start/0, area/0]). -import(io, [fwrite/1]). start() -> % Pid = spawn(fun() -> loop(Args here) end), PID = spawn(calc, area, []), io:fwrite("PID: ~w", [PID]). % PID ! {self(), {rectangle, 10, 20}}, area() -> receive {From , {rectangle, X, Y}} -> From ! {rectangle, X*Y}; {From, {square, X}} -> io:fwrite("in the Square area!"), From ! {square, X*X} end, area().
修正后的processes.erl
-module(processes). -export([execute/0]). -import(io,[fwrite/1]). -import(calc, [area/0]). execute() -> % 修正:spawn指定calc模块的area/0函数 PID = spawn(calc, area, []), % !操作符返回的是发送的消息,不是返回的面积,调整变量名更准确 SentMsg = PID ! {self(), {square, 10}}, receive {rectangle, Area} -> io:fwrite("Rectangle area: ~w~n", [Area]); {square, Area} -> io:fwrite("Square area: ~w~n", [Area]); Other -> io:fwrite("In Other! Received: ~w~n", [Other]) end, io:fwrite("Sent message: ~w~n", [SentMsg]).
额外说明
- 编译模块:确保两个模块都正确编译,在Erlang shell中执行
c(calc).和c(processes). - 运行验证:执行
processes:execute().,会输出类似内容:in the Square area!Square area: 100 Sent message: {<0.80.0>,{square,10}} - 关于
import:import(calc, [area/0])只是让你在模块内可以直接写area()而非calc:area(),但spawn/3必须明确指定模块名,它是基于模块和函数名查找代码的,和import无关。
内容的提问来源于stack exchange,提问作者Rishab Parmar
相关产品推荐
相关产品推荐

