我如何使用 import 或 exref 实现 Erlang 模块间通信

问题描述

我无法导入,因此无法在我的“主”模块中调用一个模块的函数。我是一个 Erlang 新手。下面是我的“主要”模块。

-module('Sysmod').
-author("pato").

%% API
-export([ hello_world/0,sayGoodNight/0]).
-import('Goodnight',[sayGoodNight/0]).

hello_world()->
  io:fwrite("Hello World\n").

下面是正在导入的另一个模块。

-module('Goodnight').
-author("pato").

%% API
-export([sayGoodNight/0]).


sayGoodNight() ->
  io:format("Good night world\n"). 

一旦我导出导入的函数,我什至无法编译我的“主”模块(Sysmod),因为它会抛出一个未定义的 shell 命令 错误。当我导入模块和函数时它会编译,但无法执行该函数并抛出一个 undefined function 错误。我已经查看了 [this answer]1 并查看了 [erlang man pages on code server]2。 此外,我成功地add_path了 Erlang Decimal 库,如下尝试我的应用程序与外部库通信。

12> code:add_path("/home/pato/IdeaProjects/AdminConsole/erlang-decimal-master/ebin").         true

但无法成功运行任何 Decimal 函数,如下所示。

 decimal:add("1.3","1.07").** exception error: undefined function decimal:add/2

简而言之,使用 import 进行模块间通信的第一种方法(我知道由于不可读而不推荐使用)不起作用。在寻找解决方案时,我意识到 add-path 仅适用于具有 ebin 目录的模块。

我卡住了。如何让我的模块相互通信,包括通过 add_path 成功添加的外部库?我听说过 exref,我无法理解 Erlang 手册页。我需要有人像一个五岁的孩子一样向我解释。谢谢。

解决方法

我是一个 Erlang 新手

不要使用import。没有其他人这样做。这是糟糕的编程习惯。相反,通过它们的完全限定名称调用函数,即 moduleName:functionName

抛出一个未定义的函数错误

您没有编译您尝试导入的模块。此外,您不能导出未在模块中定义的函数。

这是一个例子:

~/erlang_programs$ mkdir test1
~/erlang_programs$ cd test1
~/erlang_programs/test1$ m a.erl  %%creates a.erl
~/erlang_programs/test1$ cat a.erl
-module(a).
-compile(export_all).

go()->
    b:hello().

~/erlang_programs/test1$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V9.3  (abort with ^G)
1> c(a).
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}

2> a:go().
** exception error: undefined function b:hello/0
3> 
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
       (v)ersion (k)ill (D)b-tables (d)istribution

~/erlang_programs/test1$ mkdir test2
~/erlang_programs/test1$ cd test2
~/erlang_programs/test1/test2$ m b.erl  %%creates b.erl
~/erlang_programs/test1$ cat b.erl
-module(b).
-compile(export_all).

hello() ->
    io:format("hello~n").

~/erlang_programs/test1/test2$ erlc b.erl
b.erl:2: Warning: export_all flag enabled - all functions will be exported
~/erlang_programs/test1/test2$ ls
b.beam  b.erl

~/erlang_programs/test1/test2$ cd ..
~/erlang_programs/test1$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V9.3  (abort with ^G)
1> c(a).
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}
2> a:go().
** exception error: undefined function b:hello/0
3> code:add_path("./test2").
true
4> a:go().                  
hello
ok

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...