[英]Linker issue with header file
在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
文件輕松解決此問題,但是我寧願不utility.c
,因為它會在較大的項目中導致太多文件。
解決上述問題的最佳實踐是什么?
看來問題在於您有太多包含
你不需要
#include "bar.h"
在foo.h中,因為您將其包含在main.c中
發生什么情況是前任將在程序編譯之前將所有內容組合在一起...
...所以發生的是將foo.h和bar.h的一個副本加載到main中,然后在foo.h和bar.h內重新加載了bar.h和foo.h
所以刪除
#include "bar.h"
來自foo.h
並刪除
#include "foo.h"
來自bar.h
看起來好像您對類型的定義太多了
typedef struct foo foo;
這應該只在整個代碼中一次。
評論后編輯...。
您可以在main.c中創建一個等級
#include "foo.h"
並且不包含“ bar.h”
然后在foo.h中,您可以擁有
#include "bar.h"
那么您的程序中將只有foo.h和bar.h的一個副本。 (在bar.h中,您不需要任何#include)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.