你在哪里声明目标c的常数?

时间:2011-05-31 13:55:57

标签: objective-c

我在头文件const double EARTH_RADIUS=6353;中声明了一个常量,该头文件被导入到各种其他头文件中,我收到了一个链接器错误。

Ld /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Products/Debug-iphonesimulator/BadgerNew.app/BadgerNew normal i386
    cd /Users/Teguh/Dropbox/badgers/BadgerNew
    setenv MACOSX_DEPLOYMENT_TARGET 10.6
    setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-g++-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Products/Debug-iphonesimulator -F/Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Products/Debug-iphonesimulator -filelist /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Intermediates/BadgerNew.build/Debug-iphonesimulator/BadgerNew.build/Objects-normal/i386/BadgerNew.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework CoreLocation -framework UIKit -framework Foundation -framework CoreGraphics -framework CoreData -o /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Products/Debug-iphonesimulator/BadgerNew.app/BadgerNew

ld: duplicate symbol _EARTH_RADIUS in /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Intermediates/BadgerNew.build/Debug-iphonesimulator/BadgerNew.build/Objects-normal/i386/NearbyIsiKota.o and /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Intermediates/BadgerNew.build/Debug-iphonesimulator/BadgerNew.build/Objects-normal/i386/FrontPageofBadger.o for architecture i386
collect2: ld returned 1 exit status

基本上我希望常量可用于我项目中的所有类。我应该在哪里宣布它?

4 个答案:

答案 0 :(得分:91)

您可以在标题中声明,在代码文件中定义它。只需将其声明为

即可
extern const double EARTH_RADIUS;

然后在.m文件中的某个地方(通常是你声明的.h的.m)

const double EARTH_RADIUS = 6353;

答案 1 :(得分:63)

有两种方法可以实现这一目标:

第一个选项 - 如先前的回复所述,在.h文件中

myfile.h
extern const int MY_CONSTANT_VARIABLE;

并在myfile.m中定义它们

myfile.m    
const int MY_CONSTANT_VARIABLE = 5;

第二个选项 - 我最喜欢的

myfile.h
static const int MY_CONSTANT_VARIABLE = 5 ;

答案 2 :(得分:4)

源文件中声明它并与其建立外部链接(使用 extern 关键字),以便在所有其他源文件中使用。

答案 3 :(得分:1)

最佳做法是在.h和.m文件中声明它。有关同一问题的详细解答,请参阅Constants in Objective-C

相关问题