2017-04-13 68 views
0

我想使用那些用C寫的一些功能,但是我收到以下錯誤消息時:重複的符號錯誤鏈接C代碼

duplicate symbol _getInt in: 
    /Users/<redacted>/Library/Developer/Xcode/DerivedData/Test-ecbrpcljzanjildnvawnrcgejdwn/Build/Intermediates/Test.build/Debug-iphonesimulator/Test.build/Objects-normal/x86_64/source.o 
    /Users/<redacted>/Library/Developer/Xcode/DerivedData/Test-ecbrpcljzanjildnvawnrcgejdwn/Build/Intermediates/Test.build/Debug-iphonesimulator/Test.build/Objects-normal/x86_64/swift.o 
    ld: 1 duplicate symbol for architecture x86_64 
    clang: error: linker command failed with exit code 1 (use -v to see invocation) 

swift.swift:

print(getInt()) 

header.h:

#ifndef header_h_ 
#define header_h_ 
#include "source.c" 
#endif 

由source.c:

int getInt() { 
    return 4; 
} 

這些都是我的橋接頭設置 enter image description here

+0

爲什麼在.h文件中包含.c文件? – rmaddy

回答

1

你的頭不應該包括.c文件。

.c文件應包含.h文件。

每個.c文件是它自己的「編譯單元」。編譯器分別編譯所有編譯單元。您可以在source.c中包含source.h,以便頭文件用於在編譯單元中提供函數實現的前向聲明。

如果您在source.hsource.c,那麼包括source.h(包括source.c)每個編譯單元將獲得自己在source.c定義的實現的副本。這意味着會有多個相同事物的定義,並且編譯器不知道選擇哪一個。這就是爲什麼你會得到這個「重複」的符號錯誤。我懷疑swift.csource.c包括source.h

+0

謝謝。這解決了問題! –