Where do you declare a constant in Objective-C?

后端 未结 4 1608
故里飘歌
故里飘歌 2020-12-07 18:54

I declared a constant in a header file const double EARTH_RADIUS=6353; that is imported to various other headers and I got a linker error.

L         


        
相关标签:
4条回答
  • 2020-12-07 19:09

    There are two ways to accomplish this:

    1st option- As previous replies pointed, in the .h file:

    myfile.h
    extern const int MY_CONSTANT_VARIABLE;
    

    and in myfile.m define them

    myfile.m    
    const int MY_CONSTANT_VARIABLE = 5;
    

    2nd option- My favourite:

    myfile.h
    static const int MY_CONSTANT_VARIABLE = 5 ;
    
    0 讨论(0)
  • 2020-12-07 19:14

    Declare it in a source file and have external linkage to it( using extern keyword ) so as to use in all other source files.

    0 讨论(0)
  • 2020-12-07 19:19

    Best practice would be to declare it in your .h and .m files. See Constants in Objective-C for a very detailed set of answers regarding this same question.

    0 讨论(0)
  • 2020-12-07 19:30

    You can declare in the header, define it in a code file. Simply declare it as

    extern const double EARTH_RADIUS;
    

    then in a .m file somewhere (usually the .m for the .h you declared it in)

    const double EARTH_RADIUS = 6353;
    
    0 讨论(0)
提交回复
热议问题