You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:01:30