Can't have 2 consts with same name in different files? - ios

So this actually makes sense to me, but what I find weird is that this "problem" built without issue for a long time until I went to modify a file.
I have a ViewController class that defines a constant variable lineWidth as
const int lineWidth = 2;
In another class, called GridView, I define the same constant
const int lineWidth = 2;
These are both in the .m files of either class. ViewController.h does import GridView.h.
This caused no issue at all until today when I went to make a modification to GridView.m. The modification had nothing to do with this constant variable; I was merely adding another constructor to the class. When I built the project, I got this error:
Apple Mach-O Linker error: duplicate symbol '_lineWidth' in ViewController.o and GridView.o
I had never seen this error before.
After some trial and error, I was able to get the project to build after changing one of them to nLineWidth. Now I think I figured out that the problem was that I was importing GridView.h from ViewController.h, which then imported ViewController.m and GridView.m, both of which had this constant variable defined, causing an error.
My Question,
however, is why did this build properly up until this point. Is this a new flag that was introduced in XCode 5.1.1? I find it interesting that this wasn't an issue until I started modifying that file. When it needed to rebuild that file, the problem showed up.

Change them both to be:
static const int lineWidth = 2;
This will make each one specific to the file it is defined in. Each can have its own value without affect the other one. Without static they are both declared as app globals and having two with the same name doesn't work.
If you want one shared global then add the following to a .h file:
extern const int lineWidth;
Then add the following to one (corresponding) .m file:
const int lineWidth = 2;
This will create a single global that can be used anywhere by importing the .h file.

Related

How to compile .h file which has struct definition with default values [duplicate]

This question already has an answer here:
Force Header Files to Compile as C++ in Xcode
(1 answer)
Closed 2 years ago.
I'm trying to use a 3rd party sample code as part of my Objective-C application.
However, when trying to compile my project I get a lot of compiler errors.
The objc syntax that is used in the sample is quite strange and I believe that it is compiled as something else within the project.
For example, as part of the header file the struct definition has default values:
File.h
struct Options
{
int count = 100;
}
...
In their project, the above header file would compile just fine, but when I try to compile it I see an Xcode error:
Expected ';' at end of declaration list
I'm not an objective-c expert, but from what I've read and also found as part of other posts data types cannot have default values, but somehow it compiles fine in the Xcode sample app.
Please let me know if you need more info or other examples of what would compile fine in their project and doesn't work when I copy and paste the code into mine.
Edit:
Force Header Files to Compile as C++ in Xcode
Individually header files doesn't compiled. Compiled source files where they included. If you include them in .c they will be compiled like C, if in .m - like Objective-c, if in .cpp - like C++, if in .mm - like Objective-C++.
My issue was that I was using this header file into a .m file which compiles it to an Objective-C standard. When I change the extension to .mm everything worked fine.
When you think of objective-C as actually being C its more clear why defaults are not set in .h files
This does not apply to the rules of default sizes which are needed when no flexible memory allocation for a data type is available by default, like for (as is) most data types in C.
Even this two sentences already show the difficulty to distinguish what is meant with "default".
Which is why you end up with definition of initiation processes and functions to declare what exactly is "default" in the other file.
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int count;
} Options;
typedef struct {
int foo;
Options bar[100];
} Foo;
struct Bar {
Foo lotsof;
}
void MyInitiationFunction(Bar *b);
// definition of MyInitiationFunction in .m/.c file
#ifdef __cplusplus
}
#endif
but there is the concept of enum that can trick your mind where defined enumeration default states are what you build some stuff on, which is not a value.

Header file issue with xcode 7

I have a subclass of NSObject, but I have a problem with header file, when I run the project, it shows me this:
and it allows me to add this, but directly this logical error is returned: "#end must appear in Objective-C context"
I precise that with Xcode6 I didn't have that issue with this Does anyone knows how to fix this frustrating issue ?
EDIT:
that's a constants file, do not pay attention to the file's name, here is .m file:
#import "CUSBoxes.h"
const int defaultCount = 10;
const long int repeat = 25000;
const NSString *defaultDescription = #"If any layout issue is related, change default values of each box you want to display";
#implementation CUSBoxes
#end
Usually this error causes you missed #end or invalid character in one of the .h file you used in your project. I have came across with this error, this error not exist in same files it throws check for other header files to fix this issue.
1) You might missing #end in any of the Header file.Check one by one all .h file which has #interface section,should be ended with "#end".
2) If everything looks good then Try cleaning project or Restart Xcode.(In my case,It worked).

swift failed with exit code 1 while compiling in Xcode - possibly related to Bridging-Headers

