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



我不能导入,因此不能在我的'主'模块中调用另一个模块的函数。我是一个Erlang新手。下面是我的'main'模块。

-module('Sysmod').
-author("pato").
%% API
-export([ hello_world/0,sayGoodNight/0]).
-import('Goodnight',[sayGoodNight/0]).
hello_world()->
io:fwrite("Hello Worldn").

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

-module('Goodnight').
-author("pato").
%% API
-export([sayGoodNight/0]).

sayGoodNight() ->
io:format("Good night worldn"). 

我甚至不能编译我的'main'模块(Sysmod),一旦我导出导入的函数,因为它抛出一个未定义的shell命令错误。当我导入模块和函数时,它会编译,但不能执行函数,并抛出未定义函数错误。我已经查看了[这个答案]1,也查看了[代码服务器上的erlang手册页]2。此外,我成功地使用了Erlang Decimal库的add_path,如下所示,尝试我的应用程序与外部库进行通信。

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

最新更新