界面像c语言吗?

Interface like in c language?

我想创建一个程序,它使用一个结构和围绕这个结构的函数,例如一棵树。

界面会是这样的:

typedef struct _trie *Trie;

void foo1(Trie trie);
int foo2(Trie trie);
...

我想为此创建两个实现,它们将在以下文件中:

第三个使用接口的文件:

objective是编译use_trie.c两次,一次使用second_trie.h,另一次使用first_trie.h.

如何防止use_trie抱怨不知道Trie? 如何构建一个构建两次 use_trie 的 makefile,这些差异 headers?

如果 use_foo.c 仅使用 public 接口中接受指针的函数(并且它永远不需要取消引用其中一个指针),则不需要了解内部结构.类型声明就足够了。这称为 opaque pointer.

您需要一个 header、trie.h,供以下人员使用:

  • first_trie.c — 因此它可以定义与其中定义的 public 接口相匹配的函数。
  • second_trie.c — 因此它可以定义与其中定义的 public 接口相匹配的函数。
  • use_trie.c — 因此它可以使用其中定义的 public 接口声明的函数。

除非 trie 代码太大以至于需要跨越多个源文件,否则您不需要(或不想)first_trie.hsecond_trie.htrie.h 中的单一通用定义可以完成这项工作。实际 trie 结构的内部细节完全保存在实现每个 trie 的源文件中。

如评论中所述:

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.

您使用 struct _trie 如履薄冰。不过,你会和很多其他人在一起;人们经常滥用这些规则。

  • 谨慎使用 typedef 作为指针。有关详细讨论,请参阅 Is it a good idea to typedef pointers

    请注意,您通常应将 FILE 视为不透明类型,但您始终声明 FILE *fp

makefile 应该不会有太大问题。 bare-bones 大纲可以像这样简单:

TRIE1.c = first_trie.c
TRIE2.c = second_trie.c
PROG.c  = use_trie.c
TRIE1.o = ${TRIE1.c:.c=.o}
TRIE2.o = ${TRIE2.c:.c=.o}
PROG.o  = ${PROG.c:.c=.o}

PROG1 = use_trie1
PROG2 = use_trie2

all: ${PROG1} ${PROG2}

${PROG1}: ${PROG.o} ${TRIE1.o}
    ${CC} -o $@ ${CFLAGS} ${PROG.o} ${TRIE1.o} ${LDFLAGS} ${LDLIBS}

${PROG2}: ${PROG.o} ${TRIE2.o}
    ${CC} -o $@ ${CFLAGS} ${PROG.o} ${TRIE2.o} ${LDFLAGS} ${LDLIBS}

您可能想添加规则告诉 Make header 也很重要:

TRIE.h = trie.h

${TRIE1.o}: trie.h
${TRIE2.o}: trie.h
${PROG.o}:  trie.h

您不一定需要将源文件添加到依赖列表;这样做是完整的,但不是必须的。

请注意,将 first_trie.osecond_trie.o 都放在一个库中不是一个好主意。无法确定两个 object 文件中的哪一个是用任何给定程序 link 编辑的。它甚至不需要是一直 linked 的同一个文件(尽管它可能是)。您将需要单独的库 — 或者将 object 文件与您要使用的文件明确分开 link。