OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 iOS 项目中包含 C 文件 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 07:24
标题: ios - 如何在 iOS 项目中包含 C 文件

我的 View Controller 中有这段代码:

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

现在我的 View Controller 中的代码是:

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 函数还是在 Object C 中作为类函数更好?



Best Answer-推荐答案


您需要添加头文件(如 WOC_Random.h),您将在其中声明函数

int randomInt(int startInt, int endInt);

然后在 WOC_Random.c 中定义该函数。然后在要使用该函数的类中包含WOC_Random.h。

关于ios - 如何在 iOS 项目中包含 C 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22687738/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4