从Objective C调用C++方法

Jan*_*ani 14 iphone objective-c linker-errors

我有以下文件.

foo.h(C++头文件)
foo.mm(C++文件)
test_viewcontroller.h(目标c头文件)
test_viewcontroller.m(目标c文件)

我已经在foo.h中声明了一个方法donothing()并在foo.mm中定义它.让我们说它是

双重承诺(双倍){返回; }

现在,我尝试在test_viewcontroller.m中调用此函数

double var = donothing(somevar);

我在test_viewcontroller.o中获得链接器错误,其中显示"找不到符号"_donothing().
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
Run Code Online (Sandbox Code Playgroud)

@Carl

我已经包含了我的代码示例.我说我需要在ifdef中只包装test()方法.我不明白它可以有什么区别.你能解释一下吗?

Car*_*rum 35

test_viewcontroller.m正在寻找一个非C++ - 受损的符号名称donothing().将其扩展名更改为.mm,您应该是好的.或者,extern "C"foo.h编译C++文件时,在方法声明中声明一个声明.

你想让它看起来像这样:

foo.h中:

#ifdef __cplusplus
extern "C" {
#endif

double donothing(double a);

#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

foo.mm:

#include "foo.h"

double donothing(double a)
{
    return a;
}
Run Code Online (Sandbox Code Playgroud)

test_viewcontroller.m:

#import "foo.h"

- (double)myObjectiveCMethod:(double)x
{
    return donothing(x);
}
Run Code Online (Sandbox Code Playgroud)

  • @whocares,我猜这意味着你的`#ifdef`块太大了.在*#ifdef`中放入*just*`extern"C"`,而不是整个函数声明. (2认同)
  • @whocares:现在你需要接受答案,因为它解决了你的问题. (2认同)