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

use*_*951 50 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
Run Code Online (Sandbox Code Playgroud)

基本上我希望常量可用于我项目中的所有类.我应该在哪里申报?

Dan*_*n F 92

您可以在标题中声明,在代码文件中定义它.简单地声明为

extern const double EARTH_RADIUS;
Run Code Online (Sandbox Code Playgroud)

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

const double EARTH_RADIUS = 6353;
Run Code Online (Sandbox Code Playgroud)

  • 标题中的`extern`允许其他文件知道你的常量.如果只需要单个文件范围的常量,那么`extern`就不是必需的. (4认同)
  • @kraftydevil在技术上并不重要,但惯例是在`#import`s之后和`@ implementation`之前执行.但实际上文件的全局范围内的任何地方都很好(意思是只要它不在任何花括号`{}`里面 (3认同)

spa*_*ker 63

有两种方法可以实现此目的:

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

myfile.h
extern const int MY_CONSTANT_VARIABLE;
Run Code Online (Sandbox Code Playgroud)

并在myfile.m中定义它们

myfile.m    
const int MY_CONSTANT_VARIABLE = 5;
Run Code Online (Sandbox Code Playgroud)

第二个选项 - 我最喜欢的:

myfile.h
static const int MY_CONSTANT_VARIABLE = 5 ;
Run Code Online (Sandbox Code Playgroud)

  • 它可以工作,但前提是你需要一个非全局常量.静态常量在文件外部不可见.否则使用第一个选项. (8认同)