Defining a static member in objective-C and objective-C ++

I have a difference when compiling the source of objective-c and objective-c ++.

Here's the declaration of Class1 and Class2 in test.h:

#import <Foundation/Foundation.h> @interface Class1 { } @end @interface Class2 { } @end 

Now this is the implementation of objective-c in test.m:

 #import "test.h" @implementation Class1 /* static member */ static int mystatic; @end @implementation Class2 /* static member */ static int mystatic; @end 

I will successfully compile this command:

 gcc -arch armv6 -isysroot /Developer/.../iPhoneOS5.0.sdk -x objective-c -c test.m 

Now I use this exact-c ++. Mm test (exactly the same source):

 #import "test.h" @implementation Class1 /* static member */ static int mystatic; @end @implementation Class2 /* static member */ static int mystatic; @end 

And compile this command line (the difference is in the -x option):

 gcc -arch armv6 -isysroot /Developer/.../iPhoneOS5.0.sdk -x objective-c++ -c test.mm 

But I get an error message:

 test.mm:11 error: redefinition if 'int mystatic' 

Why am I getting this error in ObjC ++ and not in ObjC?

+6
source share
1 answer

It comes down to the difference between C and C ++. In C, it is normal to override a static variable with the same name and the same type; in C ++, the same thing happens with an error.

From standard C:

The declaration of an identifier for an object having a scope without an initializer, and without a storage class specifier or with a static storage class specifier is a preliminary definition. If the translation unit contains one or more preliminary definitions for the identifier, and the translation unit does not contain external definitions for this identifier, then the behavior is exactly the same as if the translation unit contained the declaration of the scope of this identifier, a composite type at the end of the translation unit, and the initializer equal to 0.

From the C ++ standard:

C.1.2, 3.1 Change: C ++ does not have “preliminary definitions” as in C. For example, in scope,

 int i ; int i ; 

valid in C, but it is not valid in C ++.

As for Objective-C, the language does not support class-level variables; static int mystatic; inside the @implementation block has the same effect as declaring outside the @implementation block. To emulate class variables, use static variables with a function inside class methods.

+6
source

Source: https://habr.com/ru/post/919764/


All Articles