从目标C调用C ++方法 [英] Calling C++ method from Objective C
问题描述
我有以下文件.
foo.h(C ++头文件)
foo.mm(C ++文件)
test_viewcontroller.h(目标c头文件)
test_viewcontroller.m(目标c文件)
foo.h (C++ header file)
foo.mm (C++ file)
test_viewcontroller.h (objective c header file)
test_viewcontroller.m (Objective c file)
我在foo.h中声明了一个donothing()方法并在foo.mm中定义了它.
I have declared a method donothing() in foo.h and defined it in foo.mm.Lets say it is
双牙(双a) { 返回 }
double donothing(double a) { return a; }
现在,我尝试在test_viewcontroller.m中调用此函数
Now,I try to call this function in test_viewcontroller.m
double var = donothing(somevar);
double var = donothing(somevar);
我在test_viewcontroller.o中收到链接器错误,提示找不到符号" _donothing().
collect2:ld返回了1个退出状态
I get linker error which says "cannot find symbols" _donothing() in test_viewcontroller.o
collect2: ld returned 1 exit status
有人可以指出什么错吗?
Can anyone please point me as to what is wrong?
让我说清楚:
#ifdef __cplusplus
extern "C"
{
char UTMLetterDesignator(double Lat);
NSString * LLtoUTM(double Lat,double Long,double UTMNorthing, double UTMEasting);
double test(double a);
}
#endif
@卡尔
我已经包含了我的代码示例.是说我只需要将test()方法包装到ifdef中.我不知道它可以产生什么变化.您能解释一下吗?
I have included my code sample.Are saying that I need to wrap only the test() method in ifdef.I dont understand what difference it can make.Can you please explain?
推荐答案
test_viewcontroller.m
正在寻找donothing()
的非C ++混合符号名称.将其扩展名更改为.mm
,您应该会很好.或者,在编译C ++文件时,将extern "C"
声明放在foo.h
中的方法声明上.
test_viewcontroller.m
is looking for a non-C++-mangled symbol name for donothing()
. Change its extension to .mm
and you should be good. Alternately, put an extern "C"
declaration on your method declaration in foo.h
when compiling the C++ file.
您要使它看起来像这样:
You want to have it look like this:
foo.h:
#ifdef __cplusplus
extern "C" {
#endif
double donothing(double a);
#ifdef __cplusplus
}
#endif
foo.mm:
#include "foo.h"
double donothing(double a)
{
return a;
}
test_viewcontroller.m:
test_viewcontroller.m:
#import "foo.h"
- (double)myObjectiveCMethod:(double)x
{
return donothing(x);
}
这篇关于从目标C调用C ++方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!