2

I had this code in one my view controller:

int randomNumber =  (arc4random() % 1) + 6;

Because I will need it on more places, I decided to made it as function. But I did it as C function, old habits die hard.

Now I have file WOC_Random.c with this content

#include <stdio.h>
#include <stdlib.h> // for arc4random() function

#ifndef WOC_Random_C
#define WOC_Random_C


int randomInt(int startInt, int endInt)
{
    int randomNumber =  (arc4random() % startInt) + endInt;

    return randomNumber;
}

#endif

Now code in my view controller is:

int randomNumber =  randomInt(1, 6);

But I have problem in linking, this is error:

duplicate symbol _randomInt in:
/Users/Mac/Library/Developer/Xcode/DerivedData/GuessTheNumber-gjovdrsarctubnbqhczqukvahwgb/Build/Intermediates/GuessTheNumber.build/Debug-iphonesimulator/GuessTheNumber.build/Objects-normal/i386/GTN_FirstViewController.o
/Users/Mac/Library/Developer/Xcode/DerivedData/GuessTheNumber-gjovdrsarctubnbqhczqukvahwgb/Build/Intermediates/GuessTheNumber.build/Debug-iphonesimulator/GuessTheNumber.build/Objects-normal/i386/WOC_Random.o
ld: 1 duplicate symbol for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I do have vague understanding, of problem.
But do not know how to fixit ?
So how to fix it, do I need some argument to linker or compiler ?

Also, in case like this when I just have some simple function to implement what is the best way to do it for iOS development, as C function or is it better to do it as class function in Object C ?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
WebOrCode
  • 6,852
  • 9
  • 43
  • 70
  • What do you have in WOC_Random.h? – Mike Pollard Mar 27 '14 at 12:47
  • Just as you have a .m and a .h file for Objective-C code, you should have a .c and a .h file for plain C code (since Objective-C is just an extension to c, you can make it a .m and .h file; that way your C code can call Objective-C functions as well if you like). You should create class methods if they really belong to the class. You shouldn't create a class just so that you can put C functions there as class methods. – gnasher729 Mar 27 '14 at 13:43

1 Answers1

4

You need to add Header file (like WOC_Random.h) in which you will declare the function

int randomInt(int startInt, int endInt);

Then define that function in WOC_Random.c. And then include WOC_Random.h in the class you want to use the function.

Amir iDev
  • 1,257
  • 2
  • 15
  • 29