Apple Mach O Linker warning

2019-08-05 15:49发布

问题:

I am getting this annoying warning

Apple Mach-O Linker Warning
Alignment lost in merging tentative definition _searchFlag

i have declared the search flag in the constant.h file like this

BOOL searchFlag

I am stuck up on this issue from the past 2 days and i have tried all the possible solutions from google but none of them seems to be working.

My app supports both armv6 and v7 arch for which i have added the settings but this dosent seems to be the problem, its just this bool flag that is biting my head since 2 days.

Please help me out on this Thanks

回答1:

Globals in headers are bad juju in ObjC; I'm not making a judgement on the use of globals (as they truly are sometimes necessary), but I would go about declaring them in a different way.

The cleanest and easiest method I can think of (and my preferred method), is to create a new class that implements accessors for your globals as class methods, and declares the variables themselves as static variables in the source file.

myglobal.h

@interface MyGlobal : Object
{
}

+ (BOOL)searchFlag;
+ (void)setSearchFlag:(BOOL)aFlag;

@end


myglobal.m

#import "myglobal.h"

// Static variables
static BOOL _searchFlag = NO;

@implementation MyGlobal

+ (BOOL)searchFlag
{
    return _searchFlag;
}

+ (void)setSearchFlag:(BOOL)aFlag
{
    _searchFlag = aFlag;
}

@end

Using this method, accessing globals is as easy as [MyGlobal searchFlag] or [MyGlobal setSearchFlag: YES].



回答2:

My guess here is that you are including this header file in multiple source files. As pasted here, that will result in multiple symbols called _searchFlag, one for each inclusion of the header.

The usual pattern here, assuming you're trying to declare a global variable of type BOOL called searchFlag that you can access from multiple source files, would be to declare it in the header with the keyword extern, and then define it in only one source file.

Header file (call it "Foo.h" for example):

extern BOOL searchFlag;

One source file (maybe "Foo.m" for example):

BOOL searchFlag;

Many source/header files:

#import "Foo.h";

By not having the extern you're technically re-declaring it in every source file in which you include/import the header.