I have an Obj-C Project I'm trying to migrate to Swift. I did succeed with various classes but recently ran into an issue I can't seem to make sense of. When I try to compile my current code base I get the following (SUPER UNHELPFUL ERROR MESSAGE)
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
My only assumption is its somehow related to my bridging-headers but Xcode isn't giving me enough information to figure out if this is actually true.
I'm using Cocoapods to add the CorePlot to my project. I'm trying to migrate the following class to Swift:
Obj-C Class (ScatterPlotContainer.h)
#import <Foundation/Foundation.h>
#class CPTScatterPlot;
#interface ScatterPlotContainer : NSObject
#property (nonatomic, strong) CPTScatterPlot *ahrsAlt;
#property (nonatomic, strong) CPTScatterPlot *calibration;
#property (nonatomic, strong) CPTScatterPlot *coreAlt;
#property (nonatomic, strong) CPTScatterPlot *pitch;
#property (nonatomic, strong) CPTScatterPlot *roll;
#property (nonatomic, strong) CPTScatterPlot *slip;
#end
Obj-c Class (ScatterPlotContainer.m)
#import <CorePlot/CPTScatterPlot.h>
#import "ScatterPlotContainer.h"
#implementation ScatterPlotContainer {
}
#end
Swift Conversion
import Foundation
class ScatterPlotContainer : NSObject {
public var ahrsAlt : CPTScatterPlot;
public var calibration : CPTScatterPlot;
public var coreAlt : CPTScatterPlot;
public var pitch : CPTScatterPlot;
public var roll : CPTScatterPlot;
public var slip : CPTScatterPlot;
}
My bridging headers file
#import <CorePlot/CPTScatterPlot.h>
What I've tried thus far
When I comment out the #import <CorePlot/CPTScatterPlot.h> from the Bridging headers file - I get an error in swift because it doesn't know what CPTScatterPlot is
I've also tried #import <CPTScatterPlot.h> which didn't work either.
Thoughts
So the only thing I can think of is perhaps because I'm using a cocoa pod there is some sort of module name I need to add. The error message really isn't that useful. Does anybody have a suggestion about some blaring error I've made or how to get a more descriptive error message to figure out what is going on?
I did the same all answer says but mine issue was not resolved. I did figured out that issue was related to broken function call.
A function syntax was not wrong but its calling mechanism was wrong.
To check the exact error for this issue check following:
Select issue navigator > Click on error will show logs for error > In that select All Messages tab.
This will show all detail logs for this error.
Scroll down and You got logs like, in my case
So, by reading this I figure out that something wrong with function calling. I browse my code and resolved it, Below was correct and wrong code.
Wrong Way:
var region = MKCoordinateRegionMake(self.mapView.userLocation.coordinate, span)
// It will not shown error here but when you build project compiler shows error.
Right Way:
let region = MKCoordinateRegion(center: self.mapView.userLocation.coordinate, span: span)
I run into this last night and nothing above was solving my problem.
I was about to do something very bad at my laptop when I saw, all by pure luck, that ONE (1) file was is text encoding set to UTF-16 ?!?! WTF??
This was the last file I was working on, and probably, one bad cut/paste "import" a strange character into the arena. I did a cut/paste of my code in this file to a bare bone text editor. I deleted the file, recreate it and paste back my code... and voilĂ ! it work.
So do the above, but also check your file encoding! :-)
I had the same error message.
What helped, was to set the optimization level in the swift compiler settings to None.
This is not really a solution for me and I think that's one of the many bugs in the swift compiler.
Another solution for this issues is to check that you don't have 2 or more files with the same file names. It solved the problem for me.
Thank you #Kampai for the advice on going through the error log message. I read through, and some files were missing:
<unknown>:0: error: no such file or directory:
Somehow, some files were removed during a pull from GitHub. The files are in the directory, but not in the Xcode project.
Right click on a folder and click 'Add files to ...' to manually add missing files to Xcode. That fixed the problem for me.
This happened to me several times already, but now I know how to fix it \o/
I was getting the same error for including this code in a didSet block:
didSet {
// Test whether this view is currently visible to the user.
if super.isViewLoaded() && (super.view.window != nil) {
// (build fails even if this block is empty)
}
}
It took a lot of trial/error to hunt this down. Removing super. allowed the build to proceed.
had a horrible time with this bug for over 3 hours by meticulously going from file to file and reverting the changes and seeing if that file had the issue in it. I tried the first answer but didn't give me any answers. Found the issue and it was because I had a non computed property named the same as a computed property of a subclass. I really hope the debugger becomes more robust with handling these sorts of cases in future updates :(
Simply deleting derived data and cleaning helped me
1) Identify the file there the problem is. You can copy and paste the compilation instruction to the console and the last screen will contain the error description. Note the pid number there the problem was identified. Then scroll up and find the pid and related instruction - there will be one file per pid, so you will find the file you have problem it.
2) Look through the file and check all you last changes. If you have git initialized you can use
git diff <file name>
As for #Kampal, I'm still struggling to figure out how much to specify in a function call. For instance, creating a UIColor object sometimes requires that UIColor be specified, and sometimes doesn't.
These both work:
playButton.backgroundColor = .darkGrayColor()
playButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
This yields the exit code 1 error on compilation, without any debugger warning. #time-sucking debug vortex
playButton.setTitleColor(.whiteColor(), forState: UIControlState.Normal)
So I have a new rule: when using a function that takes more than one parameter, be explicit.
Now back to playing swift: AVOID THE VORTEX
Since everyone else has been showing theirs, I'll show mine:
class Foo : UIView {
var pathPosition:Double = 0.0 { didSet {
pathPosition = min(max(0.0, pathPosition), 1.0) // crashes if this line is present
self.pathPosition = min(max(0.0, pathPosition), 1.0) // but not here
}}
}
Incredibly, this does not come up in Playground, but does fail when placed in code in a framework. Although it is legal syntax (used to work, still works in playground), the Swift compiler seems to want pathPosition to be qualified with self.. Note that is (relatively) old code and used to compile, maybe something broke in 6.1.
Edit:
I feel like I am going insane, but it feels like there is a greater complexity problem going on here, where surrounding code can impact this problem. I saw things compile last night, changed some code and settings again today, and it failed on me again. Today, I had to hack in a bunch of really stupid code to get it to work:
var pathPosition:Double = 0.0 { didSet {
// bug: insane!! - have to clobber the value before resetting!
let bugOldValue = pathPosition
self.pathPosition = 1.0 // fails without this nonsensical line!
self.pathPosition = min(max(0.0, bugOldValue), 1.0)
}}
For what it's worth, the actual error message I got, per the helpful instructions above, was:
PHI node has multiple entries for the same basic block with different incoming values!
%14 = phi double [ 1.000000e+00, %10 ], [ %11, %10 ], [ 1.000000e+00, %9 ], [ 0.000000e+00, %9 ], !dbg !4818
label %10
double 1.000000e+00
%11 = phi double [ %7, %entry ], !dbg !4815
LLVM ERROR: Broken function found, compilation aborted!
I'm scared for tomorrow.
I just had this same error, the problem was that I had overridden a method with a non-optional parameter and had made the parameter optional in the override. (the method parameter below)
func logNetworkCallDurationForMethod(method:String, path:String, milliseconds: UInt) {
}
override func logNetworkCallDurationForMethod(method:String?, path:String, milliseconds: UInt) {
}
Ran into this issue today actually. Was the result of a recent pull from git on a project where a file had been deleted, but it didn't update in my local project.
Clicking on the error brought up the location of the "missing" file, went and deleted it's reference in the Project Navigator. Fixed the error, did a clean, and compiled successfully.
This happened to me when trying to reference a method from an inmutable protocol argument(by mistake, I thought the member was a property):
Having an interface as follows:
public protocol NSValidatedUserInterfaceItem {
func tag() -> Int
}
Compilation crash
func validateUserInterfaceItem(anItem: NSValidatedUserInterfaceItem) -> Bool {
print(anItem.tag) // oopsie, tag is a function
return false
}
Compilation success
func validateUserInterfaceItem(anItem: NSValidatedUserInterfaceItem) -> Bool {
print(anItem.tag()) // this is cool for swift
return false
}
This happened to me and after reading the log in issue navigator I found out that I have two swift files with same name. This was creating the issue and I was getting build failed.
I got this error due to a missing file in my project. Added this file again and voila everything worked.
In my case it was wrong method overriding. Base class:
open func send(_ onSuccess: #escaping ((SomeType) -> Void)) -> SomeType { }
Subclass:
open override func send(_ onSuccess: ((SomeType) -> Void)) -> SomeType { }
As you see #escaping is missing. Swift3 converter in XCode8 doesn't consider inheritance relations, moreover, that type mistakes aren't marked as errors.
In My Case it was Simulator bug just uninstall app from simulator and clean project then run project.
I had accidentally dragged symlinks (aliases) to source files into the project instead of the actual files.
I had CoreData generated files twice (and added myself). Check the files are not duplicate.
Unfortunately this error is often caused by a glitch inside Swift's compiler. It is not always easy to find the reason. If cleaning doesn't work, my suggestion is to try to comment the last code you wrote (even the whole file if necessary). Usually commenting the last code you entered would restore the compilation and you'll get more meaningful errors. From there on you have to try to uncomment the code piece by piece until you get to the instruction which caused this error. The Swift compiler is still pretty young and from time to time it reports weird errors. These kind of errors are completely useless, because instead of helping the developers they only confuse them even more. I would suggest Apple to change the compiler to give more detailed information and avoid this annoying error from appearing anymore.
NSString const *kGreenColor = #"#00C34E";
I had above line in my Constant.h file. which was meant for preprocessors only.
Removing that line worked for me.
moving the Bridge file to project level resolve my problem.
In my case I had renamed a file. After committing I found that the file name still hasn't changed in the Xcode project (not sure why), the file was greyed out. Changing the name and committing again did the trick.
So we have to keep an eye out for this error, when making changes to files using source control.
In my case deleted a couple of files directly from SourceTree but their reference was still there in Xcode. Logs show their names. Removed them and error went away.

How to implement the ADLivelyTableView class in a project that uses ARC

I have gone through the ADLivelyTableView demo project but have not been able to import the ADLivelyTableView h and m files into my project successfully. It appears that the main issue is to do with ARC. I have experimented by converting the demo project into arc, specifically but converting just the LDMasterView.m file, and this simply removes all references to releasing objects, and so after this conversion, the use ARC option under build settings is now ON and the app works. So i figured that the ADLivelyTableView .m and .h files dont need converting, but when these are imported into my project, i get all sorts of ARC errors for these two blocks of code:
if (block != _transformBlock) {
Block_release(_transformBlock);
_transformBlock = Block_copy(block);
}
}
and
#implementation ADLivelyTableView
- (void)dealloc {
Block_release(_transformBlock);
[super dealloc];
}
I dont get why these errors didnt show when turning on ARC in the demo project. id prefer finding a solution rather than trying to import my entire application to the demo project instead! The errors are as follows:
ARC Casting Rules: Cast of block pointer type 'ADLivelyTransform (aka NSTimeINterval (^)CALayer*_strong, float) to C pointer type 'const void *' required a bridged cast.
ARC Casting Rules: Cast of C Pointer ....(Same as above)
Also, once this issue is resolved, it is supposed to be as simple as just importing the ADLivelyTableView .h and .m files and then adding the line :
ADLivelyTableView * livelyTableView = (ADLivelyTableView *)self.tableView;
livelyTableView.initialCellTransformBlock = ADLivelyTransformFan;
into my viewDidLoad section? or is that bit supposed to be edited for my specific table?
Thanks for your help,
Regards,
Rami
You can modify the Compiler Flags for ADLivelyTableView.m.
Kindly try to add -fno-objc-arc.

'Undeclared Identifier' error with defined constants

My defined constants are giving me 'undeclared identifier' issues. I have them in a Constants.h file that I am including in my .pch file. I thought it might be something with my .pch file, however, if I delete it from there and try #import it in one of the classes where I need one of the constants, then I still get an 'undeclared identifier' error.
If I take each #define line and put them at the top of the .m class file directly, they work. So my syntax is correct.
So it's something with the .h file itself, but I have no idea what.
//
// Constants.h
// Sliding Drawer
#define kOffscreenX 320 // X coord when Sliding Drawer is offscreen
#define kVisibleX 40 // X coord when Sliding Drawer is visible
// WordlistButton
#define kNumScores 3
// Fonts
#define kMessageFontSize 14
#define kScoreFontSize 10
It's impossible to see the error only from this piece of code. Preprocessor tends to create very messy things, especially when there are circular imports involved.
You can try to delete the current compiled version of the header, note it's not in the derived data folder, it's in XCode's cache (see Project -> Build Setttings -> Precompiled Headers Cache Path).
However, if you have tried to import Constants.h directly and it didn't work, the problem may be somewhere else.
Are you sure there is only 1 file called Constants.h? Note you should use a prefix for your files (e.g. SAConstants.h if Smooth Almonds is your name) to avoid collision with Apple's headers or headers of the libraries you are using.
If you import the header directly, go to the .m file and tap on Product -> Generate Output -> Preprocessed File and find Constants.h import in it. Is it your header?
By the way, there is a nice article about avoiding this kind of things in precompiled headers http://qualitycoding.org/precompiled-headers/
I found this thread due to an other error upper case parameter in my define statement. I solved it for my issue with lower casing:
#define MSB(BTvalue) ((uint8_t) (BTvalue >> 8)) //threw this error
changing BTvalue to just value with lowercase parameter made me happy
#define MSB(value) ((uint8_t) (value >> 8))

Resources