C函数始终向目标C返回零

Ben*_*XVI 1 c xcode objective-c

我有一个Objective C项目,它包含一个带有一些辅助函数的C文件.尝试float从C文件返回s时,我有一个严重且非常恼人的问题.

C档案:

float returnFloat() {
    return 10.0;
}
Run Code Online (Sandbox Code Playgroud)

同时在Objective C实例方法中:

float x;
x = returnFloat();
Run Code Online (Sandbox Code Playgroud)

x始终为0.000000.我有什么想法我做错了吗?

编辑

好的,我已经意识到我在Objective C文件中有一堆"隐式声明"警告,与我在C文件中使用的函数有关.

使用返回ints的函数的赋值工作正常.在从返回a的函数进行赋值的情况下float,调试器会说"由编译器优化掉的变量".

是不是我可能没有使用"正确"的方法在Objective C项目中包含一个包含辅助函数的C文件?我(愚蠢地?)让Xcode自动链接它.即使如此,为什么这个问题只有在函数返回时才会出现float

Jed*_*ith 12

您必须使用.h文件,就像使用.m文件一样,来声明您在另一个文件中执行的操作.所以,你需要这样的场景(这些是不完整的):

returnfloat.c

float returnFloat() {
    return 10.0;
}
Run Code Online (Sandbox Code Playgroud)

returnfloat.h

float returnFloat(void);
Run Code Online (Sandbox Code Playgroud)

usefloat.m

#import "returnfloat.h"

- (void) someMethod {
    float ten = returnFloat();
}
Run Code Online (Sandbox Code Playgroud)

问题(由"隐式声明"警告提供)是编译器假设您正在调用返回intid不是a的东西float.当您使用C时,需要对事物进行原型化(GCC会将.c文件视为C,并且所有C规则都适用,即使您在Objective-C项目中也是如此).


如果你想看一个例子,这是我的一个项目中的东西 - 生产代码(你可以在以.m结尾的文件中编写纯C,GCC会在某些方面将其视为Objective-C):

DebugF.m

#import "DebugF.h"

void __Debug(const char *file, int line, NSString *format, ...) {
#ifdef DEBUG
    /* Wraps NSLog() with printf() style semantics */
#endif
}
Run Code Online (Sandbox Code Playgroud)

DebugF.h

#ifndef __DEBUGF_H_INCLUDED__
#define __DEBUGF_H_INCLUDED__

#ifdef DEBUG
#define DebugF(args...) __Debug(__FILE__, __LINE__, args)
#else
#define DebugF(...)
#endif /* DEBUG */

void __Debug(const char *file, int line, NSString *fmt, ...);

#endif /* __DEBUGF_H_INCLUDED */
Run Code Online (Sandbox Code Playgroud)

SomeViewController.m

DebugF(@"Got these arguments: %u, %@, %@", 4, anObject, [anObject somethingElse]);
Run Code Online (Sandbox Code Playgroud)