简体   繁体   中英

Why do I need an implementation file (.m) when creating project-wide constants?

At the moment I create constants in this way:

// Constants.h
FOUNDATION_EXPORT NSString *const kTestConstant;

// Constants.m
NSString *const kTestConstant = @"TestConstant";

This of course works fine, however I'm puzzled on why I can't just have it all in the header file like this:

NSString *const kTestConstant = @"TestConstant";

If I do that, include Constants.h in various classes and use kTestConstant in those classes, I get redefinition errors at compile time. Why is that?

My theory is that by having a constant only on a header file, the file Constants.h is 'copy-pasted' into the class files that import it, consequently I end up with two copies of kTestConstant. However, by using an implementation file, that file is compiled and linked with the classes that import Constants.h. Is this more or less correct?

Essentially your analysis is correct except for the "modern" concept of "paste". The compilation unit is a concatenation of all header files directly or indirectly included/imported and the implementation file.

As always I recommend obtaining a good "C" language book and studying it, Objective-C is just a thin layer on top of "C". That is what I did years ago, still have the book.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM