从Objective C调用C++方法

14
我有以下文件。
foo.h(C++头文件) foo.mm(C ++文件) test_viewcontroller.h(Objective C头文件) test_viewcontroller.m(Objective C文件)
我在foo.h中声明了一个名为donothing()的方法,并在foo.mm中定义它。它是这样的:
double donothing(double a) { return a; }
现在,我尝试在test_viewcontroller.m中调用此函数:
double var = donothing(somevar);
我得到链接器错误,错误信息为“无法找到符号”_donothing()在test_viewcontroller.o中,collect2:ld返回1个退出状态。
请问有谁能指出问题出在哪里吗?
#ifdef __cplusplus 

extern "C" 
{
      char UTMLetterDesignator(double Lat);
      NSString * LLtoUTM(double Lat,double Long,double UTMNorthing, double UTMEasting);
      double test(double a);
}

#endif

@Carl

我已经包含了我的代码示例。你是在说我只需要将test()方法放在ifdef中吗?我不明白这有什么区别。你能否解释一下?

1个回答

36

test_viewcontroller.m正在寻找非C++符号名称的donothing()。 将其扩展名更改为.mm,你应该就可以了。或者,在编译C++文件时,在foo.h中对方法声明进行extern "C"声明。

你想要它看起来像这样:

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:

#import "foo.h"

- (double)myObjectiveCMethod:(double)x
{
    return donothing(x);
}

1
我尝试添加extern "c",但是我得到了一个新的错误 - "在字符串常量之前需要标识符或'('" - Janani
@whocares,你只需要为C++添加extern "C" - 这意味着将其包装在#ifdef __cplusplus块中。 - Carl Norum
1
@Carl - 非常感谢您的回复!链接器错误已经解决了!!但是我在“test_viewcontroller.m”中得到了一个新的警告 - 函数“donothing()”的隐式声明。我相信只有当我没有包含具有函数声明的头文件时才会发生这种情况,但是我已经在“test_viewcontroller.m”中导入了foo.h。您能告诉我出了什么问题吗? - Janani
2
@whocares,我猜这意味着你的#ifdef块太大了。只将extern "C"放在#ifdef内部,而不是整个函数声明。 - Carl Norum
@Carl - 非常感谢您详细的回复!它像广告一样工作:) 我已经在Stackoverflow注册了!! - Janani
2
@whocares:现在你需要接受答案,因为它解决了你的问题。 - JeremyP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接