Erlang與C語言的頭文件對比
Erlang中頭文件的定義:
record.hrl:
%% this is a record.hrl (header) file.
-ifndef(record).
-define(record,true).
-record(person, {name,
type=industrial,
hobbies,
details=[]}).
-endif.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
test.erl:
%%
%% Exported Functions
%%
-include("record.hrl").
-export([getName/1]).
%%
%% API Functions
%%
getName(Name) ->
Person = #person{name=Name, hobbies=["Crushing people","petting cats"]},
Person#person.name.
=================================================================
c語言中頭文件:
person.h
#ifndef PERSON_H
#define PERSON_H
typedef struct Person{
char name[20];
char type[20];
char hobbies[20];
char details[20];
} Person;
#endif
###############################################################################
test.c
#include<stdio.h>
#include "person.h"
int main(void)
{
char c;
Person p = {"li", "type", "hobbies", "detail"};
printf("%s",p.name);
scanf("%c", &c);
}
上面的例子是在頭文件定義了一個記錄或者結構體,然後在源程序中引用了這個記錄或者結構體。
爲了看懂上面的例子我做幾點對比說明:
預處理對比
C |
Erlang |
|
包含 |
#include<""> #include"" 不能是路徑 |
-include(File) File可以是絕對和相對路徑 |
宏 |
#define 分爲有參和無參 引用時,直接引用 |
-define(Const, Replacement), -define(Func(Var1, VarN), Replacement),引用時用?Const 或?Func(Var2, VarN) |
條件編譯 |
#ifdef #else #endif |
-ifdef(Macro) -ifndef(Macro) -else -endif. |
看出Erlang和C語言的預處理還是很相似的,最大的不同在於#和-, 其它在用法上有些小的區別,多注意下就好了。