【发布时间】:2016-02-09 20:31:53
【问题描述】:
在 C 应用程序中,我有一个 main.c 文件:
#include <stdio.h>
#include "foo.h"
#include "bar.h"
int main(int argc, const char * argv[])
{
foo f;
bar b;
return 0;
}
foo.h(和 foo.c 文件):
#ifndef foo_h
#define foo_h
#include <stdio.h>
#include "bar.h"
#include "utility.h"
typedef struct foo foo;
typedef struct bar bar;
struct foo {
bar * b;
int a;
};
#endif
bar.h(和 bar.c 文件):
#ifndef bar_h
#define bar_h
#include <stdio.h>
#include "foo.h"
typedef struct foo foo;
typedef struct bar bar;
struct bar {
foo * f;
int a;
};
int get_b_a(bar b);
#endif
还有一个utility.h(没有utility.c):
#ifndef utility_h
#define utility_h
int add(int a, int b);
int add(int a, int b)
{
return a + b;
}
#endif
然而,这个程序不会在 xcode 中构建,因为它抱怨链接器问题:
Duplicate symbol _add in bar.o and main.o
我知道我可以通过创建一个单独的 utility.c 文件轻松解决这个问题,但是我不希望这样做,因为它会导致更大的项目中的文件过多。
解决上述问题的最佳实践是什么?
【问题讨论】:
-
这就是为什么我们使用源文件,而不是全头代码...
-
@SouravGhosh 我知道,但这并不总是很方便,例如在一个头文件中构建 API。
-
如果你使用一种语言,你必须遵守它的约定。有些事情是有创意的——这不是其中之一。为什么以及如何使用标题在每本 C 书籍中都有解释。
-
@Olaf 在这种情况下,约定是什么?创建
utility.c?我问是因为我认为可能有另一种方法? -
对不起,堆栈溢出不是一个教程网站。恐怕你真的要读一本书。您需要了解全貌。