2014-03-27 70 views
1

C文件我有這個代碼在一個我的視圖控制器:如何包括iOS的項目

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

因爲我需要它在更多的地方,我決定做它的功能。 但是我把它當做C函數,老習慣很難死。

現在我有文件WOC_Random.c與此內容

#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 

現在,在我的視圖控制器代碼:

int randomNumber = randomInt(1, 6); 

但我在連接有問題,這是錯誤:

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) 

我對問題有模糊的理解。
但不知道如何解決?
那麼如何解決它,我需要一些參數鏈接器或編譯器?

此外,如果是這樣,當我只是有一些簡單的功能實現是什麼做的iOS發展的最佳途徑,因爲C函數或者是它更好地做到這一點作爲對象C類的功能?

+0

你在WOC_Random.h中有什麼? –

+0

就像你有一個.m和一個用於Objective-C代碼的.h文件一樣,你應該有一個.c和一個.h文件,用於純C代碼(因爲Objective-C只是c的擴展,你可以使它.m和.h文件;這樣,如果你喜歡,你的C代碼也可以調用Objective-C函數)。如果它們屬於類,則應該創建類方法。您不應該創建一個類,以便您可以將C函數作爲類方法使用。 – gnasher729

回答

3

您需要添加頭文件(如WOC_Random.h),其中,你會聲明函數

int randomInt(int startInt, int endInt); 

然後定義在WOC_Random.c該功能。然後在要使用該函數的類中包含WOC_Random.h。